From 40470ad6bcb1f051ed827446f05aeed7ae0e944a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Fri, 31 Aug 2018 16:45:25 +0800 Subject: [PATCH 001/262] fix lookup regression again and again --- src/compiler/checker.ts | 4 +++- ...arameterInitializersForwardReferencing1_es6.errors.txt | 5 ++++- .../parameterInitializersForwardReferencing1_es6.symbols | 2 +- .../parameterInitializersForwardReferencing1_es6.types | 8 ++++---- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ebd849a7844..3ee631eb273 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1213,7 +1213,9 @@ namespace ts { } if (meaning & SymbolFlags.Value && result.flags & SymbolFlags.Variable) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - if (compilerOptions.target && compilerOptions.target >= ScriptTarget.ES2015 && isParameter(lastLocation) && !isParameterPropertyDeclaration(lastLocation) && result.valueDeclaration.pos > lastLocation.end) { + const functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= ScriptTarget.ES2015 && isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { useResult = false; } else if (result.flags & SymbolFlags.FunctionScopedVariable) { diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt index 90390fbe3a4..59280d2006a 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt @@ -1,8 +1,9 @@ +tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(13,20): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(21,18): error TS2372: Parameter 'a' cannot be referenced in its initializer. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(25,22): error TS2372: Parameter 'async' cannot be referenced in its initializer. -==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts (2 errors) ==== +==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts (3 errors) ==== let foo: string = ""; function f1 (bar = foo) { // unexpected compiler error; works at runtime @@ -16,6 +17,8 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.t } function f3 (bar = foo, foo = 2) { // correct compiler error, error at runtime + ~~~ +!!! error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. return bar; } diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols index c0d42ab8b11..dcd204beb7b 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols @@ -31,7 +31,7 @@ function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at function f3 (bar = foo, foo = 2) { // correct compiler error, error at runtime >f3 : Symbol(f3, Decl(parameterInitializersForwardReferencing1_es6.ts, 10, 1)) >bar : Symbol(bar, Decl(parameterInitializersForwardReferencing1_es6.ts, 12, 13)) ->foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 0, 3)) +>foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 12, 23)) >foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 12, 23)) return bar; diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types index 009ec47ddb8..8fc5d84ae8e 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types @@ -34,14 +34,14 @@ function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at } function f3 (bar = foo, foo = 2) { // correct compiler error, error at runtime ->f3 : (bar?: string, foo?: number) => string ->bar : string ->foo : string +>f3 : (bar?: number, foo?: number) => number +>bar : number +>foo : number >foo : number >2 : 2 return bar; ->bar : string +>bar : number } function f4 (foo, bar = foo) { From eb7fbdc4eba97954d9441e39b6e340d6a37a1e37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Mon, 3 Sep 2018 16:37:34 +0800 Subject: [PATCH 002/262] update baseline --- ...ializersForwardReferencing1_es6.errors.txt | 8 ------ ...nitializersForwardReferencing1_es6.symbols | 6 ++--- ...rInitializersForwardReferencing1_es6.types | 26 +++++++++---------- 3 files changed, 16 insertions(+), 24 deletions(-) diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt index 18823284b91..59280d2006a 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt @@ -1,22 +1,17 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(13,20): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(21,18): error TS2372: Parameter 'a' cannot be referenced in its initializer. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(25,22): error TS2372: Parameter 'async' cannot be referenced in its initializer. -tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(29,15): error TS2448: Block-scoped variable 'foo' used before its declaration. ==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts (3 errors) ==== let foo: string = ""; function f1 (bar = foo) { // unexpected compiler error; works at runtime - ~~~ -!!! error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. var foo: number = 2; return bar; // returns 1 } function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at runtime - ~~~ -!!! error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. var foo: number = 2; return bar(); // returns 1 } @@ -44,9 +39,6 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.t } function f7({[foo]: bar}: any[]) { - ~~~ -!!! error TS2448: Block-scoped variable 'foo' used before its declaration. -!!! related TS2728 tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts:30:9: 'foo' is declared here. let foo: number = 2; } diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols index b44c91e8afd..dcd204beb7b 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.symbols @@ -5,7 +5,7 @@ let foo: string = ""; function f1 (bar = foo) { // unexpected compiler error; works at runtime >f1 : Symbol(f1, Decl(parameterInitializersForwardReferencing1_es6.ts, 0, 21)) >bar : Symbol(bar, Decl(parameterInitializersForwardReferencing1_es6.ts, 2, 13)) ->foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 3, 7)) +>foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 0, 3)) var foo: number = 2; >foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 3, 7)) @@ -18,7 +18,7 @@ function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at >f2 : Symbol(f2, Decl(parameterInitializersForwardReferencing1_es6.ts, 5, 1)) >bar : Symbol(bar, Decl(parameterInitializersForwardReferencing1_es6.ts, 7, 13)) >baz : Symbol(baz, Decl(parameterInitializersForwardReferencing1_es6.ts, 7, 20)) ->foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 8, 7)) +>foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 0, 3)) >baz : Symbol(baz, Decl(parameterInitializersForwardReferencing1_es6.ts, 7, 20)) var foo: number = 2; @@ -68,7 +68,7 @@ function f6 (async = async) { function f7({[foo]: bar}: any[]) { >f7 : Symbol(f7, Decl(parameterInitializersForwardReferencing1_es6.ts, 26, 1)) ->foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 29, 7)) +>foo : Symbol(foo, Decl(parameterInitializersForwardReferencing1_es6.ts, 0, 3)) >bar : Symbol(bar, Decl(parameterInitializersForwardReferencing1_es6.ts, 28, 13)) let foo: number = 2; diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types index a58d19c5755..8fc5d84ae8e 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.types @@ -4,33 +4,33 @@ let foo: string = ""; >"" : "" function f1 (bar = foo) { // unexpected compiler error; works at runtime ->f1 : (bar?: number) => number ->bar : number ->foo : number +>f1 : (bar?: string) => string +>bar : string +>foo : string var foo: number = 2; >foo : number >2 : 2 return bar; // returns 1 ->bar : number +>bar : string } function f2 (bar = (baz = foo) => baz) { // unexpected compiler error; works at runtime ->f2 : (bar?: (baz?: number) => number) => number ->bar : (baz?: number) => number ->(baz = foo) => baz : (baz?: number) => number ->baz : number ->foo : number ->baz : number +>f2 : (bar?: (baz?: string) => string) => string +>bar : (baz?: string) => string +>(baz = foo) => baz : (baz?: string) => string +>baz : string +>foo : string +>baz : string var foo: number = 2; >foo : number >2 : 2 return bar(); // returns 1 ->bar() : number ->bar : (baz?: number) => number +>bar() : string +>bar : (baz?: string) => string } function f3 (bar = foo, foo = 2) { // correct compiler error, error at runtime @@ -74,7 +74,7 @@ function f6 (async = async) { function f7({[foo]: bar}: any[]) { >f7 : ({ [foo]: bar }: any[]) => void ->foo : number +>foo : string >bar : any let foo: number = 2; From 342fda98d8817276f7fc0d020c31a9e7c1297165 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 3 Oct 2018 10:49:24 +0100 Subject: [PATCH 003/262] Allow trailing void arguments to be omitted --- src/compiler/checker.ts | 17 +- .../reference/callWithMissingVoid.errors.txt | 131 ++++++++ .../reference/callWithMissingVoid.js | 140 ++++++++ .../reference/callWithMissingVoid.symbols | 231 +++++++++++++ .../reference/callWithMissingVoid.types | 312 ++++++++++++++++++ .../functionCalls/callWithMissingVoid.ts | 85 +++++ 6 files changed, 914 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/callWithMissingVoid.errors.txt create mode 100644 tests/baselines/reference/callWithMissingVoid.js create mode 100644 tests/baselines/reference/callWithMissingVoid.symbols create mode 100644 tests/baselines/reference/callWithMissingVoid.types create mode 100644 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 82480428790..941a8b384f1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19076,6 +19076,10 @@ namespace ts { return findIndex(args, isSpreadArgument); } + function acceptsVoid(t: Type): boolean { + return !!(t.flags & TypeFlags.Void); + } + function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { if (isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". @@ -19130,8 +19134,17 @@ namespace ts { } // If the call is incomplete, we should skip the lower bound check. - const hasEnoughArguments = argCount >= getMinArgumentCount(signature); - return callIsIncomplete || hasEnoughArguments; + const minArgs = getMinArgumentCount(signature); + if (callIsIncomplete || argCount >= minArgs) { + return true; + } + for (let i = argCount; i < minArgs; i++) { + const type = getTypeAtPosition(signature, i); + if (filterType(type, acceptsVoid).flags & TypeFlags.Never) { + return false; + } + } + return true; } function hasCorrectTypeArgumentArity(signature: Signature, typeArguments: NodeArray | undefined) { diff --git a/tests/baselines/reference/callWithMissingVoid.errors.txt b/tests/baselines/reference/callWithMissingVoid.errors.txt new file mode 100644 index 00000000000..7ad2a481f2e --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.errors.txt @@ -0,0 +1,131 @@ +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(16,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(19,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(22,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(35,31): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(36,35): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(37,33): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(48,1): error TS2554: Expected 3 arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(55,1): error TS2554: Expected 4 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(56,1): error TS2554: Expected 4 arguments, but got 3. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(57,1): error TS2554: Expected 4 arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(75,1): error TS2554: Expected 3 arguments, but got 1. + + +==== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts (11 errors) ==== + // From #4260 + class X { + f(t: T) { + return { a: t }; + } + } + + declare const x: X; + x.f() // no error because f expects void + + declare const xUnion: X; + xUnion.f(42) // no error because f accepts number + xUnion.f() // no error because f accepts void + + declare const xAny: X; + xAny.f() // error, any still expects an argument + ~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + declare const xUnknown: X; + xUnknown.f() // error, unknown still expects an argument + ~~~~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + declare const xNever: X; + xNever.f() // error, never still expects an argument + ~~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + + // Promise has previously been updated to work without arguments, but to show this fixes the issue too. + + class MyPromise { + constructor(executor: (resolve: (value: X) => void) => void) { + + } + } + + new MyPromise(resolve => resolve()); // no error + new MyPromise(resolve => resolve()); // no error + new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + + + // Multiple parameters + + function a(x: number, y: string, z: void): void { + + } + + a(4, "hello"); // ok + a(4, "hello", void 0); // ok + a(4); // not ok + ~~~~ +!!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:42:23: An argument for 'y' was not provided. + + function b(x: number, y: string, z: void, what: number): void { + + } + + b(4, "hello", void 0, 2); // ok + b(4, "hello"); // not ok + ~~~~~~~~~~~~~ +!!! error TS2554: Expected 4 arguments, but got 2. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:34: An argument for 'z' was not provided. + b(4, "hello", void 0); // not ok + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 4 arguments, but got 3. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:43: An argument for 'what' was not provided. + b(4); // not ok + ~~~~ +!!! error TS2554: Expected 4 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:23: An argument for 'y' was not provided. + + function c(x: number | void, y: void, z: void | string | number): void { + + } + + c(3, void 0, void 0); // ok + c(3, void 0); // ok + c(3); // ok + c(); // ok + + + // Spread Parameters + + declare function call( + handler: (...args: TS) => unknown, + ...args: TS): void; + + call((x: number, y: number) => x + y) // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:73:5: An argument for 'args' was not provided. + call((x: number, y: number) => x + y, 4, 2) // ok + + call((x: number, y: void) => x, 4, void 0) // ok + call((x: number, y: void) => x, 4) // ok + call((x: void, y: void) => 42) // ok + call((x: number | void, y: number | void) => 42) // ok + call((x: number | void, y: number | void) => 42, 4) // ok + call((x: number | void, y: number | void) => 42, 4, 2) // ok + \ No newline at end of file diff --git a/tests/baselines/reference/callWithMissingVoid.js b/tests/baselines/reference/callWithMissingVoid.js new file mode 100644 index 00000000000..50282931fa6 --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.js @@ -0,0 +1,140 @@ +//// [callWithMissingVoid.ts] +// From #4260 +class X { + f(t: T) { + return { a: t }; + } +} + +declare const x: X; +x.f() // no error because f expects void + +declare const xUnion: X; +xUnion.f(42) // no error because f accepts number +xUnion.f() // no error because f accepts void + +declare const xAny: X; +xAny.f() // error, any still expects an argument + +declare const xUnknown: X; +xUnknown.f() // error, unknown still expects an argument + +declare const xNever: X; +xNever.f() // error, never still expects an argument + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { + constructor(executor: (resolve: (value: X) => void) => void) { + + } +} + +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { + +} + +a(4, "hello"); // ok +a(4, "hello", void 0); // ok +a(4); // not ok + +function b(x: number, y: string, z: void, what: number): void { + +} + +b(4, "hello", void 0, 2); // ok +b(4, "hello"); // not ok +b(4, "hello", void 0); // not ok +b(4); // not ok + +function c(x: number | void, y: void, z: void | string | number): void { + +} + +c(3, void 0, void 0); // ok +c(3, void 0); // ok +c(3); // ok +c(); // ok + + +// Spread Parameters + +declare function call( + handler: (...args: TS) => unknown, + ...args: TS): void; + +call((x: number, y: number) => x + y) // error +call((x: number, y: number) => x + y, 4, 2) // ok + +call((x: number, y: void) => x, 4, void 0) // ok +call((x: number, y: void) => x, 4) // ok +call((x: void, y: void) => 42) // ok +call((x: number | void, y: number | void) => 42) // ok +call((x: number | void, y: number | void) => 42, 4) // ok +call((x: number | void, y: number | void) => 42, 4, 2) // ok + + +//// [callWithMissingVoid.js] +"use strict"; +// From #4260 +var X = /** @class */ (function () { + function X() { + } + X.prototype.f = function (t) { + return { a: t }; + }; + return X; +}()); +x.f(); // no error because f expects void +xUnion.f(42); // no error because f accepts number +xUnion.f(); // no error because f accepts void +xAny.f(); // error, any still expects an argument +xUnknown.f(); // error, unknown still expects an argument +xNever.f(); // error, never still expects an argument +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. +var MyPromise = /** @class */ (function () { + function MyPromise(executor) { + } + return MyPromise; +}()); +new MyPromise(function (resolve) { return resolve(); }); // no error +new MyPromise(function (resolve) { return resolve(); }); // no error +new MyPromise(function (resolve) { return resolve(); }); // error, `any` arguments cannot be omitted +new MyPromise(function (resolve) { return resolve(); }); // error, `unknown` arguments cannot be omitted +new MyPromise(function (resolve) { return resolve(); }); // error, `never` arguments cannot be omitted +// Multiple parameters +function a(x, y, z) { +} +a(4, "hello"); // ok +a(4, "hello", void 0); // ok +a(4); // not ok +function b(x, y, z, what) { +} +b(4, "hello", void 0, 2); // ok +b(4, "hello"); // not ok +b(4, "hello", void 0); // not ok +b(4); // not ok +function c(x, y, z) { +} +c(3, void 0, void 0); // ok +c(3, void 0); // ok +c(3); // ok +c(); // ok +call(function (x, y) { return x + y; }); // error +call(function (x, y) { return x + y; }, 4, 2); // ok +call(function (x, y) { return x; }, 4, void 0); // ok +call(function (x, y) { return x; }, 4); // ok +call(function (x, y) { return 42; }); // ok +call(function (x, y) { return 42; }); // ok +call(function (x, y) { return 42; }, 4); // ok +call(function (x, y) { return 42; }, 4, 2); // ok diff --git a/tests/baselines/reference/callWithMissingVoid.symbols b/tests/baselines/reference/callWithMissingVoid.symbols new file mode 100644 index 00000000000..22a198b7433 --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.symbols @@ -0,0 +1,231 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts === +// From #4260 +class X { +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) +>T : Symbol(T, Decl(callWithMissingVoid.ts, 1, 8)) + + f(t: T) { +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>t : Symbol(t, Decl(callWithMissingVoid.ts, 2, 6)) +>T : Symbol(T, Decl(callWithMissingVoid.ts, 1, 8)) + + return { a: t }; +>a : Symbol(a, Decl(callWithMissingVoid.ts, 3, 16)) +>t : Symbol(t, Decl(callWithMissingVoid.ts, 2, 6)) + } +} + +declare const x: X; +>x : Symbol(x, Decl(callWithMissingVoid.ts, 7, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +x.f() // no error because f expects void +>x.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 7, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xUnion: X; +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xUnion.f(42) // no error because f accepts number +>xUnion.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +xUnion.f() // no error because f accepts void +>xUnion.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xAny: X; +>xAny : Symbol(xAny, Decl(callWithMissingVoid.ts, 14, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xAny.f() // error, any still expects an argument +>xAny.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xAny : Symbol(xAny, Decl(callWithMissingVoid.ts, 14, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xUnknown: X; +>xUnknown : Symbol(xUnknown, Decl(callWithMissingVoid.ts, 17, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xUnknown.f() // error, unknown still expects an argument +>xUnknown.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnknown : Symbol(xUnknown, Decl(callWithMissingVoid.ts, 17, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xNever: X; +>xNever : Symbol(xNever, Decl(callWithMissingVoid.ts, 20, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xNever.f() // error, never still expects an argument +>xNever.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xNever : Symbol(xNever, Decl(callWithMissingVoid.ts, 20, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 26, 16)) + + constructor(executor: (resolve: (value: X) => void) => void) { +>executor : Symbol(executor, Decl(callWithMissingVoid.ts, 27, 16)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 27, 27)) +>value : Symbol(value, Decl(callWithMissingVoid.ts, 27, 37)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 26, 16)) + + } +} + +new MyPromise(resolve => resolve()); // no error +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 32, 20)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 32, 20)) + +new MyPromise(resolve => resolve()); // no error +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 33, 29)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 33, 29)) + +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 34, 19)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 34, 19)) + +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 35, 23)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 35, 23)) + +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 36, 21)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 36, 21)) + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 41, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 41, 21)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 41, 32)) + +} + +a(4, "hello"); // ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +a(4, "hello", void 0); // ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +a(4); // not ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +function b(x: number, y: string, z: void, what: number): void { +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 49, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 49, 21)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 49, 32)) +>what : Symbol(what, Decl(callWithMissingVoid.ts, 49, 41)) + +} + +b(4, "hello", void 0, 2); // ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4, "hello"); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4, "hello", void 0); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +function c(x: number | void, y: void, z: void | string | number): void { +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 58, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 58, 28)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 58, 37)) + +} + +c(3, void 0, void 0); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(3, void 0); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(3); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + + +// Spread Parameters + +declare function call( +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + + handler: (...args: TS) => unknown, +>handler : Symbol(handler, Decl(callWithMissingVoid.ts, 70, 44)) +>args : Symbol(args, Decl(callWithMissingVoid.ts, 71, 14)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + + ...args: TS): void; +>args : Symbol(args, Decl(callWithMissingVoid.ts, 71, 38)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + +call((x: number, y: number) => x + y) // error +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 74, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 74, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 74, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 74, 16)) + +call((x: number, y: number) => x + y, 4, 2) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 75, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 75, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 75, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 75, 16)) + +call((x: number, y: void) => x, 4, void 0) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 77, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 77, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 77, 6)) + +call((x: number, y: void) => x, 4) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 78, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 78, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 78, 6)) + +call((x: void, y: void) => 42) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 79, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 79, 14)) + +call((x: number | void, y: number | void) => 42) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 80, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 80, 23)) + +call((x: number | void, y: number | void) => 42, 4) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 81, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 81, 23)) + +call((x: number | void, y: number | void) => 42, 4, 2) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 82, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 82, 23)) + diff --git a/tests/baselines/reference/callWithMissingVoid.types b/tests/baselines/reference/callWithMissingVoid.types new file mode 100644 index 00000000000..4fbcbbf5d1b --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.types @@ -0,0 +1,312 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts === +// From #4260 +class X { +>X : X + + f(t: T) { +>f : (t: T) => { a: T; } +>t : T + + return { a: t }; +>{ a: t } : { a: T; } +>a : T +>t : T + } +} + +declare const x: X; +>x : X + +x.f() // no error because f expects void +>x.f() : { a: void; } +>x.f : (t: void) => { a: void; } +>x : X +>f : (t: void) => { a: void; } + +declare const xUnion: X; +>xUnion : X + +xUnion.f(42) // no error because f accepts number +>xUnion.f(42) : { a: number | void; } +>xUnion.f : (t: number | void) => { a: number | void; } +>xUnion : X +>f : (t: number | void) => { a: number | void; } +>42 : 42 + +xUnion.f() // no error because f accepts void +>xUnion.f() : { a: number | void; } +>xUnion.f : (t: number | void) => { a: number | void; } +>xUnion : X +>f : (t: number | void) => { a: number | void; } + +declare const xAny: X; +>xAny : X + +xAny.f() // error, any still expects an argument +>xAny.f() : { a: any; } +>xAny.f : (t: any) => { a: any; } +>xAny : X +>f : (t: any) => { a: any; } + +declare const xUnknown: X; +>xUnknown : X + +xUnknown.f() // error, unknown still expects an argument +>xUnknown.f() : { a: unknown; } +>xUnknown.f : (t: unknown) => { a: unknown; } +>xUnknown : X +>f : (t: unknown) => { a: unknown; } + +declare const xNever: X; +>xNever : X + +xNever.f() // error, never still expects an argument +>xNever.f() : { a: never; } +>xNever.f : (t: never) => { a: never; } +>xNever : X +>f : (t: never) => { a: never; } + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { +>MyPromise : MyPromise + + constructor(executor: (resolve: (value: X) => void) => void) { +>executor : (resolve: (value: X) => void) => void +>resolve : (value: X) => void +>value : X + + } +} + +new MyPromise(resolve => resolve()); // no error +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: void) => void) => void +>resolve : (value: void) => void +>resolve() : void +>resolve : (value: void) => void + +new MyPromise(resolve => resolve()); // no error +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: number | void) => void) => void +>resolve : (value: number | void) => void +>resolve() : void +>resolve : (value: number | void) => void + +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: any) => void) => any +>resolve : (value: any) => void +>resolve() : void +>resolve : (value: any) => void + +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: unknown) => void) => any +>resolve : (value: unknown) => void +>resolve() : void +>resolve : (value: unknown) => void + +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: never) => void) => any +>resolve : (value: never) => void +>resolve() : void +>resolve : (value: never) => void + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { +>a : (x: number, y: string, z: void) => void +>x : number +>y : string +>z : void + +} + +a(4, "hello"); // ok +>a(4, "hello") : void +>a : (x: number, y: string, z: void) => void +>4 : 4 +>"hello" : "hello" + +a(4, "hello", void 0); // ok +>a(4, "hello", void 0) : void +>a : (x: number, y: string, z: void) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 + +a(4); // not ok +>a(4) : void +>a : (x: number, y: string, z: void) => void +>4 : 4 + +function b(x: number, y: string, z: void, what: number): void { +>b : (x: number, y: string, z: void, what: number) => void +>x : number +>y : string +>z : void +>what : number + +} + +b(4, "hello", void 0, 2); // ok +>b(4, "hello", void 0, 2) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 +>2 : 2 + +b(4, "hello"); // not ok +>b(4, "hello") : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" + +b(4, "hello", void 0); // not ok +>b(4, "hello", void 0) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 + +b(4); // not ok +>b(4) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 + +function c(x: number | void, y: void, z: void | string | number): void { +>c : (x: number | void, y: void, z: string | number | void) => void +>x : number | void +>y : void +>z : string | number | void + +} + +c(3, void 0, void 0); // ok +>c(3, void 0, void 0) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 +>void 0 : undefined +>0 : 0 +>void 0 : undefined +>0 : 0 + +c(3, void 0); // ok +>c(3, void 0) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 +>void 0 : undefined +>0 : 0 + +c(3); // ok +>c(3) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 + +c(); // ok +>c() : void +>c : (x: number | void, y: void, z: string | number | void) => void + + +// Spread Parameters + +declare function call( +>call : (handler: (...args: TS) => unknown, ...args: TS) => void + + handler: (...args: TS) => unknown, +>handler : (...args: TS) => unknown +>args : TS + + ...args: TS): void; +>args : TS + +call((x: number, y: number) => x + y) // error +>call((x: number, y: number) => x + y) : any +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: number) => x + y : (x: number, y: number) => number +>x : number +>y : number +>x + y : number +>x : number +>y : number + +call((x: number, y: number) => x + y, 4, 2) // ok +>call((x: number, y: number) => x + y, 4, 2) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: number) => x + y : (x: number, y: number) => number +>x : number +>y : number +>x + y : number +>x : number +>y : number +>4 : 4 +>2 : 2 + +call((x: number, y: void) => x, 4, void 0) // ok +>call((x: number, y: void) => x, 4, void 0) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: void) => x : (x: number, y: void) => number +>x : number +>y : void +>x : number +>4 : 4 +>void 0 : undefined +>0 : 0 + +call((x: number, y: void) => x, 4) // ok +>call((x: number, y: void) => x, 4) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: void) => x : (x: number, y: void) => number +>x : number +>y : void +>x : number +>4 : 4 + +call((x: void, y: void) => 42) // ok +>call((x: void, y: void) => 42) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: void, y: void) => 42 : (x: void, y: void) => number +>x : void +>y : void +>42 : 42 + +call((x: number | void, y: number | void) => 42) // ok +>call((x: number | void, y: number | void) => 42) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 + +call((x: number | void, y: number | void) => 42, 4) // ok +>call((x: number | void, y: number | void) => 42, 4) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 +>4 : 4 + +call((x: number | void, y: number | void) => 42, 4, 2) // ok +>call((x: number | void, y: number | void) => 42, 4, 2) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 +>4 : 4 +>2 : 2 + diff --git a/tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts b/tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts new file mode 100644 index 00000000000..70855da320e --- /dev/null +++ b/tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts @@ -0,0 +1,85 @@ +// @strict: true + +// From #4260 +class X { + f(t: T) { + return { a: t }; + } +} + +declare const x: X; +x.f() // no error because f expects void + +declare const xUnion: X; +xUnion.f(42) // no error because f accepts number +xUnion.f() // no error because f accepts void + +declare const xAny: X; +xAny.f() // error, any still expects an argument + +declare const xUnknown: X; +xUnknown.f() // error, unknown still expects an argument + +declare const xNever: X; +xNever.f() // error, never still expects an argument + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { + constructor(executor: (resolve: (value: X) => void) => void) { + + } +} + +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { + +} + +a(4, "hello"); // ok +a(4, "hello", void 0); // ok +a(4); // not ok + +function b(x: number, y: string, z: void, what: number): void { + +} + +b(4, "hello", void 0, 2); // ok +b(4, "hello"); // not ok +b(4, "hello", void 0); // not ok +b(4); // not ok + +function c(x: number | void, y: void, z: void | string | number): void { + +} + +c(3, void 0, void 0); // ok +c(3, void 0); // ok +c(3); // ok +c(); // ok + + +// Spread Parameters + +declare function call( + handler: (...args: TS) => unknown, + ...args: TS): void; + +call((x: number, y: number) => x + y) // error +call((x: number, y: number) => x + y, 4, 2) // ok + +call((x: number, y: void) => x, 4, void 0) // ok +call((x: number, y: void) => x, 4) // ok +call((x: void, y: void) => 42) // ok +call((x: number | void, y: number | void) => 42) // ok +call((x: number | void, y: number | void) => 42, 4) // ok +call((x: number | void, y: number | void) => 42, 4, 2) // ok From 0ac96580d5ccd72df0786d991724232c3129008a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 18 Sep 2018 16:21:05 -0700 Subject: [PATCH 004/262] Resolve project references transitively --- src/compiler/commandLineParser.ts | 1 + src/compiler/program.ts | 161 +++++++++++------- src/compiler/types.ts | 3 +- src/server/project.ts | 8 +- src/testRunner/unittests/tsbuild.ts | 50 ++++-- .../reference/api/tsserverlibrary.d.ts | 7 +- tests/baselines/reference/api/typescript.d.ts | 3 +- tests/projects/transitiveReferences/a.ts | 1 + tests/projects/transitiveReferences/b.ts | 2 + tests/projects/transitiveReferences/c.ts | 2 + .../transitiveReferences/tsconfig.a.json | 1 + .../transitiveReferences/tsconfig.b.json | 1 + .../transitiveReferences/tsconfig.c.json | 1 + 13 files changed, 163 insertions(+), 78 deletions(-) create mode 100644 tests/projects/transitiveReferences/a.ts create mode 100644 tests/projects/transitiveReferences/b.ts create mode 100644 tests/projects/transitiveReferences/c.ts create mode 100644 tests/projects/transitiveReferences/tsconfig.a.json create mode 100644 tests/projects/transitiveReferences/tsconfig.b.json create mode 100644 tests/projects/transitiveReferences/tsconfig.c.json diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 58f1e8fdaa3..b1cc4ef5b27 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1293,6 +1293,7 @@ namespace ts { const result = parseJsonText(configFileName, configFileText); const cwd = host.getCurrentDirectory(); + result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd)); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 17a10137d20..6dff51559b8 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -454,6 +454,8 @@ namespace ts { return false; } + let seenResolvedRefs: ResolvedProjectReference[] | undefined; + // If project references dont match if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; @@ -496,11 +498,29 @@ namespace ts { if (!projectReferenceIsEqualTo(oldRef, newRef)) { return false; } - const oldResolvedRef = program!.getResolvedProjectReferences()![index]; + return resolvedProjectReferenceUptoDate(program!.getResolvedProjectReferences()![index], oldRef); + } + + function resolvedProjectReferenceUptoDate(oldResolvedRef: ResolvedProjectReference | undefined, oldRef: ProjectReference): boolean { if (oldResolvedRef) { + if (contains(seenResolvedRefs, oldResolvedRef)) { + // Assume true + return true; + } + // If sourceFile for the oldResolvedRef existed, check the version for uptodate - return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) { + return false; + } + + // Add to seen before checking the referenced paths of this config file + (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); + + // If child project references are upto date, this project reference is uptodate + return !forEach(oldResolvedRef.references, (childResolvedRef, index) => + !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences![index])); } + // In old program, not able to resolve project reference path, // so if config file doesnt exist, it is uptodate. return !fileExists(resolveProjectReferencePath(oldRef)); @@ -662,8 +682,8 @@ namespace ts { const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files - let resolvedProjectReferences: (ResolvedProjectReference | undefined)[] | undefined = projectReferences ? [] : undefined; - let projectReferenceRedirects: ParsedCommandLine[] | undefined; + let resolvedProjectReferences: ReadonlyArray | undefined; + let projectReferenceRedirects: Map | undefined; const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); const structuralIsReused = tryReuseStructureFromOldProgram(); @@ -672,16 +692,16 @@ namespace ts { processingOtherFiles = []; if (projectReferences) { - for (const ref of projectReferences) { - const parsedRef = parseProjectReferenceConfigFile(ref); - resolvedProjectReferences!.push(parsedRef); + if (!resolvedProjectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } + for (const parsedRef of resolvedProjectReferences) { if (parsedRef) { const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; if (out) { const dtsOutfile = changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -740,6 +760,12 @@ namespace ts { // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; + // Do not use our own command line for projectReferenceRedirects + if (projectReferenceRedirects) { + Debug.assert(!!options.configFilePath); + const path = toPath(options.configFilePath!); + projectReferenceRedirects.delete(path); + } program = { getRootFileNames: () => rootNames, @@ -1001,6 +1027,48 @@ namespace ts { } } + function canReuseProjectReferences( + newProjectReferences: ReadonlyArray | undefined, + oldProjectReferences: ReadonlyArray | undefined, + oldResolvedReferences: ReadonlyArray | undefined): boolean { + // If array of references is changed, we cant resue old program + if (!arrayIsEqualTo(oldProjectReferences!, newProjectReferences, projectReferenceIsEqualTo)) { + return false; + } + + // Check the json files for the project references + if (newProjectReferences) { + // Resolved project referenced should be array if projectReferences provided are array + Debug.assert(!!oldResolvedReferences); + for (let i = 0; i < newProjectReferences.length; i++) { + const oldRef = oldResolvedReferences![i]; + const newRef = parseProjectReferenceConfigFile(newProjectReferences[i]); + if (oldRef) { + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return false; + } + + // If the transitive references can be reused then only this reference can be reused + if (!canReuseProjectReferences(newRef.commandLine.projectReferences, oldRef.commandLine.projectReferences, oldRef.references)) { + return false; + } + } + else { + // A previously-unresolved reference may be resolved now + if (newRef !== undefined) { + return false; + } + } + } + } + else { + // Resolved project referenced should be undefined if projectReferences is undefined + Debug.assert(!oldResolvedReferences); + } + return true; + } + function tryReuseStructureFromOldProgram(): StructureIsReused { if (!oldProgram) { return StructureIsReused.Not; @@ -1026,39 +1094,10 @@ namespace ts { } // Check if any referenced project tsconfig files are different - - // If array of references is changed, we cant resue old program - const oldProjectReferences = oldProgram.getProjectReferences(); - if (!arrayIsEqualTo(oldProjectReferences!, projectReferences, projectReferenceIsEqualTo)) { + if (!canReuseProjectReferences(projectReferences, oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences())) { return oldProgram.structureIsReused = StructureIsReused.Not; } - - // Check the json files for the project references - const oldRefs = oldProgram.getResolvedProjectReferences(); - if (projectReferences) { - // Resolved project referenced should be array if projectReferences provided are array - Debug.assert(!!oldRefs); - for (let i = 0; i < projectReferences.length; i++) { - const oldRef = oldRefs![i]; - const newRef = parseProjectReferenceConfigFile(projectReferences[i]); - if (oldRef) { - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return oldProgram.structureIsReused = StructureIsReused.Not; - } - } - else { - // A previously-unresolved reference may be resolved now - if (newRef !== undefined) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } - } - } - } - else { - // Resolved project referenced should be undefined if projectReferences is undefined - Debug.assert(!oldRefs); - } + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; @@ -1248,14 +1287,6 @@ namespace ts { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); - if (resolvedProjectReferences) { - resolvedProjectReferences.forEach(ref => { - if (ref) { - addProjectReferenceRedirects(ref.commandLine); - } - }); - } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; @@ -2182,22 +2213,22 @@ namespace ts { function getProjectReferenceRedirect(fileName: string): string | undefined { // Ignore dts or any of the non ts files - if (!projectReferenceRedirects || fileExtensionIs(fileName, Extension.Dts) || !fileExtensionIsOneOf(fileName, supportedTSExtensions)) { + if (!resolvedProjectReferences || !resolvedProjectReferences.length || fileExtensionIs(fileName, Extension.Dts) || !fileExtensionIsOneOf(fileName, supportedTSExtensions)) { return undefined; } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - return forEach(projectReferenceRedirects, referencedProject => { + return forEachEntry(projectReferenceRedirects!, referencedProject => { // not input file from the referenced project, ignore - if (!contains(referencedProject.fileNames, fileName, isSameFile)) { + if (!referencedProject || !contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - const out = referencedProject.options.outFile || referencedProject.options.out; + const out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; return out ? changeExtension(out, Extension.Dts) : - getOutputDeclarationFileName(fileName, referencedProject); + getOutputDeclarationFileName(fileName, referencedProject.commandLine); }); } @@ -2388,22 +2419,34 @@ namespace ts { return allFilesBelongToPath; } - function parseProjectReferenceConfigFile(ref: ProjectReference): { commandLine: ParsedCommandLine, sourceFile: SourceFile } | undefined { + function parseProjectReferenceConfigFile(ref: ProjectReference): ResolvedProjectReference | undefined { + if (!projectReferenceRedirects) { + projectReferenceRedirects = createMap(); + } + // The actual filename (i.e. add "/tsconfig.json" if necessary) const refPath = resolveProjectReferencePath(ref); + const sourceFilePath = toPath(refPath); + const fromCache = projectReferenceRedirects.get(sourceFilePath); + if (fromCache !== undefined) { + return fromCache || undefined; + } + // An absolute path pointing to the containing directory of the config file const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile | undefined; if (sourceFile === undefined) { + projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile.path = toPath(refPath); + sourceFile.path = sourceFilePath; const commandLine = parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); - return { commandLine, sourceFile }; - } - - function addProjectReferenceRedirects(referencedProject: ParsedCommandLine) { - (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); + const resolvedRef: ResolvedProjectReference = { commandLine, sourceFile }; + projectReferenceRedirects.set(sourceFilePath, resolvedRef); + if (commandLine.projectReferences) { + resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile); + } + return resolvedRef; } function verifyCompilerOptions() { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a091228813d..bc35588488c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2829,7 +2829,7 @@ namespace ts { /* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; getProjectReferences(): ReadonlyArray | undefined; - getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; /*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined; } @@ -2839,6 +2839,7 @@ namespace ts { export interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } /* @internal */ diff --git a/src/server/project.ts b/src/server/project.ts index 8689c5e7e3d..164f0fe7c34 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -281,8 +281,8 @@ namespace ts.server { return this.projectStateVersion.toString(); } - getProjectReferences(): ReadonlyArray { - return emptyArray; + getProjectReferences(): ReadonlyArray | undefined { + return undefined; } getScriptFileNames() { @@ -1391,8 +1391,8 @@ namespace ts.server { return asNormalizedPath(this.getProjectName()); } - getProjectReferences(): ReadonlyArray { - return this.projectReferences || emptyArray; + getProjectReferences(): ReadonlyArray | undefined { + return this.projectReferences; } updateReferences(refs: ReadonlyArray | undefined) { diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index 36feb68a223..bb219ced37c 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -321,16 +321,6 @@ export class cNew {}`); "/src/tests/index.ts" ]); - function getLibs() { - return [ - "/lib/lib.d.ts", - "/lib/lib.es5.d.ts", - "/lib/lib.dom.d.ts", - "/lib/lib.webworker.importscripts.d.ts", - "/lib/lib.scripthost.d.ts" - ]; - } - function getCoreOutputs() { return [ "/src/core/index.d.ts", @@ -376,6 +366,36 @@ export class cNew {}`); } }); }); + + describe("tsbuild - when project reference is referenced transitively", () => { + const projFs = loadProjectFromDisk("tests/projects/transitiveReferences"); + const allExpectedOutputs = [ + "/src/a.js", "/src/a.d.ts", + "/src/b.js", "/src/b.d.ts", + "/src/c.js" + ]; + it("verify that it builds correctly", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true }); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + assert.deepEqual(host.traces, [ + ...getLibs(), + "/src/a.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.d.ts", + "/src/c.ts" + ]); + }); + }); } export namespace OutFile { @@ -584,4 +604,14 @@ export class cNew {}`); fs.makeReadonly(); return fs; } + + function getLibs() { + return [ + "/lib/lib.d.ts", + "/lib/lib.es5.d.ts", + "/lib/lib.dom.d.ts", + "/lib/lib.webworker.importscripts.d.ts", + "/lib/lib.scripthost.d.ts" + ]; + } } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index a90f40f9ac7..942b3978e75 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1812,11 +1812,12 @@ declare namespace ts { isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; getProjectReferences(): ReadonlyArray | undefined; - getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ @@ -8114,7 +8115,7 @@ declare namespace ts.server { getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; - getProjectReferences(): ReadonlyArray; + getProjectReferences(): ReadonlyArray | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; @@ -8231,7 +8232,7 @@ declare namespace ts.server { */ updateGraph(): boolean; getConfigFilePath(): NormalizedPath; - getProjectReferences(): ReadonlyArray; + getProjectReferences(): ReadonlyArray | undefined; updateReferences(refs: ReadonlyArray | undefined): void; enablePlugins(): void; /** diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index d6bd508999d..ee9ce336ad9 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1812,11 +1812,12 @@ declare namespace ts { isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; getProjectReferences(): ReadonlyArray | undefined; - getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getResolvedProjectReferences(): ReadonlyArray | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } interface CustomTransformers { /** Custom transformers to evaluate before built-in .js transformations. */ diff --git a/tests/projects/transitiveReferences/a.ts b/tests/projects/transitiveReferences/a.ts new file mode 100644 index 00000000000..56d3f8e39a0 --- /dev/null +++ b/tests/projects/transitiveReferences/a.ts @@ -0,0 +1 @@ +export class A {} diff --git a/tests/projects/transitiveReferences/b.ts b/tests/projects/transitiveReferences/b.ts new file mode 100644 index 00000000000..619dd224835 --- /dev/null +++ b/tests/projects/transitiveReferences/b.ts @@ -0,0 +1,2 @@ +import {A} from './a'; +export const b = new A(); diff --git a/tests/projects/transitiveReferences/c.ts b/tests/projects/transitiveReferences/c.ts new file mode 100644 index 00000000000..b436b3db99c --- /dev/null +++ b/tests/projects/transitiveReferences/c.ts @@ -0,0 +1,2 @@ +import {b} from './b'; +console.log(b); \ No newline at end of file diff --git a/tests/projects/transitiveReferences/tsconfig.a.json b/tests/projects/transitiveReferences/tsconfig.a.json new file mode 100644 index 00000000000..74fe1ef8b56 --- /dev/null +++ b/tests/projects/transitiveReferences/tsconfig.a.json @@ -0,0 +1 @@ +{"compilerOptions": {"composite": true}, "files": ["a.ts"]} diff --git a/tests/projects/transitiveReferences/tsconfig.b.json b/tests/projects/transitiveReferences/tsconfig.b.json new file mode 100644 index 00000000000..f4734997f73 --- /dev/null +++ b/tests/projects/transitiveReferences/tsconfig.b.json @@ -0,0 +1 @@ +{"compilerOptions": {"composite": true}, "files": ["b.ts"], "references": [{"path": "tsconfig.a.json"}]} diff --git a/tests/projects/transitiveReferences/tsconfig.c.json b/tests/projects/transitiveReferences/tsconfig.c.json new file mode 100644 index 00000000000..1f919a04cd9 --- /dev/null +++ b/tests/projects/transitiveReferences/tsconfig.c.json @@ -0,0 +1 @@ +{"files": ["c.ts"], "references": [{"path": "tsconfig.b.json"}]} From 0e4b10d726d64c092effd2bbcf90a593ae22cc3c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 1 Oct 2018 15:30:06 -0700 Subject: [PATCH 005/262] Use resolution options of project reference if the file is from the project reference --- src/compiler/diagnosticMessages.json | 6 +- src/compiler/moduleNameResolver.ts | 16 ++++- src/compiler/program.ts | 63 +++++++++++-------- src/compiler/resolutionCache.ts | 21 ++++--- src/compiler/types.ts | 4 +- src/compiler/watch.ts | 12 ++-- src/server/project.ts | 8 +-- src/services/services.ts | 6 +- src/services/types.ts | 4 +- tests/projects/transitiveReferences/b.ts | 2 +- .../transitiveReferences/tsconfig.b.json | 12 +++- 11 files changed, 97 insertions(+), 57 deletions(-) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ce1ccf17145..3de5961c856 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3763,6 +3763,10 @@ "category": "Message", "code": 6214 }, + "Using compiler options of project reference redirect '{0}'.": { + "category": "Message", + "code": 6215 + }, "Projects to reference": { "category": "Message", @@ -4684,4 +4688,4 @@ "category": "Message", "code": 95068 } -} \ No newline at end of file +} diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 4906abc8f8c..315bc394e56 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -258,8 +258,11 @@ namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { + export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } const failedLookupLocations: string[] = []; const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; @@ -281,6 +284,9 @@ namespace ts { trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } let resolved = primaryLookup(); @@ -542,10 +548,16 @@ namespace ts { return perFolderCache && perFolderCache.get(moduleName); } - export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { + export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); + if (redirectedReference) { + compilerOptions = redirectedReference.commandLine.options; + } if (traceEnabled) { trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + if (redirectedReference) { + trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + } } const containingDirectory = getDirectoryPath(containingFile); const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 6dff51559b8..416c2d218eb 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -406,7 +406,7 @@ namespace ts { } } - function loadWithLocalCache(names: string[], containingFile: string, loader: (name: string, containingFile: string) => T): T[] { + function loadWithLocalCache(names: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, loader: (name: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => T): T[] { if (names.length === 0) { return []; } @@ -418,7 +418,7 @@ namespace ts { result = cache.get(name)!; } else { - cache.set(name, result = loader(name, containingFile)); + cache.set(name, result = loader(name, containingFile, redirectedReference)); } resolutions.push(result); } @@ -638,10 +638,10 @@ namespace ts { let _referencesArrayLiteralSyntax: ArrayLiteralExpression | null | undefined; let moduleResolutionCache: ModuleResolutionCache | undefined; - let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[]) => ResolvedModuleFull[]; + let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[]; const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(resolved => { + resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference).map(resolved => { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) { return resolved as ResolvedModuleFull; @@ -653,17 +653,17 @@ namespace ts { } else { moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x)); - const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule!; // TODO: GH#18217 - resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, loader); + const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217 + resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader); } - let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; + let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => ResolvedTypeReferenceDirective[]; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile); + resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); } else { - const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective!; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, loader); + const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective!; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader); } // Map from a stringified PackageId to the source file with that id. @@ -760,12 +760,6 @@ namespace ts { // unconditionally set oldProgram to undefined to prevent it from being captured in closure oldProgram = undefined; - // Do not use our own command line for projectReferenceRedirects - if (projectReferenceRedirects) { - Debug.assert(!!options.configFilePath); - const path = toPath(options.configFilePath!); - projectReferenceRedirects.delete(path); - } program = { getRootFileNames: () => rootNames, @@ -887,7 +881,7 @@ namespace ts { if (structuralIsReused === StructureIsReused.Not && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getProjectReferenceRedirectProject(file.originalFileName)); } const oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); @@ -967,7 +961,7 @@ namespace ts { } const resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getProjectReferenceRedirectProject(file.originalFileName)) : emptyArray; // Combine results of resolutions and predicted results @@ -1248,7 +1242,7 @@ namespace ts { if (resolveTypeReferenceDirectiveNamesWorker) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase()); - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getProjectReferenceRedirectProject(newSourceFile.originalFileName)); // ensure that types resolutions are still correct const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -2219,16 +2213,35 @@ namespace ts { // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input + const referencedProject = getProjectReferenceRedirectProject(fileName); + if (!referencedProject) { + return undefined; + } + + const out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; + return out ? + changeExtension(out, Extension.Dts) : + getOutputDeclarationFileName(fileName, referencedProject.commandLine); + } + + /** + * Get the referenced project if the file is input file from that reference project + */ + function getProjectReferenceRedirectProject(fileName: string) { + if (!resolvedProjectReferences || !resolvedProjectReferences.length) { + return undefined; + } + + // If this file is input file of the referenced projec return forEachEntry(projectReferenceRedirects!, referencedProject => { // not input file from the referenced project, ignore - if (!referencedProject || !contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { + if (!referencedProject || + options.configFilePath === referencedProject.commandLine.options.configFilePath || + !contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - const out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; - return out ? - changeExtension(out, Extension.Dts) : - getOutputDeclarationFileName(fileName, referencedProject.commandLine); + return referencedProject; }); } @@ -2246,7 +2259,7 @@ namespace ts { return; } - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getProjectReferenceRedirectProject(file.originalFileName)); for (let i = 0; i < typeDirectives.length; i++) { const ref = file.typeReferenceDirectives[i]; diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 84b5d8e0a85..809a649520d 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -5,9 +5,9 @@ namespace ts { startRecordingFilesWithChangedResolutions(): void; finishRecordingFilesWithChangedResolutions(): Path[] | undefined; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; @@ -217,8 +217,8 @@ namespace ts { }); } - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): CachedResolvedModuleWithFailedLookupLocations { - const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): CachedResolvedModuleWithFailedLookupLocations { + const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { return primaryResult; @@ -242,9 +242,10 @@ namespace ts { function resolveNamesWithLocalCache( names: string[], containingFile: string, + redirectedReference: ResolvedProjectReference | undefined, cache: Map>, perDirectoryCache: Map>, - loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T, + loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, reusedNames: string[] | undefined, logChanges: boolean): R[] { @@ -274,7 +275,7 @@ namespace ts { resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost); + resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); @@ -323,18 +324,18 @@ namespace ts { } } - function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] { + function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[] { return resolveNamesWithLocalCache( - typeDirectiveNames, containingFile, + typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, /*reusedNames*/ undefined, /*logChanges*/ false ); } - function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[] { + function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[] { return resolveNamesWithLocalCache( - moduleNames, containingFile, + moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule diff --git a/src/compiler/types.ts b/src/compiler/types.ts index bc35588488c..eb5ab188796 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4876,11 +4876,11 @@ namespace ts { * If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just * 'throw new Error("NotImplemented")' */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 24ce39fdc4f..34cd1a4a107 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -338,9 +338,9 @@ namespace ts { getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; } /** Internal interface used to wire emit through same host */ @@ -558,11 +558,11 @@ namespace ts { ); // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names compilerHost.resolveModuleNames = host.resolveModuleNames ? - ((moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames)) : - ((moduleNames, containingFile, reusedNames) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames)); + ((moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames, redirectedReference)) : + ((moduleNames, containingFile, reusedNames, redirectedReference) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference)); compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? - ((typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives!(typeDirectiveNames, containingFile)) : - ((typeDirectiveNames, containingFile) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile)); + ((typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(typeDirectiveNames, containingFile, redirectedReference)) : + ((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; synchronizeProgram(); diff --git a/src/server/project.ts b/src/server/project.ts index 164f0fe7c34..2f3a0c203d4 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -368,16 +368,16 @@ namespace ts.server { return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); } - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[] { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[] { + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); } getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined { return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); } - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] { - return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[] { + return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); } directoryExists(path: string): boolean { diff --git a/src/services/services.ts b/src/services/services.ts index 9e08f1b14a6..662b471fe75 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1232,11 +1232,11 @@ namespace ts { } if (host.resolveModuleNames) { - compilerHost.resolveModuleNames = (moduleNames, containingFile, reusedNames) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames); + compilerHost.resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(moduleNames, containingFile, reusedNames, redirectedReference); } if (host.resolveTypeReferenceDirectives) { - compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile) => { - return host.resolveTypeReferenceDirectives!(typeReferenceDirectiveNames, containingFile); + compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile, redirectedReference) => { + return host.resolveTypeReferenceDirectives!(typeReferenceDirectiveNames, containingFile, redirectedReference); }; } diff --git a/src/services/types.ts b/src/services/types.ts index 011c98f9da6..80dac58095c 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -212,9 +212,9 @@ namespace ts { * * If this is implemented, `getResolvedModuleWithFailedLookupLocationsFromCache` should be too. */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; diff --git a/tests/projects/transitiveReferences/b.ts b/tests/projects/transitiveReferences/b.ts index 619dd224835..8b601a60765 100644 --- a/tests/projects/transitiveReferences/b.ts +++ b/tests/projects/transitiveReferences/b.ts @@ -1,2 +1,2 @@ -import {A} from './a'; +import {A} from '@ref/a'; export const b = new A(); diff --git a/tests/projects/transitiveReferences/tsconfig.b.json b/tests/projects/transitiveReferences/tsconfig.b.json index f4734997f73..f5e23c38b76 100644 --- a/tests/projects/transitiveReferences/tsconfig.b.json +++ b/tests/projects/transitiveReferences/tsconfig.b.json @@ -1 +1,11 @@ -{"compilerOptions": {"composite": true}, "files": ["b.ts"], "references": [{"path": "tsconfig.a.json"}]} +{ + "compilerOptions": { + "composite": true, + "baseUrl": "./", + "paths": { + "@ref/*": [ "./*" ] + } + }, + "files": [ "b.ts" ], + "references": [ { "path": "tsconfig.a.json" } ] +} From 6923f2cdb0abede5755b20eb32782e4015b045d4 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 1 Oct 2018 16:07:52 -0700 Subject: [PATCH 006/262] Handle caching of module resolution depending on project references --- src/compiler/moduleNameResolver.ts | 110 +++++--- src/compiler/resolutionCache.ts | 13 +- src/testRunner/unittests/tsbuild.ts | 1 + src/testRunner/unittests/tsbuildWatchMode.ts | 248 ++++++++++++------ .../reference/api/tsserverlibrary.d.ts | 28 +- tests/baselines/reference/api/typescript.d.ts | 24 +- tests/projects/transitiveReferences/c.ts | 4 +- .../projects/transitiveReferences/refs/a.d.ts | 2 + .../transitiveReferences/tsconfig.c.json | 11 +- 9 files changed, 284 insertions(+), 157 deletions(-) create mode 100644 tests/projects/transitiveReferences/refs/a.d.ts diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 315bc394e56..c09c9542055 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -345,7 +345,7 @@ namespace ts { } let result: SearchResult | undefined; if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { - result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); } else { const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)); @@ -415,7 +415,7 @@ namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ export interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** @@ -423,7 +423,7 @@ namespace ts { * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ export interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } export interface PerModuleNameCache { @@ -433,40 +433,78 @@ namespace ts { export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache { return createModuleResolutionCacheWithMaps( - createMap>(), - createMap(), + createCacheWithRedirects(), + createCacheWithRedirects(), currentDirectory, getCanonicalFileName ); } + /*@internal*/ + export interface CacheWithRedirects { + ownMap: Map; + redirectsMap: Map>; + getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map; + clear(): void; + } + + /*@internal*/ + export function createCacheWithRedirects(): CacheWithRedirects { + const ownMap: Map = createMap(); + const redirectsMap: Map> = createMap(); + return { + ownMap, + redirectsMap, + getOrCreateMapOfCacheRedirects, + clear + }; + + function getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined) { + if (!redirectedReference) { + return ownMap; + } + const path = redirectedReference.sourceFile.path; + let redirects = redirectsMap.get(path); + if (!redirects) { + redirects = createMap(); + redirectsMap.set(path, redirects); + } + return redirects; + } + + function clear() { + ownMap.clear(); + redirectsMap.clear(); + } + } + /*@internal*/ export function createModuleResolutionCacheWithMaps( - directoryToModuleNameMap: Map>, - moduleNameToDirectoryMap: Map, + directoryToModuleNameMap: CacheWithRedirects>, + moduleNameToDirectoryMap: CacheWithRedirects, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): ModuleResolutionCache { return { getOrCreateCacheForDirectory, getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName: string) { + function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) { const path = toPath(directoryName, currentDirectory, getCanonicalFileName); - let perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; + return getOrCreateCache>(directoryToModuleNameMap, redirectedReference, path, createMap); } - function getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache { + function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache { Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName)); - let perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache); + } + + function getOrCreateCache(cacheWithRedirects: CacheWithRedirects, redirectedReference: ResolvedProjectReference | undefined, key: string, create: () => T): T { + const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); + let result = cache.get(key); + if (!result) { + result = create(); + cache.set(key, result); } - return perModuleNameCache; + return result; } function createPerModuleNameCache(): PerModuleNameCache { @@ -560,7 +598,7 @@ namespace ts { } } const containingDirectory = getDirectoryPath(containingFile); - const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference); let result = perFolderCache && perFolderCache.get(moduleName); if (result) { @@ -584,10 +622,10 @@ namespace ts { switch (moduleResolution) { case ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; case ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); + result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); @@ -597,7 +635,7 @@ namespace ts { perFolderCache.set(moduleName, result); if (!isExternalModuleNameRelative(moduleName)) { // put result in per-module name cache - cache!.getOrCreateCacheForModuleName(moduleName).set(containingDirectory, result); + cache!.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result); } } } @@ -817,14 +855,14 @@ namespace ts { } function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*redirectedReference*/ undefined, /*jsOnly*/ true); } - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, redirectedReference, /*jsOnly*/ false); } - function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; @@ -852,7 +890,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); + const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved) return undefined; let resolvedValue = resolved.value; @@ -1190,17 +1228,17 @@ namespace ts { return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); + function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference); } function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName: string, directory: string, state: ModuleResolutionState): SearchResult { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined); } - function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult { + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); @@ -1368,7 +1406,7 @@ namespace ts { } } - export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations { + export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; @@ -1385,7 +1423,7 @@ namespace ts { } if (!isExternalModuleNameRelative(moduleName)) { - const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference); // Climb up parent directories looking for a module. const resolved = forEachAncestorDirectory(containingDirectory, directory => { const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, state); diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 809a649520d..42df1eb9a24 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -90,17 +90,17 @@ namespace ts { // The key in the map is source file's path. // The values are Map of resolutions with key being name lookedup. const resolvedModuleNames = createMap>(); - const perDirectoryResolvedModuleNames = createMap>(); - const nonRelaticeModuleNameCache = createMap(); + const perDirectoryResolvedModuleNames: CacheWithRedirects> = createCacheWithRedirects(); + const nonRelativeModuleNameCache: CacheWithRedirects = createCacheWithRedirects(); const moduleResolutionCache = createModuleResolutionCacheWithMaps( perDirectoryResolvedModuleNames, - nonRelaticeModuleNameCache, + nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName ); const resolvedTypeReferenceDirectives = createMap>(); - const perDirectoryResolvedTypeReferenceDirectives = createMap>(); + const perDirectoryResolvedTypeReferenceDirectives: CacheWithRedirects> = createCacheWithRedirects(); /** * These are the extensions that failed lookup files will have by default, @@ -199,7 +199,7 @@ namespace ts { function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -244,7 +244,7 @@ namespace ts { containingFile: string, redirectedReference: ResolvedProjectReference | undefined, cache: Map>, - perDirectoryCache: Map>, + perDirectoryCacheWithRedirects: CacheWithRedirects>, loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, reusedNames: string[] | undefined, @@ -253,6 +253,7 @@ namespace ts { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = cache.get(path) || cache.set(path, createMap()).get(path)!; const dirPath = getDirectoryPath(path); + const perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference); let perDirectoryResolution = perDirectoryCache.get(dirPath); if (!perDirectoryResolution) { perDirectoryResolution = createMap(); diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index bb219ced37c..34e83eab43e 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -392,6 +392,7 @@ export class cNew {}`); ...getLibs(), "/src/a.d.ts", "/src/b.d.ts", + "/src/refs/a.d.ts", "/src/c.ts" ]); }); diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 2ffe51189d8..87116a28202 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -26,8 +26,23 @@ namespace ts.tscWatch { type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; const root = Harness.IO.getWorkspaceRoot(); + function getProjectPath(project: string) { + return `${projectsLocation}/${project}`; + } + + function getFilePathInProject(project: string, file: string) { + return `${projectsLocation}/${project}/${file}`; + } + + function getFileFromProject(project: string, file: string): File { + return { + path: getFilePathInProject(project, file), + content: Harness.IO.readFile(`${root}/tests/projects/${project}/${file}`)! + }; + } + function projectPath(subProject: SubProject) { - return `${projectsLocation}/${project}/${subProject}`; + return getFilePathInProject(project, subProject); } function projectFilePath(subProject: SubProject, baseFileName: string) { @@ -39,10 +54,7 @@ namespace ts.tscWatch { } function projectFile(subProject: SubProject, baseFileName: string): File { - return { - path: projectFilePath(subProject, baseFileName), - content: Harness.IO.readFile(`${root}/tests/projects/${project}/${subProject}/${baseFileName}`)! - }; + return getFileFromProject(project, `${subProject}/${baseFileName}`); } function subProjectFiles(subProject: SubProject, anotherModuleAndSomeDecl?: true): SubProjectFiles { @@ -97,7 +109,7 @@ namespace ts.tscWatch { const tests = subProjectFiles(SubProject.tests); const ui = subProjectFiles(SubProject.ui); const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; - const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); + const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path.toLowerCase()); const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)]; function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { @@ -244,7 +256,7 @@ export class someClass2 { }`); const allFiles = [libFile, ...core, logic[1], ...tests]; const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); - checkWatchedFiles(host, [core[0], core[1], core[2], logic[0], ...tests].map(f => f.path)); + checkWatchedFiles(host, [core[0], core[1], core[2], logic[0], ...tests].map(f => f.path.toLowerCase())); checkWatchedDirectories(host, emptyArray, /*recursive*/ false); checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true); checkOutputErrorsInitial(host, [ @@ -395,99 +407,161 @@ let x: string = 10;`); }); describe("tsc-watch works with project references", () => { - const coreIndexDts = projectFileName(SubProject.core, "index.d.ts"); - const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts"); - const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts"); - const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())); - const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); - - function createSolution() { - const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); - const solutionBuilder = createSolutionBuilder(host, [`${project}/${SubProject.tests}`], {}); - return { host, solutionBuilder }; - } - - function createBuiltSolution() { - const result = createSolution(); - const { host, solutionBuilder } = result; - solutionBuilder.buildAllProjects(); - const outputFileStamps = getOutputFileStamps(host); - for (const stamp of outputFileStamps) { - assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); - } - return result; - } - - function verifyWatches(host: WatchedSystem) { - checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); - } - - function createSolutionAndWatchMode() { - // Build the composite project - const { host, solutionBuilder } = createBuiltSolution(); - - // Build in watch mode - const watch = createWatchOfConfigFileReturningBuilder(tests[0].path, host); - checkOutputErrorsInitial(host, emptyArray); - - return { host, solutionBuilder, watch }; - } - - function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray) { - checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected); - } - describe("invoking when references are already built", () => { - it("verifies dependencies and watches", () => { - const { host, watch } = createSolutionAndWatchMode(); + function verifyWatchesOfProject(host: WatchedSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray) { + checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); + } - verifyWatches(host); - verifyDependencies(watch, coreIndexDts, [coreIndexDts]); - verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); - verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); - verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]); - }); + function createSolutionAndWatchModeOfProject( + allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + watchConfig: string, + getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray) { + // Build the composite project + const host = createWatchedSystem(allFiles, { currentDirectory }); + const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {}); + solutionBuilder.buildAllProjects(); + const outputFileStamps = getOutputFileStamps(host); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } - it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[1].path, `${logic[1].content} + // Build in watch mode + const watch = createWatchOfConfigFileReturningBuilder(watchConfig, host); + checkOutputErrorsInitial(host, emptyArray); + + return { host, solutionBuilder, watch }; + } + + function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray) { + checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected); + } + + describe("on sample project", () => { + const coreIndexDts = projectFileName(SubProject.core, "index.d.ts"); + const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts"); + const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts"); + const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())); + const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); + + function createSolutionAndWatchMode() { + return createSolutionAndWatchModeOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[0].path, getOutputFileStamps); + } + + function verifyWatches(host: WatchedSystem) { + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + } + + it("verifies dependencies and watches", () => { + const { host, watch } = createSolutionAndWatchMode(); + + verifyWatches(host); + verifyDependencies(watch, coreIndexDts, [coreIndexDts]); + verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); + verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); + verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]); + }); + + it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[1].path, `${logic[1].content} function foo() { }`); - solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); - solutionBuilder.buildInvalidatedProject(); + solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); + solutionBuilder.buildInvalidatedProject(); - host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); - }); + host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + }); - it("non local edit in ts file, rebuilds in watch compilation", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[1].path, `${logic[1].content} + it("non local edit in ts file, rebuilds in watch compilation", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[1].path, `${logic[1].content} export function gfoo() { }`); - solutionBuilder.invalidateProject(logic[0].path); - solutionBuilder.buildInvalidatedProject(); + solutionBuilder.invalidateProject(logic[0].path); + solutionBuilder.buildInvalidatedProject(); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + }); + + it("change in project reference config file builds correctly", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + host.writeFile(logic[0].path, JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); + solutionBuilder.buildInvalidatedProject(); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); + }); }); - it("change in project reference config file builds correctly", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[0].path, JSON.stringify({ - compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, - references: [{ path: "../core" }] - })); - solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); - solutionBuilder.buildInvalidatedProject(); + describe("on transitive references", () => { + const project = "transitiveReferences"; + const aTs = getFileFromProject(project, "a.ts"); + const bTs = getFileFromProject(project, "b.ts"); + const cTs = getFileFromProject(project, "c.ts"); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); + const configToBuild = "tsconfig.c.json"; + const aTsconfig = getFileFromProject(project, "tsconfig.a.json"); + const bTsconfig = getFileFromProject(project, "tsconfig.b.json"); + const cTsconfig = getFileFromProject(project, configToBuild); + const refs = getFileFromProject(project, "refs/a.d.ts"); + const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs]; + const aDts = dtsFile("a"), bDts = dtsFile("b"); + const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")]; + const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts]; + const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); + const expectedWatchedDirectoriesRecursive = [ + getFilePathInProject(project, "refs").toLowerCase(), // Failed lookup since refs/a.ts does not exist + ...projectSystem.getTypeRootsFromLocation(getProjectPath(project).toLowerCase())]; + + function jsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.js`); + } + + function dtsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.d.ts`); + } + + function createSolutionAndWatchMode() { + return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); + } + + function getOutputFileStamps(host: WatchedSystem) { + return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); + } + + function verifyWatches(host: WatchedSystem) { + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + } + + function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { + verifyWatches(host); + + verifyDependencies(watch, aDts, [aDts]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, bDts, [bDts, aDts]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + } + + it("verifies dependencies and watches", () => { + // Initial build + const { host, watch } = createSolutionAndWatchMode(); + verifyProgram(host, watch); + }); }); }); }); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 942b3978e75..0df8c4643ff 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2688,11 +2688,11 @@ declare namespace ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } @@ -3606,7 +3606,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -3621,14 +3621,14 @@ declare namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -3636,9 +3636,9 @@ declare namespace ts { } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; @@ -4384,9 +4384,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; } /** * Host to create watch with root files and options @@ -4654,9 +4654,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. @@ -8129,9 +8129,9 @@ declare namespace ts.server { readFile(fileName: string): string | undefined; writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; log(s: string): void; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index ee9ce336ad9..55b4b10e5c2 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2688,11 +2688,11 @@ declare namespace ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } @@ -3606,7 +3606,7 @@ declare namespace ts { * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups * is assumed to be the same as root directory of the project. */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -3621,14 +3621,14 @@ declare namespace ts { * This assumes that any module id will have the same resolution for sibling files located in the same folder. */ interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; + getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map; } /** * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. */ interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache; } interface PerModuleNameCache { get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -3636,9 +3636,9 @@ declare namespace ts { } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; @@ -4384,9 +4384,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; } /** * Host to create watch with root files and options @@ -4654,9 +4654,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. diff --git a/tests/projects/transitiveReferences/c.ts b/tests/projects/transitiveReferences/c.ts index b436b3db99c..d45b2621f3e 100644 --- a/tests/projects/transitiveReferences/c.ts +++ b/tests/projects/transitiveReferences/c.ts @@ -1,2 +1,4 @@ import {b} from './b'; -console.log(b); \ No newline at end of file +import {X} from "@ref/a"; +b; +X; \ No newline at end of file diff --git a/tests/projects/transitiveReferences/refs/a.d.ts b/tests/projects/transitiveReferences/refs/a.d.ts new file mode 100644 index 00000000000..9a5b34f9a2b --- /dev/null +++ b/tests/projects/transitiveReferences/refs/a.d.ts @@ -0,0 +1,2 @@ +export class X {} +export class A {} diff --git a/tests/projects/transitiveReferences/tsconfig.c.json b/tests/projects/transitiveReferences/tsconfig.c.json index 1f919a04cd9..c9ddec97111 100644 --- a/tests/projects/transitiveReferences/tsconfig.c.json +++ b/tests/projects/transitiveReferences/tsconfig.c.json @@ -1 +1,10 @@ -{"files": ["c.ts"], "references": [{"path": "tsconfig.b.json"}]} +{ + "files": [ "c.ts" ], + "compilerOptions": { + "baseUrl": "./", + "paths": { + "@ref/*": [ "./refs/*" ] + } + }, + "references": [ { "path": "tsconfig.b.json" } ] +} From 4d413a6a55ab92d90c8c9f3b59e45c24e5e100cd Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 2 Oct 2018 13:11:12 -0700 Subject: [PATCH 007/262] Fix the fileByName cache when program is used completely which breaks the getSourceFile not return redirected file by its name --- src/compiler/program.ts | 28 +++++++++++--------- src/testRunner/unittests/tsbuildWatchMode.ts | 15 +++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 416c2d218eb..e7caa7048cb 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1095,7 +1095,6 @@ namespace ts { // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; - const filePaths: Path[] = []; const modifiedSourceFiles: { oldFile: SourceFile, newFile: SourceFile }[] = []; oldProgram.structureIsReused = StructureIsReused.Completely; @@ -1148,7 +1147,6 @@ namespace ts { newSourceFile.originalFileName = oldSourceFile.originalFileName; newSourceFile.resolvedPath = oldSourceFile.resolvedPath; newSourceFile.fileName = oldSourceFile.fileName; - filePaths.push(newSourceFile.path); const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -1266,11 +1264,12 @@ namespace ts { missingFilePaths = oldProgram.getMissingFilePaths(); // update fileName -> file mapping - for (let i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); + for (const newSourceFile of newSourceFiles) { + const filePath = newSourceFile.path; + addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath); // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i])!)) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePath)!)) { + sourceFilesFoundSearchingNodeModules.set(filePath, true); } } @@ -2113,7 +2112,7 @@ namespace ts { return file; } - let redirectedPath: string | undefined; + let redirectedPath: Path | undefined; if (refFile) { const redirect = getProjectReferenceRedirect(fileName); if (redirect) { @@ -2147,7 +2146,7 @@ namespace ts { // Instead of creating a duplicate, just redirect to the existing one. const dupFile = createRedirectSourceFile(fileFromPackageId, file!, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); - filesByName.set(path, dupFile); + addFileToFilesByName(dupFile, path, redirectedPath); sourceFileToPackageName.set(path, packageId.name); processingOtherFiles!.push(dupFile); return dupFile; @@ -2158,11 +2157,7 @@ namespace ts { sourceFileToPackageName.set(path, packageId.name); } } - - filesByName.set(path, file); - if (redirectedPath) { - filesByName.set(redirectedPath, file); - } + addFileToFilesByName(file, path, redirectedPath); if (file) { sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); @@ -2205,6 +2200,13 @@ namespace ts { return file; } + function addFileToFilesByName(file: SourceFile | undefined, path: Path, redirectedPath: Path | undefined) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, file); + } + } + function getProjectReferenceRedirect(fileName: string): string | undefined { // Ignore dts or any of the non ts files if (!resolvedProjectReferences || !resolvedProjectReferences.length || fileExtensionIs(fileName, Extension.Dts) || !fileExtensionIsOneOf(fileName, supportedTSExtensions)) { diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 87116a28202..4226ae2e02a 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -562,6 +562,21 @@ export function gfoo() { const { host, watch } = createSolutionAndWatchMode(); verifyProgram(host, watch); }); + + it("non local edit updates the program and watch correctly", () => { + const { host, watch, solutionBuilder } = createSolutionAndWatchMode(); + + // edit + host.writeFile(bTs.path, `${bTs.content} +export function gfoo() { +}`); + solutionBuilder.invalidateProject(bTsconfig.path); + solutionBuilder.buildInvalidatedProject(); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); }); }); }); From d4e4b432391dc5028b578375fb07c275d960136c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 2 Oct 2018 13:36:06 -0700 Subject: [PATCH 008/262] Verify that own config change in module resolution gets reflected --- src/testRunner/unittests/tsbuildWatchMode.ts | 40 ++++++++++++++------ 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 4226ae2e02a..242c55f8200 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -542,19 +542,13 @@ export function gfoo() { return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); } - function verifyWatches(host: WatchedSystem) { - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); - } - function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { - verifyWatches(host); - - verifyDependencies(watch, aDts, [aDts]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, bDts, [bDts, aDts]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyDependencies(watch, aDts, [aDts]); + verifyDependencies(watch, bDts, [bDts, aDts]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); } it("verifies dependencies and watches", () => { @@ -577,6 +571,30 @@ export function gfoo() { checkOutputErrorsIncremental(host, emptyArray); verifyProgram(host, watch); }); + + it("edit on config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: refs.content + }; + const cTsConfigJson = JSON.parse(cTsconfig.content); + host.ensureFileOrFolder(nrefs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": ["./nrefs/*"] }; + host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + + const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); + verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer)); + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(nrefReplacer)); + verifyDependencies(watch, aDts, [aDts]); + verifyDependencies(watch, bDts, [bDts, aDts]); + verifyDependencies(watch, nrefs.path, [nrefs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, nrefs.path, bDts]); + }); }); }); }); From 94df5167b0ecec912a5d63af2ec3b2f4c5b032f1 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 2 Oct 2018 14:10:19 -0700 Subject: [PATCH 009/262] Handle resolution caching when referenced tsconfig changes --- src/compiler/commandLineParser.ts | 2 + src/compiler/program.ts | 161 ++++++++++++------ src/compiler/resolutionCache.ts | 26 ++- src/compiler/types.ts | 5 +- src/compiler/watch.ts | 11 +- src/server/editorServices.ts | 38 +++-- src/server/project.ts | 36 ++-- src/services/services.ts | 2 +- src/testRunner/unittests/projectReferences.ts | 2 +- src/testRunner/unittests/tsbuildWatchMode.ts | 66 ++++++- .../unittests/tsserverProjectSystem.ts | 2 +- 11 files changed, 253 insertions(+), 98 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index b1cc4ef5b27..1c6265c9454 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1294,6 +1294,8 @@ namespace ts { const result = parseJsonText(configFileName, configFileText); const cwd = host.getCurrentDirectory(); result.path = toPath(configFileName, cwd, createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + result.resolvedPath = result.path; + result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd)); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index e7caa7048cb..db621f4e214 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -487,7 +487,7 @@ namespace ts { function sourceFileNotUptoDate(sourceFile: SourceFile) { return !sourceFileVersionUptoDate(sourceFile) || - hasInvalidatedResolution(sourceFile.resolvedPath); + hasInvalidatedResolution(sourceFile.path); } function sourceFileVersionUptoDate(sourceFile: SourceFile) { @@ -752,10 +752,18 @@ namespace ts { if (oldProgram && host.onReleaseOldSourceFile) { const oldSourceFiles = oldProgram.getSourceFiles(); for (const oldSourceFile of oldSourceFiles) { - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); + if (shouldCreateNewSourceFile || !newFile || + // old file wasnt redirect but new file is + (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path)); } } + oldProgram.forEachResolvedProjectReference((resolvedProjectReference, resolvedProjectReferencePath) => { + if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + host.onReleaseOldSourceFile!(resolvedProjectReference.sourceFile, oldProgram!.getCompilerOptions(), /*hasSourceFileByPath*/ false); + } + }); } // unconditionally set oldProgram to undefined to prevent it from being captured in closure @@ -798,7 +806,10 @@ namespace ts { getResolvedModuleWithFailedLookupLocationsFromCache, getProjectReferences, getResolvedProjectReferences, - getProjectReferenceRedirect + getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath, + forEachResolvedProjectReference }; verifyCompilerOptions(); @@ -881,7 +892,7 @@ namespace ts { if (structuralIsReused === StructureIsReused.Not && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getProjectReferenceRedirectProject(file.originalFileName)); + return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } const oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); @@ -961,7 +972,7 @@ namespace ts { } const resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getProjectReferenceRedirectProject(file.originalFileName)) + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName)) : emptyArray; // Combine results of resolutions and predicted results @@ -1021,46 +1032,28 @@ namespace ts { } } - function canReuseProjectReferences( - newProjectReferences: ReadonlyArray | undefined, - oldProjectReferences: ReadonlyArray | undefined, - oldResolvedReferences: ReadonlyArray | undefined): boolean { - // If array of references is changed, we cant resue old program - if (!arrayIsEqualTo(oldProjectReferences!, newProjectReferences, projectReferenceIsEqualTo)) { - return false; - } - - // Check the json files for the project references - if (newProjectReferences) { - // Resolved project referenced should be array if projectReferences provided are array - Debug.assert(!!oldResolvedReferences); - for (let i = 0; i < newProjectReferences.length; i++) { - const oldRef = oldResolvedReferences![i]; - const newRef = parseProjectReferenceConfigFile(newProjectReferences[i]); - if (oldRef) { - if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { - // Resolved project reference has gone missing or changed - return false; - } - - // If the transitive references can be reused then only this reference can be reused - if (!canReuseProjectReferences(newRef.commandLine.projectReferences, oldRef.commandLine.projectReferences, oldRef.references)) { - return false; - } + function canReuseProjectReferences(): boolean { + return !forEachProjectReference( + oldProgram!.getProjectReferences(), + oldProgram!.getResolvedProjectReferences(), + (oldResolvedRef, index, parent) => { + const newRef = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const newResolvedRef = parseProjectReferenceConfigFile(newRef); + if (oldResolvedRef) { + // Resolved project reference has gone missing or changed + return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile; } else { // A previously-unresolved reference may be resolved now - if (newRef !== undefined) { - return false; - } + return newResolvedRef !== undefined; } + }, + (oldProjectReferences, parent) => { + // If array of references is changed, we cant resue old program + const newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path)!.commandLine.projectReferences : projectReferences; + return !arrayIsEqualTo(oldProjectReferences, newReferences, projectReferenceIsEqualTo); } - } - else { - // Resolved project referenced should be undefined if projectReferences is undefined - Debug.assert(!oldResolvedReferences); - } - return true; + ); } function tryReuseStructureFromOldProgram(): StructureIsReused { @@ -1088,7 +1081,7 @@ namespace ts { } // Check if any referenced project tsconfig files are different - if (!canReuseProjectReferences(projectReferences, oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences())) { + if (!canReuseProjectReferences()) { return oldProgram.structureIsReused = StructureIsReused.Not; } resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); @@ -1240,7 +1233,7 @@ namespace ts { if (resolveTypeReferenceDirectiveNamesWorker) { // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase()); - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getProjectReferenceRedirectProject(newSourceFile.originalFileName)); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName)); // ensure that types resolutions are still correct const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -2215,7 +2208,7 @@ namespace ts { // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - const referencedProject = getProjectReferenceRedirectProject(fileName); + const referencedProject = getResolvedProjectReferenceToRedirect(fileName); if (!referencedProject) { return undefined; } @@ -2229,16 +2222,11 @@ namespace ts { /** * Get the referenced project if the file is input file from that reference project */ - function getProjectReferenceRedirectProject(fileName: string) { - if (!resolvedProjectReferences || !resolvedProjectReferences.length) { - return undefined; - } - - // If this file is input file of the referenced projec - return forEachEntry(projectReferenceRedirects!, referencedProject => { + function getResolvedProjectReferenceToRedirect(fileName: string) { + return forEachResolvedProjectReference((referencedProject, referenceProjectPath) => { // not input file from the referenced project, ignore if (!referencedProject || - options.configFilePath === referencedProject.commandLine.options.configFilePath || + toPath(options.configFilePath!) === referenceProjectPath || !contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } @@ -2247,6 +2235,67 @@ namespace ts { }); } + function forEachResolvedProjectReference( + cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined + ): T | undefined { + return forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => { + const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const resolvedRefPath = toPath(resolveProjectReferencePath(ref)); + return cb(resolvedRef, resolvedRefPath); + }); + } + + function forEachProjectReference( + projectReferences: ReadonlyArray | undefined, + resolvedProjectReferences: ReadonlyArray | undefined, + cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, + cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined + ): T | undefined { + let seenResolvedRefs: ResolvedProjectReference[] | undefined; + + return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef); + + function worker( + projectReferences: ReadonlyArray | undefined, + resolvedProjectReferences: ReadonlyArray | undefined, + parent: ResolvedProjectReference | undefined, + cbResolvedRef: (resolvedRef: ResolvedProjectReference | undefined, index: number, parent: ResolvedProjectReference | undefined) => T | undefined, + cbRef?: (projectReferences: ReadonlyArray | undefined, parent: ResolvedProjectReference | undefined) => T | undefined, + ): T | undefined { + + // Visit project references first + if (cbRef) { + const result = cbRef(projectReferences, parent); + if (result) { return result; } + } + + return forEach(resolvedProjectReferences, (resolvedRef, index) => { + if (contains(seenResolvedRefs, resolvedRef)) { + // ignore recursives + return undefined; + } + + const result = cbResolvedRef(resolvedRef, index, parent); + if (result) { + return result; + } + + if (!resolvedRef) return undefined; + + (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef); + return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef); + }); + } + } + + function getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined { + if (!projectReferenceRedirects) { + return undefined; + } + + return projectReferenceRedirects.get(projectReferencePath) || undefined; + } + function processReferencedFiles(file: SourceFile, isDefaultLib: boolean) { forEach(file.referencedFiles, ref => { const referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); @@ -2261,7 +2310,7 @@ namespace ts { return; } - const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getProjectReferenceRedirectProject(file.originalFileName)); + const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName)); for (let i = 0; i < typeDirectives.length; i++) { const ref = file.typeReferenceDirectives[i]; @@ -2450,11 +2499,14 @@ namespace ts { // An absolute path pointing to the containing directory of the config file const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile | undefined; + addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); if (sourceFile === undefined) { projectReferenceRedirects.set(sourceFilePath, false); return undefined; } sourceFile.path = sourceFilePath; + sourceFile.resolvedPath = sourceFilePath; + sourceFile.originalFileName = refPath; const commandLine = parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); const resolvedRef: ResolvedProjectReference = { commandLine, sourceFile }; projectReferenceRedirects.set(sourceFilePath, resolvedRef); @@ -2506,12 +2558,13 @@ namespace ts { } } + //TODO:: Errors on transitive references if (projectReferences) { for (let i = 0; i < projectReferences.length; i++) { const ref = projectReferences[i]; const resolvedRefOpts = resolvedProjectReferences![i] && resolvedProjectReferences![i]!.commandLine.options; if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, Diagnostics.File_0_does_not_exist, ref.path); + createDiagnosticForReference(i, Diagnostics.File_0_not_found, ref.path); continue; } if (!resolvedRefOpts.composite) { diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 42df1eb9a24..b462ab96b1a 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -11,6 +11,7 @@ namespace ts { invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; + removeResolutionsFromProjectReferenceRedirects(filePath: Path): void; setFilesWithInvalidatedNonRelativeUnresolvedImports(filesWithUnresolvedImports: Map>): void; createHasInvalidatedResolution(forceAllFilesAsInvalidated?: boolean): HasInvalidatedResolution; @@ -128,6 +129,7 @@ namespace ts { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -262,12 +264,20 @@ namespace ts { const resolvedModules: R[] = []; const compilerOptions = resolutionHost.getCompilationSettings(); const hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); + + // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect + const program = resolutionHost.getCurrentProgram(); + const oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile); + const unmatchedRedirects = oldRedirect ? + !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path : + !!redirectedReference; + const seenNamesInFile = createMap(); for (const name of names) { let resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { const existingResolution = resolution; @@ -596,6 +606,20 @@ namespace ts { } } + function removeResolutionsFromProjectReferenceRedirects(filePath: Path) { + if (!fileExtensionIs(filePath, Extension.Json)) { return; } + + const program = resolutionHost.getCurrentProgram(); + if (!program) { return; } + + // If this file is input file for the referenced project, get it + const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); + if (!resolvedProjectReference) { return; } + + // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution + resolvedProjectReference.commandLine.fileNames.forEach(f => removeResolutionsOfFile(resolutionHost.toPath(f))); + } + function removeResolutionsOfFile(filePath: Path) { removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index eb5ab188796..8d8282615fa 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2831,6 +2831,9 @@ namespace ts { getProjectReferences(): ReadonlyArray | undefined; getResolvedProjectReferences(): ReadonlyArray | undefined; /*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined; + /*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined; + /*@internal*/ forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined; + /*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined; } /* @internal */ @@ -4882,7 +4885,7 @@ namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; - /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions): void; + /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; createHash?(data: string): string; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 34cd1a4a107..ff39b61e481 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -764,8 +764,8 @@ namespace ts { return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); } - function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions) { - const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions, hasSourceFileByPath: boolean) { + const hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); // If this is the source file thats in the cache and new program doesnt need it, // remove the cached entry. // Note we arent deleting entry if file became missing in new program or @@ -779,8 +779,10 @@ namespace ts { if ((hostSourceFileInfo as FilePresentOnHost).fileWatcher) { (hostSourceFileInfo as FilePresentOnHost).fileWatcher.close(); } - sourceFilesCache.delete(oldSourceFile.path); - resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + sourceFilesCache.delete(oldSourceFile.resolvedPath); + if (oldSourceFile.resolvedPath === oldSourceFile.path || !hasSourceFileByPath) { + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } } } } @@ -875,6 +877,7 @@ namespace ts { if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 32916f8308a..043c44f4834 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -871,15 +871,20 @@ namespace ts.server { if (!info) { this.logger.msg(`Error: got watch notification for unknown file: ${fileName}`); } - else if (eventKind === FileWatcherEventKind.Deleted) { - // File was deleted - this.handleDeletedFile(info); - } - else if (!info.isScriptOpen()) { - // file has been changed which might affect the set of referenced files in projects that include - // this file and set of inferred projects - info.delayReloadNonMixedContentFile(); - this.delayUpdateProjectGraphs(info.containingProjects); + else { + if (info.containingProjects) { + info.containingProjects.forEach(project => project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path)); + } + if (eventKind === FileWatcherEventKind.Deleted) { + // File was deleted + this.handleDeletedFile(info); + } + else if (!info.isScriptOpen()) { + // file has been changed which might affect the set of referenced files in projects that include + // this file and set of inferred projects + info.delayReloadNonMixedContentFile(); + this.delayUpdateProjectGraphs(info.containingProjects); + } } } @@ -2434,17 +2439,14 @@ namespace ts.server { } else { // If the configured project for project reference has more than zero references, keep it alive - const resolvedProjectReferences = project.getResolvedProjectReferences(); - if (resolvedProjectReferences) { - for (const ref of resolvedProjectReferences) { - if (ref) { - const refProject = this.configuredProjects.get(ref.sourceFile.path); - if (refProject && refProject.hasOpenRef()) { - toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); - } + project.forEachResolvedProjectReference(ref => { + if (ref) { + const refProject = this.configuredProjects.get(ref.sourceFile.path); + if (refProject && refProject.hasOpenRef()) { + toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath); } } - } + }); } }); diff --git a/src/server/project.ts b/src/server/project.ts index 2f3a0c203d4..dcdac0e201d 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -583,14 +583,11 @@ namespace ts.server { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - const projectReferences = this.program.getResolvedProjectReferences(); - if (projectReferences) { - for (const ref of projectReferences) { - if (ref) { - this.detachScriptInfoFromProject(ref.sourceFile.fileName); - } + this.program.forEachResolvedProjectReference(ref => { + if (ref) { + this.detachScriptInfoFromProject(ref.sourceFile.fileName); } - } + }); } // Release external files forEach(this.externalFiles, externalFile => this.detachScriptInfoIfNotRoot(externalFile)); @@ -925,12 +922,19 @@ namespace ts.server { if (hasNewProgram) { if (oldProgram) { for (const f of oldProgram.getSourceFiles()) { - if (this.program.getSourceFileByPath(f.path)) { - continue; + const newFile = this.program.getSourceFileByPath(f.resolvedPath); + if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { + // new program does not contain this file - detach it from the project + // - remove resolutions only if this is undirected file or doesnt have source file with the path in new program + this.detachScriptInfoFromProject(f.fileName, f.path !== f.resolvedPath && !!this.program.getSourceFileByPath(f.path)); } - // new program does not contain this file - detach it from the project - this.detachScriptInfoFromProject(f.fileName); } + + oldProgram.forEachResolvedProjectReference((resolvedProjectReference, resolvedProjectReferencePath) => { + if (resolvedProjectReference && !this.program.getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) { + this.detachScriptInfoFromProject(resolvedProjectReference.sourceFile.fileName); + } + }); } // Update the missing file paths watcher @@ -964,11 +968,13 @@ namespace ts.server { return hasNewProgram; } - private detachScriptInfoFromProject(uncheckedFileName: string) { + private detachScriptInfoFromProject(uncheckedFileName: string, noRemoveResolution?: boolean) { const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { scriptInfoToDetach.detachFromProject(this); - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + if (!noRemoveResolution) { + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); + } } } @@ -1400,9 +1406,9 @@ namespace ts.server { } /*@internal*/ - getResolvedProjectReferences() { + forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined { const program = this.getCurrentProgram(); - return program && program.getResolvedProjectReferences(); + return program && program.forEachResolvedProjectReference(cb); } enablePlugins() { diff --git a/src/services/services.ts b/src/services/services.ts index 662b471fe75..27a458bf1ef 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1276,7 +1276,7 @@ namespace ts { // not part of the new program. function onReleaseOldSourceFile(oldSourceFile: SourceFile, oldOptions: CompilerOptions) { const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); - documentRegistry.releaseDocumentWithKey(oldSourceFile.path, oldSettingsKey); + documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey); } function getOrCreateSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined { diff --git a/src/testRunner/unittests/projectReferences.ts b/src/testRunner/unittests/projectReferences.ts index 4702c0c26ce..53fcd4a9dd0 100644 --- a/src/testRunner/unittests/projectReferences.ts +++ b/src/testRunner/unittests/projectReferences.ts @@ -184,7 +184,7 @@ namespace ts { }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); - assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_does_not_exist); + assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_not_found); }); }); diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 242c55f8200..eed69251db5 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -543,8 +543,8 @@ export function gfoo() { } function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); verifyDependencies(watch, aDts, [aDts]); verifyDependencies(watch, bDts, [bDts, aDts]); verifyDependencies(watch, refs.path, [refs.path]); @@ -588,12 +588,74 @@ export function gfoo() { checkOutputErrorsIncremental(host, emptyArray); const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); - verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer)); checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(nrefReplacer)); + verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer)); verifyDependencies(watch, aDts, [aDts]); verifyDependencies(watch, bDts, [bDts, aDts]); verifyDependencies(watch, nrefs.path, [nrefs.path]); verifyDependencies(watch, cTs.path, [cTs.path, nrefs.path, bDts]); + + // revert the update + host.writeFile(cTsconfig.path, cTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("edit in referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: host.readFile(aDts)! + }; + const bTsConfigJson = JSON.parse(bTsconfig.content); + host.ensureFileOrFolder(nrefs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": ["./nrefs/*"] }; + host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + + const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), expectedWatchedDirectoriesRecursive.concat(getFilePathInProject(project, "nrefs").toLowerCase())); + verifyDependencies(watch, nrefs.path, [nrefs.path]); + verifyDependencies(watch, bDts, [bDts, nrefs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + + // revert the update + host.writeFile(bTsconfig.path, bTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("deleting referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + // Resolutions should change now + // Should map to b.ts instead with options from our own config + host.deleteFile(bTsconfig.path); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, [ + "tsconfig.c.json(9,21): error TS6053: File '/user/username/projects/transitiveReferences/tsconfig.b.json' not found.\n" + ]); + + const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()), expectedWatchedDirectoriesRecursive); + verifyDependencies(watch, bTs.path, [bTs.path, refs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bTs.path]); + + // revert the update + host.writeFile(bTsconfig.path, bTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); }); }); }); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index e031786c3aa..b4a87405ef9 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -5070,7 +5070,7 @@ namespace ts.projectSystem { function getFileNotFoundDiagnostic(configFile: File, relativeFileName: string): ConfigFileDiagnostic { const findString = `{"path":"./${relativeFileName}"}`; - const d = Diagnostics.File_0_does_not_exist; + const d = Diagnostics.File_0_not_found; const start = configFile.content.indexOf(findString); return { fileName: configFile.path, From 3e67cf43b00e31453b6e2dd60669cc41aaa8c803 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 3 Oct 2018 16:09:16 -0700 Subject: [PATCH 010/262] Verify errors on transitively referenced files --- src/compiler/program.ts | 93 ++++++++++---------- src/testRunner/unittests/tsbuildWatchMode.ts | 23 +++++ 2 files changed, 69 insertions(+), 47 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index db621f4e214..799d4cafa08 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -635,7 +635,6 @@ namespace ts { // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createMap(); let _compilerOptionsObjectLiteralSyntax: ObjectLiteralExpression | null | undefined; - let _referencesArrayLiteralSyntax: ArrayLiteralExpression | null | undefined; let moduleResolutionCache: ModuleResolutionCache | undefined; let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[]; @@ -1084,7 +1083,9 @@ namespace ts { if (!canReuseProjectReferences()) { return oldProgram.structureIsReused = StructureIsReused.Not; } - resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (projectReferences) { + resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); + } // check if program source files has changed in the way that can affect structure of the program const newSourceFiles: SourceFile[] = []; @@ -1827,11 +1828,22 @@ namespace ts { fileProcessingDiagnostics.getGlobalDiagnostics(), concatenate( programDiagnostics.getGlobalDiagnostics(), - options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : [] + getOptionsDiagnosticsOfConfigFile() ) )); } + function getOptionsDiagnosticsOfConfigFile() { + if (!options.configFile) { return emptyArray; } + let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + forEachResolvedProjectReference(resolvedRef => { + if (resolvedRef) { + diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + } + }); + return diagnostics; + } + function getGlobalDiagnostics(): Diagnostic[] { return sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } @@ -2558,31 +2570,7 @@ namespace ts { } } - //TODO:: Errors on transitive references - if (projectReferences) { - for (let i = 0; i < projectReferences.length; i++) { - const ref = projectReferences[i]; - const resolvedRefOpts = resolvedProjectReferences![i] && resolvedProjectReferences![i]!.commandLine.options; - if (resolvedRefOpts === undefined) { - createDiagnosticForReference(i, Diagnostics.File_0_not_found, ref.path); - continue; - } - if (!resolvedRefOpts.composite) { - createDiagnosticForReference(i, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - } - if (ref.prepend) { - const out = resolvedRefOpts.outFile || resolvedRefOpts.out; - if (out) { - if (!host.fileExists(out)) { - createDiagnosticForReference(i, Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); - } - } - else { - createDiagnosticForReference(i, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); - } - } - } - } + verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -2800,6 +2788,32 @@ namespace ts { } } + function verifyProjectReferences() { + forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => { + const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index]; + const parentFile = parent && parent.sourceFile as JsonSourceFile; + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path); + return; + } + const options = resolvedRef.commandLine.options; + if (!options.composite) { + createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + const out = options.outFile || options.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(parentFile, index, Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); + } + } + else { + createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + }); + } + function createDiagnosticForOptionPathKeyValue(key: string, valueIndex: number, message: DiagnosticMessage, arg0: string | number, arg1: string | number, arg2?: string | number) { let needCompilerDiagnostic = true; const pathsSyntax = getOptionPathsSyntax(); @@ -2856,10 +2870,11 @@ namespace ts { createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); } - function createDiagnosticForReference(index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) { - const referencesSyntax = getProjectReferencesSyntax(); + function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) { + const referencesSyntax = firstDefined(getTsConfigPropArray(sourceFile || options.configFile, "references"), + property => isArrayLiteralExpression(property.initializer) ? property.initializer : undefined); if (referencesSyntax && referencesSyntax.elements.length > index) { - programDiagnostics.add(createDiagnosticForNodeInSourceFile(options.configFile!, referencesSyntax.elements[index], message, arg0, arg1)); + programDiagnostics.add(createDiagnosticForNodeInSourceFile(sourceFile || options.configFile!, referencesSyntax.elements[index], message, arg0, arg1)); } else { programDiagnostics.add(createCompilerDiagnostic(message, arg0, arg1)); @@ -2876,22 +2891,6 @@ namespace ts { } } - function getProjectReferencesSyntax(): ArrayLiteralExpression | null { - if (_referencesArrayLiteralSyntax === undefined) { - _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile) { - const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile)!; // TODO: GH#18217 - for (const prop of getPropertyAssignment(jsonObjectLiteral, "references")) { - if (isArrayLiteralExpression(prop.initializer)) { - _referencesArrayLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _referencesArrayLiteralSyntax; - } - function getCompilerOptionsObjectLiteralSyntax() { if (_compilerOptionsObjectLiteralSyntax === undefined) { _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index eed69251db5..c6ede07d6f1 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -657,6 +657,29 @@ export function gfoo() { checkOutputErrorsIncremental(host, emptyArray); verifyProgram(host, watch); }); + + it("deleting transitively referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + host.deleteFile(aTsconfig.path); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, [ + "tsconfig.b.json(10,21): error TS6053: File '/user/username/projects/transitiveReferences/tsconfig.a.json' not found.\n" + ]); + + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(s => s.replace(aDts, aTs.path))); + verifyWatchesOfProject(host, expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), expectedWatchedDirectoriesRecursive); + verifyDependencies(watch, aTs.path, [aTs.path]); + verifyDependencies(watch, bDts, [bDts, aTs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + + // revert the update + host.writeFile(aTsconfig.path, aTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); }); }); }); From 2fb11d85309b6d4cbd6a72e9a71b766fa1691fb5 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 4 Oct 2018 11:41:53 -0700 Subject: [PATCH 011/262] Test transitive references in folders side by side so that later we can add tsserver tests as well --- src/compiler/watch.ts | 2 +- src/server/project.ts | 4 +- src/testRunner/unittests/tsbuildWatchMode.ts | 389 +++++++++++-------- 3 files changed, 234 insertions(+), 161 deletions(-) diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index ff39b61e481..261013e29b3 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -780,7 +780,7 @@ namespace ts { (hostSourceFileInfo as FilePresentOnHost).fileWatcher.close(); } sourceFilesCache.delete(oldSourceFile.resolvedPath); - if (oldSourceFile.resolvedPath === oldSourceFile.path || !hasSourceFileByPath) { + if (!hasSourceFileByPath) { resolutionCache.removeResolutionsOfFile(oldSourceFile.path); } } diff --git a/src/server/project.ts b/src/server/project.ts index dcdac0e201d..249a4cb2ee3 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -925,8 +925,8 @@ namespace ts.server { const newFile = this.program.getSourceFileByPath(f.resolvedPath); if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) { // new program does not contain this file - detach it from the project - // - remove resolutions only if this is undirected file or doesnt have source file with the path in new program - this.detachScriptInfoFromProject(f.fileName, f.path !== f.resolvedPath && !!this.program.getSourceFileByPath(f.path)); + // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution) + this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path)); } } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index c6ede07d6f1..4a60fb581c5 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -408,9 +408,9 @@ let x: string = 10;`); describe("tsc-watch works with project references", () => { describe("invoking when references are already built", () => { - function verifyWatchesOfProject(host: WatchedSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray) { + function verifyWatchesOfProject(host: WatchedSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray, expectedWatchedDirectories?: ReadonlyArray) { checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false); checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); } @@ -508,177 +508,250 @@ export function gfoo() { describe("on transitive references", () => { const project = "transitiveReferences"; - const aTs = getFileFromProject(project, "a.ts"); - const bTs = getFileFromProject(project, "b.ts"); - const cTs = getFileFromProject(project, "c.ts"); - - const configToBuild = "tsconfig.c.json"; - const aTsconfig = getFileFromProject(project, "tsconfig.a.json"); - const bTsconfig = getFileFromProject(project, "tsconfig.b.json"); - const cTsconfig = getFileFromProject(project, configToBuild); + const aTsFile = getFileFromProject(project, "a.ts"); + const bTsFile = getFileFromProject(project, "b.ts"); + const cTsFile = getFileFromProject(project, "c.ts"); + const aTsconfigFile = getFileFromProject(project, "tsconfig.a.json"); + const bTsconfigFile = getFileFromProject(project, "tsconfig.b.json"); + const cTsconfigFile = getFileFromProject(project, "tsconfig.c.json"); const refs = getFileFromProject(project, "refs/a.d.ts"); - const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs]; - const aDts = dtsFile("a"), bDts = dtsFile("b"); - const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")]; - const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts]; - const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); - const expectedWatchedDirectoriesRecursive = [ - getFilePathInProject(project, "refs").toLowerCase(), // Failed lookup since refs/a.ts does not exist - ...projectSystem.getTypeRootsFromLocation(getProjectPath(project).toLowerCase())]; - function jsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.js`); + function getRootFile(multiFolder: boolean, fileFromDisk: File, multiFolderPath: string): File { + return multiFolder ? { + path: getFilePathInProject(project, multiFolderPath), + content: fileFromDisk.content + // Replace the relative imports + .replace("./", "../") + } : fileFromDisk; } - function dtsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.d.ts`); + function getTsConfigFile(multiFolder: boolean, fileFromDisk: File, folder: string): File { + if (!multiFolder) return fileFromDisk; + + return { + path: getFilePathInProject(project, `${folder}/tsconfig.json`), + content: fileFromDisk.content + // Replace files array + .replace(`${folder}.ts`, "index.ts") + // Replace path mappings + .replace("./*", "../*") + .replace("./refs", "../refs") + // Replace references + .replace("tsconfig.a.json", "../a") + .replace("tsconfig.b.json", "../b") + }; } - function createSolutionAndWatchMode() { - return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); - } + // function writeFile(file: File) { + // Harness.IO.writeFile(file.path.replace(projectsLocation, "c:/temp"), file.content); + // } - function getOutputFileStamps(host: WatchedSystem) { - return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); - } + function verifyTransitiveReferences(multiFolder: boolean) { + const aTs = getRootFile(multiFolder, aTsFile, "a/index.ts"); + const bTs = getRootFile(multiFolder, bTsFile, "b/index.ts"); + const cTs = getRootFile(multiFolder, cTsFile, "c/index.ts"); - function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); - verifyDependencies(watch, aDts, [aDts]); - verifyDependencies(watch, bDts, [bDts, aDts]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - } + const configToBuild = multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"; + const aTsconfig = getTsConfigFile(multiFolder, aTsconfigFile, "a"); + const bTsconfig = getTsConfigFile(multiFolder, bTsconfigFile, "b"); + const cTsconfig = getTsConfigFile(multiFolder, cTsconfigFile, "c"); - it("verifies dependencies and watches", () => { - // Initial build - const { host, watch } = createSolutionAndWatchMode(); - verifyProgram(host, watch); - }); + // if (multiFolder) { + // writeFile(aTs); + // writeFile(bTs); + // writeFile(cTs); + // writeFile(aTsconfig); + // writeFile(bTsconfig); + // writeFile(cTsconfig); + // } - it("non local edit updates the program and watch correctly", () => { - const { host, watch, solutionBuilder } = createSolutionAndWatchMode(); + const allFiles = [libFile, aTs, bTs, cTs, aTsconfig, bTsconfig, cTsconfig, refs]; + const aDts = dtsFile(multiFolder ? "a/index" : "a"), bDts = dtsFile(multiFolder ? "b/index" : "b"); + const expectedFiles = [jsFile(multiFolder ? "a/index" : "a"), aDts, jsFile(multiFolder ? "b/index" : "b"), bDts, jsFile(multiFolder ? "c/index" : "c")]; + const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts]; + const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()); + const expectedWatchedDirectories = multiFolder ? [ + getProjectPath(project).toLowerCase() // watches for directories created for resolution of b + ] : emptyArray; + const nrefsPath = multiFolder ? ["../nrefs/*"] : ["./nrefs/*"]; + const expectedWatchedDirectoriesRecursive = [ + ...(multiFolder ? [ + getFilePathInProject(project, "a"), // Failed to package json + getFilePathInProject(project, "b"), // Failed to package json + ] : []), + getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist + ...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project)) + ].map(s => s.toLowerCase()); - // edit - host.writeFile(bTs.path, `${bTs.content} + function jsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.js`); + } + + function dtsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.d.ts`); + } + + function createSolutionAndWatchMode() { + return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); + } + + function getOutputFileStamps(host: WatchedSystem) { + return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); + } + + function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + verifyDependencies(watch, aDts, [aDts]); + verifyDependencies(watch, bDts, [bDts, aDts]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + } + + it("verifies dependencies and watches", () => { + // Initial build + const { host, watch } = createSolutionAndWatchMode(); + verifyProgram(host, watch); + }); + + it("non local edit updates the program and watch correctly", () => { + const { host, watch, solutionBuilder } = createSolutionAndWatchMode(); + + // edit + host.writeFile(bTs.path, `${bTs.content} export function gfoo() { }`); - solutionBuilder.invalidateProject(bTsconfig.path); - solutionBuilder.buildInvalidatedProject(); + solutionBuilder.invalidateProject(bTsconfig.path); + solutionBuilder.buildInvalidatedProject(); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("edit on config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: refs.content + }; + const cTsConfigJson = JSON.parse(cTsconfig.content); + host.ensureFileOrFolder(nrefs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + + const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(nrefReplacer)); + verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer), expectedWatchedDirectories); + verifyDependencies(watch, aDts, [aDts]); + verifyDependencies(watch, bDts, [bDts, aDts]); + verifyDependencies(watch, nrefs.path, [nrefs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, nrefs.path, bDts]); + + // revert the update + host.writeFile(cTsconfig.path, cTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("edit in referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + const nrefs: File = { + path: getFilePathInProject(project, "nrefs/a.d.ts"), + content: host.readFile(aDts)! + }; + const bTsConfigJson = JSON.parse(bTsconfig.content); + host.ensureFileOrFolder(nrefs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + + const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario + verifyWatchesOfProject(host, + expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), + (multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()), + expectedWatchedDirectories); + verifyDependencies(watch, nrefs.path, [nrefs.path]); + verifyDependencies(watch, bDts, [bDts, nrefs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + + // revert the update + host.writeFile(bTsconfig.path, bTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("deleting referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + + // Resolutions should change now + // Should map to b.ts instead with options from our own config + host.deleteFile(bTsconfig.path); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, [ + `${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n` + ]); + + const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario + verifyWatchesOfProject(host, + expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()), + multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive, + expectedWatchedDirectories); + verifyDependencies(watch, bTs.path, [bTs.path, refs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bTs.path]); + + // revert the update + host.writeFile(bTsconfig.path, bTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + + it("deleting transitively referenced config file", () => { + const { host, watch } = createSolutionAndWatchMode(); + host.deleteFile(aTsconfig.path); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, [ + `${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${ multiFolder ? "a" : "tsconfig.a.json"}' not found.\n` + ]); + + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(s => s.replace(aDts, aTs.path))); + verifyWatchesOfProject(host, expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + verifyDependencies(watch, aTs.path, [aTs.path]); + verifyDependencies(watch, bDts, [bDts, aTs.path]); + verifyDependencies(watch, refs.path, [refs.path]); + verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + + // revert the update + host.writeFile(aTsconfig.path, aTsconfig.content); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + }); + } + + describe("when config files are side by side", () => { + verifyTransitiveReferences(/*multiFolder*/ false); }); - - it("edit on config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - - const nrefs: File = { - path: getFilePathInProject(project, "nrefs/a.d.ts"), - content: refs.content - }; - const cTsConfigJson = JSON.parse(cTsconfig.content); - host.ensureFileOrFolder(nrefs); - cTsConfigJson.compilerOptions.paths = { "@ref/*": ["./nrefs/*"] }; - host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - - const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(nrefReplacer)); - verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer)); - verifyDependencies(watch, aDts, [aDts]); - verifyDependencies(watch, bDts, [bDts, aDts]); - verifyDependencies(watch, nrefs.path, [nrefs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, nrefs.path, bDts]); - - // revert the update - host.writeFile(cTsconfig.path, cTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); - }); - - it("edit in referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - - const nrefs: File = { - path: getFilePathInProject(project, "nrefs/a.d.ts"), - content: host.readFile(aDts)! - }; - const bTsConfigJson = JSON.parse(bTsconfig.content); - host.ensureFileOrFolder(nrefs); - bTsConfigJson.compilerOptions.paths = { "@ref/*": ["./nrefs/*"] }; - host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - - const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), expectedWatchedDirectoriesRecursive.concat(getFilePathInProject(project, "nrefs").toLowerCase())); - verifyDependencies(watch, nrefs.path, [nrefs.path]); - verifyDependencies(watch, bDts, [bDts, nrefs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - - // revert the update - host.writeFile(bTsconfig.path, bTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); - }); - - it("deleting referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - - // Resolutions should change now - // Should map to b.ts instead with options from our own config - host.deleteFile(bTsconfig.path); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, [ - "tsconfig.c.json(9,21): error TS6053: File '/user/username/projects/transitiveReferences/tsconfig.b.json' not found.\n" - ]); - - const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()), expectedWatchedDirectoriesRecursive); - verifyDependencies(watch, bTs.path, [bTs.path, refs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bTs.path]); - - // revert the update - host.writeFile(bTsconfig.path, bTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); - }); - - it("deleting transitively referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - host.deleteFile(aTsconfig.path); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, [ - "tsconfig.b.json(10,21): error TS6053: File '/user/username/projects/transitiveReferences/tsconfig.a.json' not found.\n" - ]); - - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(s => s.replace(aDts, aTs.path))); - verifyWatchesOfProject(host, expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), expectedWatchedDirectoriesRecursive); - verifyDependencies(watch, aTs.path, [aTs.path]); - verifyDependencies(watch, bDts, [bDts, aTs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - - // revert the update - host.writeFile(aTsconfig.path, aTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + describe("when config files are in side by side folders", () => { + verifyTransitiveReferences(/*multiFolder*/ true); }); }); }); From dd343149a2d7fc2db3903a2d56b6d63430a66f3b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 4 Oct 2018 12:26:20 -0700 Subject: [PATCH 012/262] Add tests for project updates with tsserver --- src/testRunner/unittests/tsbuildWatchMode.ts | 476 ++++++++++++------ src/testRunner/unittests/tscWatchMode.ts | 4 +- .../unittests/tsserverProjectSystem.ts | 4 +- 3 files changed, 322 insertions(+), 162 deletions(-) diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 4a60fb581c5..971bb39fa66 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -406,7 +406,7 @@ let x: string = 10;`); }); }); - describe("tsc-watch works with project references", () => { + describe("tsc-watch and tsserver works with project references", () => { describe("invoking when references are already built", () => { function verifyWatchesOfProject(host: WatchedSystem, expectedWatchedFiles: ReadonlyArray, expectedWatchedDirectoriesRecursive: ReadonlyArray, expectedWatchedDirectories?: ReadonlyArray) { checkWatchedFilesDetailed(host, expectedWatchedFiles, 1); @@ -414,11 +414,9 @@ let x: string = 10;`); checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true); } - function createSolutionAndWatchModeOfProject( - allFiles: ReadonlyArray, + function createSolutionOfProject(allFiles: ReadonlyArray, currentDirectory: string, solutionBuilderconfig: string, - watchConfig: string, getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray) { // Build the composite project const host = createWatchedSystem(allFiles, { currentDirectory }); @@ -428,6 +426,17 @@ let x: string = 10;`); for (const stamp of outputFileStamps) { assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); } + return { host, solutionBuilder }; + } + + function createSolutionAndWatchModeOfProject( + allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + watchConfig: string, + getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray) { + // Build the composite project + const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); // Build in watch mode const watch = createWatchOfConfigFileReturningBuilder(watchConfig, host); @@ -436,7 +445,29 @@ let x: string = 10;`); return { host, solutionBuilder, watch }; } - function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray) { + function createSolutionAndServiceOfProject(allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + openFileName: string, + getOutputFileStamps: (host: WatchedSystem) => ReadonlyArray) { + // Build the composite project + const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); + + // service + const service = projectSystem.createProjectService(host); + service.openClientFile(openFileName); + + return { host, solutionBuilder, service }; + } + + function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: ReadonlyArray) { + projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 }); + projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles); + } + + type Watch = () => BuilderProgram; + + function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray) { checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected); } @@ -446,63 +477,93 @@ let x: string = 10;`); const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts"); const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())); const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests)); + const expectedProgramFiles = [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]; function createSolutionAndWatchMode() { return createSolutionAndWatchModeOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[0].path, getOutputFileStamps); } - function verifyWatches(host: WatchedSystem) { - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + function createSolutionAndService() { + return createSolutionAndServiceOfProject(allFiles, projectsLocation, `${project}/${SubProject.tests}`, tests[1].path, getOutputFileStamps); } - it("verifies dependencies and watches", () => { - const { host, watch } = createSolutionAndWatchMode(); + function verifyWatches(host: WatchedSystem, withTsserver?: boolean) { + verifyWatchesOfProject(host, withTsserver ? expectedWatchedFiles.filter(f => f !== tests[1].path.toLowerCase()) : expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + } - verifyWatches(host); - verifyDependencies(watch, coreIndexDts, [coreIndexDts]); - verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); - verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); - verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]); + function verifyScenario( + edit: (host: WatchedSystem, solutionBuilder: SolutionBuilder) => void, + expectedFilesAfterEdit: ReadonlyArray + ) { + it("with tsc-watch", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + checkProgramActualFiles(watch().getProgram(), expectedFilesAfterEdit); + + }); + + it("with tsserver", () => { + const { host, solutionBuilder, service } = createSolutionAndService(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service, tests[0].path, [tests[0].path, ...expectedFilesAfterEdit]); + }); + } + + describe("verifies dependencies and watches", () => { + it("with tsc-watch", () => { + const { host, watch } = createSolutionAndWatchMode(); + verifyWatches(host); + verifyDependencies(watch, coreIndexDts, [coreIndexDts]); + verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]); + verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]); + verifyDependencies(watch, tests[1].path, expectedProgramFiles.filter(f => f !== libFile.path)); + }); + + it("with tsserver", () => { + const { host } = createSolutionAndService(); + verifyWatches(host, /*withTsserver*/ true); + }); }); - it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[1].path, `${logic[1].content} + describe("local edit in ts file, result in watch compilation because logic.d.ts is written", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[1].path, `${logic[1].content} function foo() { }`); - solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); - solutionBuilder.buildInvalidatedProject(); + solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`); + solutionBuilder.buildInvalidatedProject(); - host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + // not ideal, but currently because of d.ts but no new file is written + // There will be timeout queued even though file contents are same + }, expectedProgramFiles); }); - it("non local edit in ts file, rebuilds in watch compilation", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[1].path, `${logic[1].content} + describe("non local edit in ts file, rebuilds in watch compilation", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[1].path, `${logic[1].content} export function gfoo() { }`); - solutionBuilder.invalidateProject(logic[0].path); - solutionBuilder.buildInvalidatedProject(); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]); + solutionBuilder.invalidateProject(logic[0].path); + solutionBuilder.buildInvalidatedProject(); + }, expectedProgramFiles); }); - it("change in project reference config file builds correctly", () => { - const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); - host.writeFile(logic[0].path, JSON.stringify({ - compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, - references: [{ path: "../core" }] - })); - solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); - solutionBuilder.buildInvalidatedProject(); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); + describe("change in project reference config file builds correctly", () => { + verifyScenario((host, solutionBuilder) => { + host.writeFile(logic[0].path, JSON.stringify({ + compilerOptions: { composite: true, declaration: true, declarationDir: "decls" }, + references: [{ path: "../core" }] + })); + solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full); + solutionBuilder.buildInvalidatedProject(); + }, [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]); }); }); @@ -583,6 +644,13 @@ export function gfoo() { ...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project)) ].map(s => s.toLowerCase()); + const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]] + ]; + function jsFile(extensionLessFile: string) { return getFilePathInProject(project, `${extensionLessFile}.js`); } @@ -595,155 +663,247 @@ export function gfoo() { return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); } + function createSolutionAndService() { + return createSolutionAndServiceOfProject(allFiles, getProjectPath(project), configToBuild, cTs.path, getOutputFileStamps); + } + function getOutputFileStamps(host: WatchedSystem) { return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); } - function verifyProgram(host: WatchedSystem, watch: () => BuilderProgram) { - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); - verifyDependencies(watch, aDts, [aDts]); - verifyDependencies(watch, bDts, [bDts, aDts]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); + function verifyProgram(host: WatchedSystem, watch: Watch) { + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies); } - it("verifies dependencies and watches", () => { + function verifyWatchState( + host: WatchedSystem, + watch: Watch, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>) { + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + for (const [file, deps] of dependencies) { + verifyDependencies(watch, file, deps); + } + } + + function verifyProject(host: WatchedSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray) { + verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos); + } + + function verifyServerState( + host: WatchedSystem, + service: projectSystem.TestProjectService, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + orphanInfos?: ReadonlyArray) { + checkProjectActualFiles(service, cTsconfig.path, expectedProgramFiles.concat(cTsconfig.path)); + const watchedFiles = expectedWatchedFiles.filter(f => f !== cTs.path.toLowerCase()); + if (orphanInfos) { + for (const orphan of orphanInfos) { + const info = service.getScriptInfoForPath(orphan as Path); + assert.isDefined(info); + assert.equal(info!.containingProjects.length, 0); + watchedFiles.push(orphan); + } + } + verifyWatchesOfProject(host, watchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + } + + function verifyScenario( + edit: (host: WatchedSystem, solutionBuilder: SolutionBuilder) => void, + expectedEditErrors: ReadonlyArray, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + revert?: (host: WatchedSystem) => void, + orphanInfosAfterEdit?: ReadonlyArray, + orphanInfosAfterRevert?: ReadonlyArray) { + it("with tsc-watch", () => { + const { host, solutionBuilder, watch } = createSolutionAndWatchMode(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, expectedEditErrors); + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies); + + if (revert) { + revert(host); + + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + verifyProgram(host, watch); + } + }); + + if (!multiFolder) return; // With side by side file open is in inferred project without any settings + + it("with tsserver", () => { + const { host, solutionBuilder, service } = createSolutionAndService(); + + edit(host, solutionBuilder); + + host.checkTimeoutQueueLengthAndRun(2); + verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfosAfterEdit); + + if (revert) { + revert(host); + + host.checkTimeoutQueueLengthAndRun(2); + verifyProject(host, service, orphanInfosAfterRevert); + } + }); + } + + describe("verifies dependencies and watches", () => { // Initial build - const { host, watch } = createSolutionAndWatchMode(); - verifyProgram(host, watch); + it("with tsc-watch", () => { + const { host, watch } = createSolutionAndWatchMode(); + verifyProgram(host, watch); + }); + if (!multiFolder) return; + it("with tsserver", () => { + const { host, service } = createSolutionAndService(); + verifyProject(host, service); + }); }); - it("non local edit updates the program and watch correctly", () => { - const { host, watch, solutionBuilder } = createSolutionAndWatchMode(); - - // edit - host.writeFile(bTs.path, `${bTs.content} + describe("non local edit updates the program and watch correctly", () => { + verifyScenario( + (host, solutionBuilder) => { + // edit + host.writeFile(bTs.path, `${bTs.content} export function gfoo() { }`); - solutionBuilder.invalidateProject(bTsconfig.path); - solutionBuilder.buildInvalidatedProject(); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + solutionBuilder.invalidateProject(bTsconfig.path); + solutionBuilder.buildInvalidatedProject(); + }, + emptyArray, + expectedProgramFiles, + expectedWatchedFiles, + expectedWatchedDirectoriesRecursive, + defaultDependencies); }); - it("edit on config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - + describe("edit on config file", () => { + const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); const nrefs: File = { path: getFilePathInProject(project, "nrefs/a.d.ts"), content: refs.content }; - const cTsConfigJson = JSON.parse(cTsconfig.content); - host.ensureFileOrFolder(nrefs); - cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; - host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - - const nrefReplacer = (f: string) => f.replace("refs", "nrefs"); - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(nrefReplacer)); - verifyWatchesOfProject(host, expectedWatchedFiles.map(nrefReplacer), expectedWatchedDirectoriesRecursive.map(nrefReplacer), expectedWatchedDirectories); - verifyDependencies(watch, aDts, [aDts]); - verifyDependencies(watch, bDts, [bDts, aDts]); - verifyDependencies(watch, nrefs.path, [nrefs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, nrefs.path, bDts]); - - // revert the update - host.writeFile(cTsconfig.path, cTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + verifyScenario( + host => { + const cTsConfigJson = JSON.parse(cTsconfig.content); + host.ensureFileOrFolder(nrefs); + cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)); + }, + emptyArray, + expectedProgramFiles.map(nrefReplacer), + expectedWatchedFiles.map(nrefReplacer), + expectedWatchedDirectoriesRecursive.map(nrefReplacer), + [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [nrefs.path, [nrefs.path]], + [cTs.path, [cTs.path, nrefs.path, bDts]] + ], + // revert the update + host => host.writeFile(cTsconfig.path, cTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [refs.path.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [nrefs.path.toLowerCase()] + ); }); - it("edit in referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - + describe("edit in referenced config file", () => { const nrefs: File = { path: getFilePathInProject(project, "nrefs/a.d.ts"), - content: host.readFile(aDts)! + content: "export declare class A {}" }; - const bTsConfigJson = JSON.parse(bTsconfig.content); - host.ensureFileOrFolder(nrefs); - bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; - host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path]; - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario - verifyWatchesOfProject(host, + verifyScenario( + host => { + const bTsConfigJson = JSON.parse(bTsconfig.content); + host.ensureFileOrFolder(nrefs); + bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath }; + host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)); + }, + emptyArray, + expectedProgramFiles, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()), (multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()), - expectedWatchedDirectories); - verifyDependencies(watch, nrefs.path, [nrefs.path]); - verifyDependencies(watch, bDts, [bDts, nrefs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - - // revert the update - host.writeFile(bTsconfig.path, bTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + [ + [nrefs.path, [nrefs.path]], + [bDts, [bDts, nrefs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]], + ], + // revert the update + host => host.writeFile(bTsconfig.path, bTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [aDts.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [nrefs.path.toLowerCase()] + ); }); - it("deleting referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - + describe("deleting referenced config file", () => { + const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; + const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario // Resolutions should change now // Should map to b.ts instead with options from our own config - host.deleteFile(bTsconfig.path); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, [ - `${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n` - ]); - - const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path]; - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario - verifyWatchesOfProject(host, + verifyScenario( + host => host.deleteFile(bTsconfig.path), + [ + `${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n` + ], + expectedProgramFiles, expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()), multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive, - expectedWatchedDirectories); - verifyDependencies(watch, bTs.path, [bTs.path, refs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bTs.path]); - - // revert the update - host.writeFile(bTsconfig.path, bTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + [ + [bTs.path, [bTs.path, refs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bTs.path]], + ], + // revert the update + host => host.writeFile(bTsconfig.path, bTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [bDts.toLowerCase(), aDts.toLowerCase(), aTsconfig.path.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [bTs.path.toLowerCase()] + ); }); - it("deleting transitively referenced config file", () => { - const { host, watch } = createSolutionAndWatchMode(); - host.deleteFile(aTsconfig.path); - - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, [ - `${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${ multiFolder ? "a" : "tsconfig.a.json"}' not found.\n` - ]); - - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles.map(s => s.replace(aDts, aTs.path))); - verifyWatchesOfProject(host, expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); - verifyDependencies(watch, aTs.path, [aTs.path]); - verifyDependencies(watch, bDts, [bDts, aTs.path]); - verifyDependencies(watch, refs.path, [refs.path]); - verifyDependencies(watch, cTs.path, [cTs.path, refs.path, bDts]); - - // revert the update - host.writeFile(aTsconfig.path, aTsconfig.content); - host.checkTimeoutQueueLengthAndRun(1); - checkOutputErrorsIncremental(host, emptyArray); - verifyProgram(host, watch); + describe("deleting transitively referenced config file", () => { + verifyScenario( + host => host.deleteFile(aTsconfig.path), + [ + `${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "a" : "tsconfig.a.json"}' not found.\n` + ], + expectedProgramFiles.map(s => s.replace(aDts, aTs.path)), + expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())), + expectedWatchedDirectoriesRecursive, + [ + [aTs.path, [aTs.path]], + [bDts, [bDts, aTs.path]], + [refs.path, [refs.path]], + [cTs.path, [cTs.path, refs.path, bDts]], + ], + // revert the update + host => host.writeFile(aTsconfig.path, aTsconfig.content), + // AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open + [aDts.toLowerCase()], + // AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open + [aTs.path.toLowerCase()] + ); }); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index c4b7d6adf44..a04a0431484 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -12,11 +12,11 @@ namespace ts.tscWatch { export import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain; export import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; - export function checkProgramActualFiles(program: Program, expectedFiles: string[]) { + export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray) { checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); } - export function checkProgramRootFiles(program: Program, expectedFiles: string[]) { + export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray) { checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index b4a87405ef9..80c63f10ad3 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -392,11 +392,11 @@ namespace ts.projectSystem { return values.next().value; } - export function checkProjectActualFiles(project: server.Project, expectedFiles: string[]) { + export function checkProjectActualFiles(project: server.Project, expectedFiles: ReadonlyArray) { checkArray(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles); } - function checkProjectRootFiles(project: server.Project, expectedFiles: string[]) { + function checkProjectRootFiles(project: server.Project, expectedFiles: ReadonlyArray) { checkArray(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles); } From 638cf5b7b880f770fae8c3942352153a51f64965 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 4 Oct 2018 15:55:17 -0700 Subject: [PATCH 013/262] Ignore the directory watchers invoked in non polling watch mode with no relative file name information Fixes #27326 --- src/compiler/sys.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 713085f1922..5aaa331f586 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -796,11 +796,10 @@ namespace ts { dirName, (_eventName: string, relativeFileName) => { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - const fileName = !isString(relativeFileName) - ? undefined! // TODO: GH#18217 - : getNormalizedAbsolutePath(relativeFileName, dirName); + if (!isString(relativeFileName)) { return; } + const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - const callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + const callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (const fileCallback of callbacks) { fileCallback(fileName, FileWatcherEventKind.Changed); From f30e73fc8028e482868c0ccbb7a9cf7b4a3983c6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 5 Oct 2018 15:37:41 -0700 Subject: [PATCH 014/262] Report the errors for static incompatibility only if instance types are assignable Fixes #26138 --- src/compiler/checker.ts | 7 ++-- ...taticMismatchBecauseOfPrototype.errors.txt | 19 ++++++++++ .../staticMismatchBecauseOfPrototype.js | 36 +++++++++++++++++++ .../staticMismatchBecauseOfPrototype.symbols | 26 ++++++++++++++ .../staticMismatchBecauseOfPrototype.types | 22 ++++++++++++ .../staticMismatchBecauseOfPrototype.ts | 11 ++++++ 6 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/staticMismatchBecauseOfPrototype.errors.txt create mode 100644 tests/baselines/reference/staticMismatchBecauseOfPrototype.js create mode 100644 tests/baselines/reference/staticMismatchBecauseOfPrototype.symbols create mode 100644 tests/baselines/reference/staticMismatchBecauseOfPrototype.types create mode 100644 tests/cases/compiler/staticMismatchBecauseOfPrototype.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ba0b180b71f..2126b12894f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -26069,8 +26069,11 @@ namespace ts { if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, - Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, + Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & TypeFlags.TypeVariable && !isMixinConstructorType(staticType)) { error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } diff --git a/tests/baselines/reference/staticMismatchBecauseOfPrototype.errors.txt b/tests/baselines/reference/staticMismatchBecauseOfPrototype.errors.txt new file mode 100644 index 00000000000..49760196800 --- /dev/null +++ b/tests/baselines/reference/staticMismatchBecauseOfPrototype.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/staticMismatchBecauseOfPrototype.ts(10,5): error TS2416: Property 'n' in type 'B' is not assignable to the same property in base type 'A'. + Type 'string' is not assignable to type 'number'. + + +==== tests/cases/compiler/staticMismatchBecauseOfPrototype.ts (1 errors) ==== + interface A { + n: number; + } + declare var A: { + prototype: A; + new(): A; + }; + + class B extends A { + n = ""; + ~ +!!! error TS2416: Property 'n' in type 'B' is not assignable to the same property in base type 'A'. +!!! error TS2416: Type 'string' is not assignable to type 'number'. + } \ No newline at end of file diff --git a/tests/baselines/reference/staticMismatchBecauseOfPrototype.js b/tests/baselines/reference/staticMismatchBecauseOfPrototype.js new file mode 100644 index 00000000000..4bc7b248957 --- /dev/null +++ b/tests/baselines/reference/staticMismatchBecauseOfPrototype.js @@ -0,0 +1,36 @@ +//// [staticMismatchBecauseOfPrototype.ts] +interface A { + n: number; +} +declare var A: { + prototype: A; + new(): A; +}; + +class B extends A { + n = ""; +} + +//// [staticMismatchBecauseOfPrototype.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var B = /** @class */ (function (_super) { + __extends(B, _super); + function B() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.n = ""; + return _this; + } + return B; +}(A)); diff --git a/tests/baselines/reference/staticMismatchBecauseOfPrototype.symbols b/tests/baselines/reference/staticMismatchBecauseOfPrototype.symbols new file mode 100644 index 00000000000..98abd4b9e1c --- /dev/null +++ b/tests/baselines/reference/staticMismatchBecauseOfPrototype.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/staticMismatchBecauseOfPrototype.ts === +interface A { +>A : Symbol(A, Decl(staticMismatchBecauseOfPrototype.ts, 0, 0), Decl(staticMismatchBecauseOfPrototype.ts, 3, 11)) + + n: number; +>n : Symbol(A.n, Decl(staticMismatchBecauseOfPrototype.ts, 0, 13)) +} +declare var A: { +>A : Symbol(A, Decl(staticMismatchBecauseOfPrototype.ts, 0, 0), Decl(staticMismatchBecauseOfPrototype.ts, 3, 11)) + + prototype: A; +>prototype : Symbol(prototype, Decl(staticMismatchBecauseOfPrototype.ts, 3, 16)) +>A : Symbol(A, Decl(staticMismatchBecauseOfPrototype.ts, 0, 0), Decl(staticMismatchBecauseOfPrototype.ts, 3, 11)) + + new(): A; +>A : Symbol(A, Decl(staticMismatchBecauseOfPrototype.ts, 0, 0), Decl(staticMismatchBecauseOfPrototype.ts, 3, 11)) + +}; + +class B extends A { +>B : Symbol(B, Decl(staticMismatchBecauseOfPrototype.ts, 6, 2)) +>A : Symbol(A, Decl(staticMismatchBecauseOfPrototype.ts, 0, 0), Decl(staticMismatchBecauseOfPrototype.ts, 3, 11)) + + n = ""; +>n : Symbol(B.n, Decl(staticMismatchBecauseOfPrototype.ts, 8, 19)) +} diff --git a/tests/baselines/reference/staticMismatchBecauseOfPrototype.types b/tests/baselines/reference/staticMismatchBecauseOfPrototype.types new file mode 100644 index 00000000000..d55c86b3fc7 --- /dev/null +++ b/tests/baselines/reference/staticMismatchBecauseOfPrototype.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/staticMismatchBecauseOfPrototype.ts === +interface A { + n: number; +>n : number +} +declare var A: { +>A : { new (): A; prototype: A; } + + prototype: A; +>prototype : A + + new(): A; +}; + +class B extends A { +>B : B +>A : A + + n = ""; +>n : string +>"" : "" +} diff --git a/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts b/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts new file mode 100644 index 00000000000..24d50f1951d --- /dev/null +++ b/tests/cases/compiler/staticMismatchBecauseOfPrototype.ts @@ -0,0 +1,11 @@ +interface A { + n: number; +} +declare var A: { + prototype: A; + new(): A; +}; + +class B extends A { + n = ""; +} \ No newline at end of file From 4d9a202ef15424d16b723820073b3066d3098351 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 5 Oct 2018 16:23:42 -0700 Subject: [PATCH 015/262] Properly widen initializer types in binding elements --- 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 21518ca34d5..e200730bc87 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4704,11 +4704,11 @@ namespace ts { } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & TypeFlags.Undefined)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & TypeFlags.Undefined)) { type = getTypeWithFacts(type, TypeFacts.NEUndefined); } return declaration.initializer && !getEffectiveTypeAnnotationNode(walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], UnionReduction.Subtype) : + getUnionType([type, checkDeclarationInitializer(declaration)], UnionReduction.Subtype) : type; } From c9ea6c3e03353a90815f0caf86ab45c7197aa1c8 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 08:04:09 -0700 Subject: [PATCH 016/262] Accept new baselines --- .../baselines/reference/declarationsAndAssignments.errors.txt | 4 ++-- tests/baselines/reference/declarationsAndAssignments.types | 4 ++-- .../destructuringArrayBindingPatternAndAssignment2.types | 2 +- .../reference/destructuringVariableDeclaration1ES5.types | 4 ++-- .../destructuringVariableDeclaration1ES5iterable.types | 4 ++-- .../reference/destructuringVariableDeclaration1ES6.types | 4 ++-- tests/baselines/reference/for-of43.types | 2 +- tests/baselines/reference/literalTypesAndTypeAssertions.types | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/baselines/reference/declarationsAndAssignments.errors.txt b/tests/baselines/reference/declarationsAndAssignments.errors.txt index 9f8cdc11851..46536d6fff0 100644 --- a/tests/baselines/reference/declarationsAndAssignments.errors.txt +++ b/tests/baselines/reference/declarationsAndAssignments.errors.txt @@ -5,7 +5,7 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(23,25): tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(24,19): error TS2353: Object literal may only specify known properties, and 'x' does not exist in type '{ y: any; }'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(28,28): error TS2353: Object literal may only specify known properties, and 'y' does not exist in type '{ x: any; }'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(29,22): error TS2353: Object literal may only specify known properties, and 'x' does not exist in type '{ y: any; }'. -tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(58,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string | 1', but here has type 'string'. +tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(58,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string | number', but here has type 'string'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(62,10): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(62,13): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(62,16): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. @@ -97,7 +97,7 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,9): var x: number; var y: string; ~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string | 1', but here has type 'string'. +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'y' must be of type 'string | number', but here has type 'string'. } function f8() { diff --git a/tests/baselines/reference/declarationsAndAssignments.types b/tests/baselines/reference/declarationsAndAssignments.types index e7db6f84fdb..edb00c9879b 100644 --- a/tests/baselines/reference/declarationsAndAssignments.types +++ b/tests/baselines/reference/declarationsAndAssignments.types @@ -238,7 +238,7 @@ function f7() { var [x = 0, y = 1] = [1, "hello"]; // Error, initializer for y must be string >x : number >0 : 0 ->y : string | 1 +>y : string | number >1 : 1 >[1, "hello"] : [number, string] >1 : 1 @@ -248,7 +248,7 @@ function f7() { >x : number var y: string; ->y : string | 1 +>y : string | number } function f8() { diff --git a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.types b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.types index 127e6f46f79..aa4f3a73b09 100644 --- a/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.types +++ b/tests/baselines/reference/destructuringArrayBindingPatternAndAssignment2.types @@ -39,7 +39,7 @@ function bar(): J { >3 : 3 } var [b3 = "string", b4, b5] = bar(); // Error ->b3 : Number | "string" +>b3 : string | Number >"string" : "string" >b4 : Number >b5 : Number diff --git a/tests/baselines/reference/destructuringVariableDeclaration1ES5.types b/tests/baselines/reference/destructuringVariableDeclaration1ES5.types index 58427ebd849..fc153be7c60 100644 --- a/tests/baselines/reference/destructuringVariableDeclaration1ES5.types +++ b/tests/baselines/reference/destructuringVariableDeclaration1ES5.types @@ -62,9 +62,9 @@ var [b2 = 3, b3 = true, b4 = temp] = [3, false, { t1: false, t2: "hello" }]; >"hello" : "hello" var [b5 = 3, b6 = true, b7 = temp] = [undefined, undefined, undefined]; ->b5 : 3 +>b5 : number >3 : 3 ->b6 : true +>b6 : boolean >true : true >b7 : { t1: boolean; t2: string; } >temp : { t1: boolean; t2: string; } diff --git a/tests/baselines/reference/destructuringVariableDeclaration1ES5iterable.types b/tests/baselines/reference/destructuringVariableDeclaration1ES5iterable.types index f8d01563d50..9c943356d80 100644 --- a/tests/baselines/reference/destructuringVariableDeclaration1ES5iterable.types +++ b/tests/baselines/reference/destructuringVariableDeclaration1ES5iterable.types @@ -62,9 +62,9 @@ var [b2 = 3, b3 = true, b4 = temp] = [3, false, { t1: false, t2: "hello" }]; >"hello" : "hello" var [b5 = 3, b6 = true, b7 = temp] = [undefined, undefined, undefined]; ->b5 : 3 +>b5 : number >3 : 3 ->b6 : true +>b6 : boolean >true : true >b7 : { t1: boolean; t2: string; } >temp : { t1: boolean; t2: string; } diff --git a/tests/baselines/reference/destructuringVariableDeclaration1ES6.types b/tests/baselines/reference/destructuringVariableDeclaration1ES6.types index 8b9566c3e1c..bf00e1955ca 100644 --- a/tests/baselines/reference/destructuringVariableDeclaration1ES6.types +++ b/tests/baselines/reference/destructuringVariableDeclaration1ES6.types @@ -62,9 +62,9 @@ var [b2 = 3, b3 = true, b4 = temp] = [3, false, { t1: false, t2: "hello" }]; >"hello" : "hello" var [b5 = 3, b6 = true, b7 = temp] = [undefined, undefined, undefined]; ->b5 : 3 +>b5 : number >3 : 3 ->b6 : true +>b6 : boolean >true : true >b7 : { t1: boolean; t2: string; } >temp : { t1: boolean; t2: string; } diff --git a/tests/baselines/reference/for-of43.types b/tests/baselines/reference/for-of43.types index 2327f1bafed..48466611d20 100644 --- a/tests/baselines/reference/for-of43.types +++ b/tests/baselines/reference/for-of43.types @@ -13,7 +13,7 @@ for (var {x: a = "", y: b = true} of array) { >a : string >"" : "" >y : any ->b : number | true +>b : number | boolean >true : true >array : { x: string; y: number; }[] diff --git a/tests/baselines/reference/literalTypesAndTypeAssertions.types b/tests/baselines/reference/literalTypesAndTypeAssertions.types index 1730c0ac420..be204673ad3 100644 --- a/tests/baselines/reference/literalTypesAndTypeAssertions.types +++ b/tests/baselines/reference/literalTypesAndTypeAssertions.types @@ -44,7 +44,7 @@ let { b = "foo" as "foo" } = { b: "bar" }; >"bar" : "bar" let { c = "foo" } = { c: "bar" as "bar" }; ->c : "foo" | "bar" +>c : string >"foo" : "foo" >{ c: "bar" as "bar" } : { c?: "bar"; } >c : "bar" From 7f3f98ea833445a1618092d8365bf4ade7f7e97f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 13:49:42 -0700 Subject: [PATCH 017/262] Properly handle unions of tuple types --- src/compiler/checker.ts | 61 ++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 28 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e200730bc87..6ee5ad85ced 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4681,14 +4681,14 @@ namespace ts { // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - sliceTupleType(parentType, index) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, t => sliceTupleType(t, index)) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array const index = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? + type = everyType(parentType, isTupleLikeType) ? getTupleElementType(parentType, index) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { @@ -7307,10 +7307,10 @@ namespace ts { } } else if (isUnion) { - const index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number)) || getIndexInfoOfType(type, IndexKind.String)); - if (index) { - checkFlags |= index.isReadonly ? CheckFlags.Readonly : 0; - indexTypes = append(indexTypes, index.type); + const indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, IndexKind.Number) || getIndexInfoOfType(type, IndexKind.String)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? CheckFlags.Readonly : 0; + indexTypes = append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= CheckFlags.Partial; @@ -9307,11 +9307,8 @@ namespace ts { const propType = getTypeOfSymbol(prop); return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; } - if (isTupleType(objectType)) { - const restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; - } + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); } } if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) { @@ -12867,9 +12864,17 @@ namespace ts { } function getTupleElementType(type: Type, index: number) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments![index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index as __String); + const propType = getTypeOfPropertyOfType(type, "" + index as __String); + if (propType) { + return propType; + } + if (everyType(type, isTupleType)) { + let restType = mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); + if (restType !== undefinedType) { + return restType; + } + } + return undefined; } function isNeitherUnitTypeNorNever(type: Type): boolean { @@ -14361,7 +14366,7 @@ namespace ts { } function getTypeOfDestructuredArrayElement(type: Type, index: number) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -14559,6 +14564,10 @@ namespace ts { return type.flags & TypeFlags.Union ? forEach((type).types, f) : f(type); } + function everyType(type: Type, f: (t: Type) => boolean): boolean { + return type.flags & TypeFlags.Union ? every((type).types, f) : f(type); + } + function filterType(type: Type, f: (t: Type) => boolean): Type { if (type.flags & TypeFlags.Union) { const types = (type).types; @@ -16657,11 +16666,6 @@ namespace ts { return mapType(type, t => getIndexTypeOfStructuredType(t, kind), /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type: Type): boolean { - return !!(type.flags & TypeFlags.Union ? forEach((type).types, isTupleLikeType) : isTupleLikeType(type)); - } - // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -17191,7 +17195,8 @@ namespace ts { type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { const pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. @@ -18925,9 +18930,9 @@ namespace ts { } if (isTupleType(objectType) && !objectType.target.hasRestElement && isNumericLiteral(indexExpression)) { const index = +indexExpression.text; - const maximumIndex = length(objectType.target.typeParameters); - if (index >= maximumIndex) { - error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + const length = getTypeReferenceArity(objectType); + if (index >= length) { + error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, length); } } @@ -21668,7 +21673,7 @@ namespace ts { if (element.kind !== SyntaxKind.SpreadElement) { const propName = "" + elementIndex as __String; const type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -21694,8 +21699,8 @@ namespace ts { } else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - const type = isTupleType(sourceType) ? - sliceTupleType(sourceType, elementIndex) : + const type = everyType(sourceType, isTupleType) ? + mapType(sourceType, t => sliceTupleType(t, elementIndex)) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } From 1299c9395e08c87a1ba214d6fff277f6a7f5ee82 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 13:50:24 -0700 Subject: [PATCH 018/262] Remove unused (and incorrect) code in sys.ts --- src/compiler/sys.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 713085f1922..796b601e457 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -36,23 +36,6 @@ namespace ts { Low = 250 } - function getPriorityValues(highPriorityValue: number): [number, number, number] { - const mediumPriorityValue = highPriorityValue * 2; - const lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - - function pollingInterval(watchPriority: PollingInterval): number { - return pollingIntervalsForPriority[watchPriority]; - } - - const pollingIntervalsForPriority = getPriorityValues(250); - - /* @internal */ - export function watchFileUsingPriorityPollingInterval(host: System, fileName: string, callback: FileWatcherCallback, watchPriority: PollingInterval): FileWatcher { - return host.watchFile!(fileName, callback, pollingInterval(watchPriority)); - } - /* @internal */ export type HostWatchFile = (fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval | undefined) => FileWatcher; /* @internal */ From 919fce95fc49837a620a108d54965258b4f3fbff Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 13:50:43 -0700 Subject: [PATCH 019/262] Accept new baselines --- .../reference/bestCommonTypeOfTuple.types | 16 +++++++-------- .../reference/bestCommonTypeOfTuple2.types | 20 +++++++++---------- tests/baselines/reference/castingTuple.types | 4 ++-- .../reference/emptyTuplesTypeAssertion01.js | 2 +- .../emptyTuplesTypeAssertion01.types | 4 ++-- .../reference/emptyTuplesTypeAssertion02.js | 2 +- .../emptyTuplesTypeAssertion02.types | 4 ++-- .../genericCallWithTupleType.errors.txt | 6 ++---- .../reference/genericCallWithTupleType.types | 10 +++++----- .../reference/indexerWithTuple.types | 16 +++++++-------- .../reference/keyofAndIndexedAccess.types | 4 ++-- .../reference/tupleLengthCheck.types | 8 ++++---- .../baselines/reference/tupleTypes.errors.txt | 8 +++++++- tests/baselines/reference/tupleTypes.types | 12 +++++------ 14 files changed, 60 insertions(+), 56 deletions(-) diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 612403084a5..4cc64a25505 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -76,26 +76,26 @@ t4 = [E1.one, E2.two, 20]; >20 : 20 var e1 = t1[2]; // {} ->e1 : ((x: number) => string) | ((x: number) => number) ->t1[2] : ((x: number) => string) | ((x: number) => number) +>e1 : undefined +>t1[2] : undefined >t1 : [(x: number) => string, (x: number) => number] >2 : 2 var e2 = t2[2]; // {} ->e2 : E1 | E2 ->t2[2] : E1 | E2 +>e2 : undefined +>t2[2] : undefined >t2 : [E1, E2] >2 : 2 var e3 = t3[2]; // any ->e3 : any ->t3[2] : any +>e3 : undefined +>t3[2] : undefined >t3 : [number, any] >2 : 2 var e4 = t4[3]; // number ->e4 : number ->t4[3] : number +>e4 : undefined +>t4[3] : undefined >t4 : [E1, E2, number] >3 : 3 diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.types b/tests/baselines/reference/bestCommonTypeOfTuple2.types index 33691bc65a9..6b3e6a3789c 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.types @@ -49,32 +49,32 @@ var t5: [C1, F] >t5 : [C1, F] var e11 = t1[4]; // base ->e11 : base | C ->t1[4] : base | C +>e11 : undefined +>t1[4] : undefined >t1 : [C, base] >4 : 4 var e21 = t2[4]; // {} ->e21 : C | D ->t2[4] : C | D +>e21 : undefined +>t2[4] : undefined >t2 : [C, D] >4 : 4 var e31 = t3[4]; // C1 ->e31 : C1 | D1 ->t3[4] : C1 | D1 +>e31 : undefined +>t3[4] : undefined >t3 : [C1, D1] >4 : 4 var e41 = t4[2]; // base1 ->e41 : base1 | C1 ->t4[2] : base1 | C1 +>e41 : undefined +>t4[2] : undefined >t4 : [base1, C1] >2 : 2 var e51 = t5[2]; // {} ->e51 : F | C1 ->t5[2] : F | C1 +>e51 : undefined +>t5[2] : undefined >t5 : [C1, F] >2 : 2 diff --git a/tests/baselines/reference/castingTuple.types b/tests/baselines/reference/castingTuple.types index 729c090e1ca..0c20dadc2be 100644 --- a/tests/baselines/reference/castingTuple.types +++ b/tests/baselines/reference/castingTuple.types @@ -83,8 +83,8 @@ var eleFromCDA1 = classCDATuple[2]; // A >2 : 2 var eleFromCDA2 = classCDATuple[5]; // C | D | A ->eleFromCDA2 : A | C | D ->classCDATuple[5] : A | C | D +>eleFromCDA2 : undefined +>classCDATuple[5] : undefined >classCDATuple : [C, D, A] >5 : 5 diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion01.js b/tests/baselines/reference/emptyTuplesTypeAssertion01.js index 8ee48da9a56..d213d3b1dca 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion01.js +++ b/tests/baselines/reference/emptyTuplesTypeAssertion01.js @@ -9,4 +9,4 @@ var y = x[0]; //// [emptyTuplesTypeAssertion01.d.ts] declare let x: []; -declare let y: never; +declare let y: undefined; diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion01.types b/tests/baselines/reference/emptyTuplesTypeAssertion01.types index 0a278c01d31..be26dc06955 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion01.types +++ b/tests/baselines/reference/emptyTuplesTypeAssertion01.types @@ -5,8 +5,8 @@ let x = <[]>[]; >[] : [] let y = x[0]; ->y : never ->x[0] : never +>y : undefined +>x[0] : undefined >x : [] >0 : 0 diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion02.js b/tests/baselines/reference/emptyTuplesTypeAssertion02.js index 41607e53b40..2dbfd9ea7b8 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion02.js +++ b/tests/baselines/reference/emptyTuplesTypeAssertion02.js @@ -9,4 +9,4 @@ var y = x[0]; //// [emptyTuplesTypeAssertion02.d.ts] declare let x: []; -declare let y: never; +declare let y: undefined; diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion02.types b/tests/baselines/reference/emptyTuplesTypeAssertion02.types index ef35e90eac2..3bba21cc859 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion02.types +++ b/tests/baselines/reference/emptyTuplesTypeAssertion02.types @@ -5,8 +5,8 @@ let x = [] as []; >[] : [] let y = x[0]; ->y : never ->x[0] : never +>y : undefined +>x[0] : undefined >x : [] >0 : 0 diff --git a/tests/baselines/reference/genericCallWithTupleType.errors.txt b/tests/baselines/reference/genericCallWithTupleType.errors.txt index 6e6732ebb09..6f902ebe757 100644 --- a/tests/baselines/reference/genericCallWithTupleType.errors.txt +++ b/tests/baselines/reference/genericCallWithTupleType.errors.txt @@ -2,8 +2,7 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup Types of property 'length' are incompatible. Type '4' is not assignable to type '2'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(13,20): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,1): error TS2322: Type '{ a: string; }' is not assignable to type 'string | number'. - Type '{ a: string; }' is not assignable to type 'number'. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,1): error TS2322: Type '{ a: string; }' is not assignable to type 'undefined'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,11): error TS2733: Index '3' is out-of-bounds in tuple of length 2. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(15,20): error TS2733: Index '3' is out-of-bounds in tuple of length 2. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,14): error TS2322: Type 'number' is not assignable to type 'string'. @@ -36,8 +35,7 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup !!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. i1.tuple1[3] = { a: "string" }; ~~~~~~~~~~~~ -!!! error TS2322: Type '{ a: string; }' is not assignable to type 'string | number'. -!!! error TS2322: Type '{ a: string; }' is not assignable to type 'number'. +!!! error TS2322: Type '{ a: string; }' is not assignable to type 'undefined'. ~ !!! error TS2733: Index '3' is out-of-bounds in tuple of length 2. var e4 = i1.tuple1[3]; // {} diff --git a/tests/baselines/reference/genericCallWithTupleType.types b/tests/baselines/reference/genericCallWithTupleType.types index 359ead39870..07be141f789 100644 --- a/tests/baselines/reference/genericCallWithTupleType.types +++ b/tests/baselines/reference/genericCallWithTupleType.types @@ -48,8 +48,8 @@ i1.tuple1 = ["foo", 5, false, true]; >true : true var e3 = i1.tuple1[2]; // {} ->e3 : string | number ->i1.tuple1[2] : string | number +>e3 : undefined +>i1.tuple1[2] : undefined >i1.tuple1 : [string, number] >i1 : I >tuple1 : [string, number] @@ -57,7 +57,7 @@ var e3 = i1.tuple1[2]; // {} i1.tuple1[3] = { a: "string" }; >i1.tuple1[3] = { a: "string" } : { a: string; } ->i1.tuple1[3] : string | number +>i1.tuple1[3] : undefined >i1.tuple1 : [string, number] >i1 : I >tuple1 : [string, number] @@ -67,8 +67,8 @@ i1.tuple1[3] = { a: "string" }; >"string" : "string" var e4 = i1.tuple1[3]; // {} ->e4 : string | number ->i1.tuple1[3] : string | number +>e4 : undefined +>i1.tuple1[3] : undefined >i1.tuple1 : [string, number] >i1 : I >tuple1 : [string, number] diff --git a/tests/baselines/reference/indexerWithTuple.types b/tests/baselines/reference/indexerWithTuple.types index 8a14fa9816e..01ede87ca9f 100644 --- a/tests/baselines/reference/indexerWithTuple.types +++ b/tests/baselines/reference/indexerWithTuple.types @@ -47,8 +47,8 @@ var ele11 = strNumTuple[1]; // number >1 : 1 var ele12 = strNumTuple[2]; // string | number ->ele12 : string | number ->strNumTuple[2] : string | number +>ele12 : undefined +>strNumTuple[2] : undefined >strNumTuple : [string, number] >2 : 2 @@ -83,8 +83,8 @@ var strNumTuple1 = numTupleTuple[1]; //[string, number]; >1 : 1 var ele17 = numTupleTuple[2]; // number | [string, number] ->ele17 : number | [string, number] ->numTupleTuple[2] : number | [string, number] +>ele17 : undefined +>numTupleTuple[2] : undefined >numTupleTuple : [number, [string, number]] >2 : 2 @@ -101,8 +101,8 @@ var eleUnion11 = unionTuple1[1]; // string | number >1 : 1 var eleUnion12 = unionTuple1[2]; // string | number ->eleUnion12 : string | number ->unionTuple1[2] : string | number +>eleUnion12 : undefined +>unionTuple1[2] : undefined >unionTuple1 : [number, string | number] >2 : 2 @@ -143,8 +143,8 @@ var eleUnion21 = unionTuple2[1]; // string | number >1 : 1 var eleUnion22 = unionTuple2[2]; // string | number | boolean ->eleUnion22 : string | number | boolean ->unionTuple2[2] : string | number | boolean +>eleUnion22 : undefined +>unionTuple2[2] : undefined >unionTuple2 : [boolean, string | number] >2 : 2 diff --git a/tests/baselines/reference/keyofAndIndexedAccess.types b/tests/baselines/reference/keyofAndIndexedAccess.types index 025ecc7a41e..feeec10b521 100644 --- a/tests/baselines/reference/keyofAndIndexedAccess.types +++ b/tests/baselines/reference/keyofAndIndexedAccess.types @@ -146,7 +146,7 @@ type Q31 = [string, number][1]; // number >Q31 : number type Q32 = [string, number][2]; // string | number ->Q32 : string | number +>Q32 : undefined type Q33 = [string, number][E.A]; // string >Q33 : string @@ -157,7 +157,7 @@ type Q34 = [string, number][E.B]; // number >E : any type Q35 = [string, number][E.C]; // string | number ->Q35 : string | number +>Q35 : undefined >E : any type Q36 = [string, number]["0"]; // string diff --git a/tests/baselines/reference/tupleLengthCheck.types b/tests/baselines/reference/tupleLengthCheck.types index be4372c669c..67ccb006a81 100644 --- a/tests/baselines/reference/tupleLengthCheck.types +++ b/tests/baselines/reference/tupleLengthCheck.types @@ -12,14 +12,14 @@ const a1 = a[1] >1 : 1 const a2 = a[2] ->a2 : string | number ->a[2] : string | number +>a2 : undefined +>a[2] : undefined >a : [number, string] >2 : 2 const a3 = a[1000] ->a3 : string | number ->a[1000] : string | number +>a3 : undefined +>a[1000] : undefined >a : [number, string] >1000 : 1000 diff --git a/tests/baselines/reference/tupleTypes.errors.txt b/tests/baselines/reference/tupleTypes.errors.txt index 4543eb202da..b0b4d06d518 100644 --- a/tests/baselines/reference/tupleTypes.errors.txt +++ b/tests/baselines/reference/tupleTypes.errors.txt @@ -1,4 +1,5 @@ tests/cases/compiler/tupleTypes.ts(11,12): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(12,5): error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(14,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. Property '0' is missing in type '[]'. tests/cases/compiler/tupleTypes.ts(15,1): error TS2322: Type '[number]' is not assignable to type '[number, string]'. @@ -9,6 +10,7 @@ tests/cases/compiler/tupleTypes.ts(18,1): error TS2322: Type '[number, string, n Types of property 'length' are incompatible. Type '3' is not assignable to type '2'. tests/cases/compiler/tupleTypes.ts(35,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(36,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(41,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. tests/cases/compiler/tupleTypes.ts(47,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. Type 'string | number' is not assignable to type 'number'. @@ -22,7 +24,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n Type '{}' is not assignable to type 'string'. -==== tests/cases/compiler/tupleTypes.ts (12 errors) ==== +==== tests/cases/compiler/tupleTypes.ts (14 errors) ==== var v1: []; // Error var v2: [number]; var v3: [number, string]; @@ -37,6 +39,8 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n ~ !!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. var t2: number|string; + ~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. t = []; // Error ~ @@ -77,6 +81,8 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n ~ !!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. var tt2: number | string; + ~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. tt = tuple2(1, undefined); tt = [1, undefined]; diff --git a/tests/baselines/reference/tupleTypes.types b/tests/baselines/reference/tupleTypes.types index 45fec41112c..12eaf588b98 100644 --- a/tests/baselines/reference/tupleTypes.types +++ b/tests/baselines/reference/tupleTypes.types @@ -33,13 +33,13 @@ var t1: string; >t1 : string var t2 = t[2]; // number|string ->t2 : string | number ->t[2] : string | number +>t2 : undefined +>t[2] : undefined >t : [number, string] >2 : 2 var t2: number|string; ->t2 : string | number +>t2 : undefined t = []; // Error >t = [] : [] @@ -144,13 +144,13 @@ var tt1: string; >tt1 : string var tt2 = tt[2]; ->tt2 : string | number ->tt[2] : string | number +>tt2 : undefined +>tt[2] : undefined >tt : [number, string] >2 : 2 var tt2: number | string; ->tt2 : string | number +>tt2 : undefined tt = tuple2(1, undefined); >tt = tuple2(1, undefined) : [number, any] From d4f480cbbbdadbc931b2731729552c48970adec1 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 17:03:19 -0700 Subject: [PATCH 020/262] Add tests --- .../types/tuple/unionsOfTupleTypes1.ts | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts diff --git a/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts b/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts new file mode 100644 index 00000000000..9eae78919a4 --- /dev/null +++ b/tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts @@ -0,0 +1,64 @@ +// @strict: true + +type T1 = [string, number]; +type T2 = [boolean] | [string, number]; +type T3 = [string, ...number[]]; +type T4 = [boolean] | [string, ...number[]]; + +type T10 = T1[0]; // string +type T11 = T1[1]; // number +type T12 = T1[2]; // undefined +type T1N = T1[number]; // string | number + +type T20 = T2[0]; // string | boolean +type T21 = T2[1]; // number | undefined +type T22 = T2[2]; // undefined +type T2N = T2[number]; // string | number | boolean + +type T30 = T3[0]; // string +type T31 = T3[1]; // number +type T32 = T3[2]; // number +type T3N = T3[number]; // string | number + +type T40 = T4[0]; // string | boolean +type T41 = T4[1]; // number | undefined +type T42 = T4[2]; // number | undefined +type T4N = T4[number]; // string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + let [d20, d21, d22] = t2; // string | boolean, number | undefined + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + [d20, d21, d22] = t2; + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +const ex: Unioned = ["hi"] as Unioned; + +const [x, y] = ex; From 86704e5bf9af79f8b720a1e80bbd6f526ca4be08 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 17:03:27 -0700 Subject: [PATCH 021/262] Accept new baselines --- .../reference/unionsOfTupleTypes1.errors.txt | 81 ++++++ .../reference/unionsOfTupleTypes1.js | 99 +++++++ .../reference/unionsOfTupleTypes1.symbols | 241 ++++++++++++++++ .../reference/unionsOfTupleTypes1.types | 266 ++++++++++++++++++ 4 files changed, 687 insertions(+) create mode 100644 tests/baselines/reference/unionsOfTupleTypes1.errors.txt create mode 100644 tests/baselines/reference/unionsOfTupleTypes1.js create mode 100644 tests/baselines/reference/unionsOfTupleTypes1.symbols create mode 100644 tests/baselines/reference/unionsOfTupleTypes1.types diff --git a/tests/baselines/reference/unionsOfTupleTypes1.errors.txt b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt new file mode 100644 index 00000000000..0f8f8ea786a --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt @@ -0,0 +1,81 @@ +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(27,20): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(28,20): error TS2460: Type 'T2' has no property '2'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(31,16): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(32,16): error TS2460: Type 'T2' has no property '2'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2733: Index '2' is out-of-bounds in tuple of length 2. + + +==== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts (5 errors) ==== + type T1 = [string, number]; + type T2 = [boolean] | [string, number]; + type T3 = [string, ...number[]]; + type T4 = [boolean] | [string, ...number[]]; + + type T10 = T1[0]; // string + type T11 = T1[1]; // number + type T12 = T1[2]; // undefined + type T1N = T1[number]; // string | number + + type T20 = T2[0]; // string | boolean + type T21 = T2[1]; // number | undefined + type T22 = T2[2]; // undefined + type T2N = T2[number]; // string | number | boolean + + type T30 = T3[0]; // string + type T31 = T3[1]; // number + type T32 = T3[2]; // number + type T3N = T3[number]; // string | number + + type T40 = T4[0]; // string | boolean + type T41 = T4[1]; // number | undefined + type T42 = T4[2]; // number | undefined + type T4N = T4[number]; // string | number | boolean + + function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + ~~~ +!!! error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. + let [d20, d21, d22] = t2; // string | boolean, number | undefined + ~~~ +!!! error TS2460: Type 'T2' has no property '2'. + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + ~~~ +!!! error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. + [d20, d21, d22] = t2; + ~~~ +!!! error TS2460: Type 'T2' has no property '2'. + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; + } + + // Repro from #27543 + + type Unioned = [string] | [string, number]; + const ex: Unioned = ["hi"] as Unioned; + + const [x, y] = ex; + \ No newline at end of file diff --git a/tests/baselines/reference/unionsOfTupleTypes1.js b/tests/baselines/reference/unionsOfTupleTypes1.js new file mode 100644 index 00000000000..de21e1153d0 --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.js @@ -0,0 +1,99 @@ +//// [unionsOfTupleTypes1.ts] +type T1 = [string, number]; +type T2 = [boolean] | [string, number]; +type T3 = [string, ...number[]]; +type T4 = [boolean] | [string, ...number[]]; + +type T10 = T1[0]; // string +type T11 = T1[1]; // number +type T12 = T1[2]; // undefined +type T1N = T1[number]; // string | number + +type T20 = T2[0]; // string | boolean +type T21 = T2[1]; // number | undefined +type T22 = T2[2]; // undefined +type T2N = T2[number]; // string | number | boolean + +type T30 = T3[0]; // string +type T31 = T3[1]; // number +type T32 = T3[2]; // number +type T3N = T3[number]; // string | number + +type T40 = T4[0]; // string | boolean +type T41 = T4[1]; // number | undefined +type T42 = T4[2]; // number | undefined +type T4N = T4[number]; // string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { + let [d10, d11, d12] = t1; // string, number + let [d20, d21, d22] = t2; // string | boolean, number | undefined + let [d30, d31, d32] = t3; // string, number, number + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined + [d10, d11, d12] = t1; + [d20, d21, d22] = t2; + [d30, d31, d32] = t3; + [d40, d41, d42] = t4; + let t10 = t1[0]; // string + let t11 = t1[1]; // number + let t12 = t1[2]; // undefined + let t1x = t1[x]; // string | number + let t20 = t2[0]; // string | boolean + let t21 = t2[1]; // number | undefined + let t22 = t2[2]; // undefined + let t2x = t2[x]; // string | number | boolean + let t30 = t3[0]; // string + let t31 = t3[1]; // number + let t32 = t3[2]; // number + let t3x = t3[x]; // string | number + let t40 = t4[0]; // string | boolean + let t41 = t4[1]; // number | undefined + let t42 = t4[2]; // number | undefined + let t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +const ex: Unioned = ["hi"] as Unioned; + +const [x, y] = ex; + + +//// [unionsOfTupleTypes1.js] +"use strict"; +function f1(t1, t2, t3, t4, x) { + var d10 = t1[0], d11 = t1[1], d12 = t1[2]; // string, number + var d20 = t2[0], d21 = t2[1], d22 = t2[2]; // string | boolean, number | undefined + var d30 = t3[0], d31 = t3[1], d32 = t3[2]; // string, number, number + var d40 = t4[0], d41 = t4[1], d42 = t4[2]; // string | boolean, number | undefined, number | undefined + d10 = t1[0], d11 = t1[1], d12 = t1[2]; + d20 = t2[0], d21 = t2[1], d22 = t2[2]; + d30 = t3[0], d31 = t3[1], d32 = t3[2]; + d40 = t4[0], d41 = t4[1], d42 = t4[2]; + var t10 = t1[0]; // string + var t11 = t1[1]; // number + var t12 = t1[2]; // undefined + var t1x = t1[x]; // string | number + var t20 = t2[0]; // string | boolean + var t21 = t2[1]; // number | undefined + var t22 = t2[2]; // undefined + var t2x = t2[x]; // string | number | boolean + var t30 = t3[0]; // string + var t31 = t3[1]; // number + var t32 = t3[2]; // number + var t3x = t3[x]; // string | number + var t40 = t4[0]; // string | boolean + var t41 = t4[1]; // number | undefined + var t42 = t4[2]; // number | undefined + var t4x = t4[x]; // string | number | boolean + t1[1] = 42; + t2[1] = 42; + t3[1] = 42; + t4[1] = 42; +} +var ex = ["hi"]; +var x = ex[0], y = ex[1]; diff --git a/tests/baselines/reference/unionsOfTupleTypes1.symbols b/tests/baselines/reference/unionsOfTupleTypes1.symbols new file mode 100644 index 00000000000..8d9b9185e54 --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.symbols @@ -0,0 +1,241 @@ +=== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts === +type T1 = [string, number]; +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T2 = [boolean] | [string, number]; +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T3 = [string, ...number[]]; +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T4 = [boolean] | [string, ...number[]]; +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T10 = T1[0]; // string +>T10 : Symbol(T10, Decl(unionsOfTupleTypes1.ts, 3, 44)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T11 = T1[1]; // number +>T11 : Symbol(T11, Decl(unionsOfTupleTypes1.ts, 5, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T12 = T1[2]; // undefined +>T12 : Symbol(T12, Decl(unionsOfTupleTypes1.ts, 6, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T1N = T1[number]; // string | number +>T1N : Symbol(T1N, Decl(unionsOfTupleTypes1.ts, 7, 17)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) + +type T20 = T2[0]; // string | boolean +>T20 : Symbol(T20, Decl(unionsOfTupleTypes1.ts, 8, 22)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T21 = T2[1]; // number | undefined +>T21 : Symbol(T21, Decl(unionsOfTupleTypes1.ts, 10, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T22 = T2[2]; // undefined +>T22 : Symbol(T22, Decl(unionsOfTupleTypes1.ts, 11, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T2N = T2[number]; // string | number | boolean +>T2N : Symbol(T2N, Decl(unionsOfTupleTypes1.ts, 12, 17)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) + +type T30 = T3[0]; // string +>T30 : Symbol(T30, Decl(unionsOfTupleTypes1.ts, 13, 22)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T31 = T3[1]; // number +>T31 : Symbol(T31, Decl(unionsOfTupleTypes1.ts, 15, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T32 = T3[2]; // number +>T32 : Symbol(T32, Decl(unionsOfTupleTypes1.ts, 16, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T3N = T3[number]; // string | number +>T3N : Symbol(T3N, Decl(unionsOfTupleTypes1.ts, 17, 17)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) + +type T40 = T4[0]; // string | boolean +>T40 : Symbol(T40, Decl(unionsOfTupleTypes1.ts, 18, 22)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T41 = T4[1]; // number | undefined +>T41 : Symbol(T41, Decl(unionsOfTupleTypes1.ts, 20, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T42 = T4[2]; // number | undefined +>T42 : Symbol(T42, Decl(unionsOfTupleTypes1.ts, 21, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +type T4N = T4[number]; // string | number | boolean +>T4N : Symbol(T4N, Decl(unionsOfTupleTypes1.ts, 22, 17)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { +>f1 : Symbol(f1, Decl(unionsOfTupleTypes1.ts, 23, 22)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>T1 : Symbol(T1, Decl(unionsOfTupleTypes1.ts, 0, 0)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>T2 : Symbol(T2, Decl(unionsOfTupleTypes1.ts, 0, 27)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>T3 : Symbol(T3, Decl(unionsOfTupleTypes1.ts, 1, 39)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>T4 : Symbol(T4, Decl(unionsOfTupleTypes1.ts, 2, 32)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let [d10, d11, d12] = t1; // string, number +>d10 : Symbol(d10, Decl(unionsOfTupleTypes1.ts, 26, 9)) +>d11 : Symbol(d11, Decl(unionsOfTupleTypes1.ts, 26, 13)) +>d12 : Symbol(d12, Decl(unionsOfTupleTypes1.ts, 26, 18)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + let [d20, d21, d22] = t2; // string | boolean, number | undefined +>d20 : Symbol(d20, Decl(unionsOfTupleTypes1.ts, 27, 9)) +>d21 : Symbol(d21, Decl(unionsOfTupleTypes1.ts, 27, 13)) +>d22 : Symbol(d22, Decl(unionsOfTupleTypes1.ts, 27, 18)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + let [d30, d31, d32] = t3; // string, number, number +>d30 : Symbol(d30, Decl(unionsOfTupleTypes1.ts, 28, 9)) +>d31 : Symbol(d31, Decl(unionsOfTupleTypes1.ts, 28, 13)) +>d32 : Symbol(d32, Decl(unionsOfTupleTypes1.ts, 28, 18)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined +>d40 : Symbol(d40, Decl(unionsOfTupleTypes1.ts, 29, 9)) +>d41 : Symbol(d41, Decl(unionsOfTupleTypes1.ts, 29, 13)) +>d42 : Symbol(d42, Decl(unionsOfTupleTypes1.ts, 29, 18)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + [d10, d11, d12] = t1; +>d10 : Symbol(d10, Decl(unionsOfTupleTypes1.ts, 26, 9)) +>d11 : Symbol(d11, Decl(unionsOfTupleTypes1.ts, 26, 13)) +>d12 : Symbol(d12, Decl(unionsOfTupleTypes1.ts, 26, 18)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + [d20, d21, d22] = t2; +>d20 : Symbol(d20, Decl(unionsOfTupleTypes1.ts, 27, 9)) +>d21 : Symbol(d21, Decl(unionsOfTupleTypes1.ts, 27, 13)) +>d22 : Symbol(d22, Decl(unionsOfTupleTypes1.ts, 27, 18)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + [d30, d31, d32] = t3; +>d30 : Symbol(d30, Decl(unionsOfTupleTypes1.ts, 28, 9)) +>d31 : Symbol(d31, Decl(unionsOfTupleTypes1.ts, 28, 13)) +>d32 : Symbol(d32, Decl(unionsOfTupleTypes1.ts, 28, 18)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + [d40, d41, d42] = t4; +>d40 : Symbol(d40, Decl(unionsOfTupleTypes1.ts, 29, 9)) +>d41 : Symbol(d41, Decl(unionsOfTupleTypes1.ts, 29, 13)) +>d42 : Symbol(d42, Decl(unionsOfTupleTypes1.ts, 29, 18)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t10 = t1[0]; // string +>t10 : Symbol(t10, Decl(unionsOfTupleTypes1.ts, 34, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>0 : Symbol(0) + + let t11 = t1[1]; // number +>t11 : Symbol(t11, Decl(unionsOfTupleTypes1.ts, 35, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>1 : Symbol(1) + + let t12 = t1[2]; // undefined +>t12 : Symbol(t12, Decl(unionsOfTupleTypes1.ts, 36, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) + + let t1x = t1[x]; // string | number +>t1x : Symbol(t1x, Decl(unionsOfTupleTypes1.ts, 37, 7)) +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t20 = t2[0]; // string | boolean +>t20 : Symbol(t20, Decl(unionsOfTupleTypes1.ts, 38, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>0 : Symbol(0) + + let t21 = t2[1]; // number | undefined +>t21 : Symbol(t21, Decl(unionsOfTupleTypes1.ts, 39, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>1 : Symbol(1) + + let t22 = t2[2]; // undefined +>t22 : Symbol(t22, Decl(unionsOfTupleTypes1.ts, 40, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) + + let t2x = t2[x]; // string | number | boolean +>t2x : Symbol(t2x, Decl(unionsOfTupleTypes1.ts, 41, 7)) +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t30 = t3[0]; // string +>t30 : Symbol(t30, Decl(unionsOfTupleTypes1.ts, 42, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>0 : Symbol(0) + + let t31 = t3[1]; // number +>t31 : Symbol(t31, Decl(unionsOfTupleTypes1.ts, 43, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let t32 = t3[2]; // number +>t32 : Symbol(t32, Decl(unionsOfTupleTypes1.ts, 44, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + let t3x = t3[x]; // string | number +>t3x : Symbol(t3x, Decl(unionsOfTupleTypes1.ts, 45, 7)) +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + let t40 = t4[0]; // string | boolean +>t40 : Symbol(t40, Decl(unionsOfTupleTypes1.ts, 46, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>0 : Symbol(0) + + let t41 = t4[1]; // number | undefined +>t41 : Symbol(t41, Decl(unionsOfTupleTypes1.ts, 47, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t42 = t4[2]; // number | undefined +>t42 : Symbol(t42, Decl(unionsOfTupleTypes1.ts, 48, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) + + let t4x = t4[x]; // string | number | boolean +>t4x : Symbol(t4x, Decl(unionsOfTupleTypes1.ts, 49, 7)) +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 25, 43)) + + t1[1] = 42; +>t1 : Symbol(t1, Decl(unionsOfTupleTypes1.ts, 25, 12)) +>1 : Symbol(1) + + t2[1] = 42; +>t2 : Symbol(t2, Decl(unionsOfTupleTypes1.ts, 25, 19)) +>1 : Symbol(1) + + t3[1] = 42; +>t3 : Symbol(t3, Decl(unionsOfTupleTypes1.ts, 25, 27)) + + t4[1] = 42; +>t4 : Symbol(t4, Decl(unionsOfTupleTypes1.ts, 25, 35)) +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) + +const ex: Unioned = ["hi"] as Unioned; +>ex : Symbol(ex, Decl(unionsOfTupleTypes1.ts, 59, 5)) +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) +>Unioned : Symbol(Unioned, Decl(unionsOfTupleTypes1.ts, 54, 1)) + +const [x, y] = ex; +>x : Symbol(x, Decl(unionsOfTupleTypes1.ts, 61, 7)) +>y : Symbol(y, Decl(unionsOfTupleTypes1.ts, 61, 9)) +>ex : Symbol(ex, Decl(unionsOfTupleTypes1.ts, 59, 5)) + diff --git a/tests/baselines/reference/unionsOfTupleTypes1.types b/tests/baselines/reference/unionsOfTupleTypes1.types new file mode 100644 index 00000000000..e44114f5a6a --- /dev/null +++ b/tests/baselines/reference/unionsOfTupleTypes1.types @@ -0,0 +1,266 @@ +=== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts === +type T1 = [string, number]; +>T1 : [string, number] + +type T2 = [boolean] | [string, number]; +>T2 : T2 + +type T3 = [string, ...number[]]; +>T3 : [string, ...number[]] + +type T4 = [boolean] | [string, ...number[]]; +>T4 : T4 + +type T10 = T1[0]; // string +>T10 : string + +type T11 = T1[1]; // number +>T11 : number + +type T12 = T1[2]; // undefined +>T12 : undefined + +type T1N = T1[number]; // string | number +>T1N : string | number + +type T20 = T2[0]; // string | boolean +>T20 : string | boolean + +type T21 = T2[1]; // number | undefined +>T21 : number | undefined + +type T22 = T2[2]; // undefined +>T22 : undefined + +type T2N = T2[number]; // string | number | boolean +>T2N : string | number | boolean + +type T30 = T3[0]; // string +>T30 : string + +type T31 = T3[1]; // number +>T31 : number + +type T32 = T3[2]; // number +>T32 : number + +type T3N = T3[number]; // string | number +>T3N : string | number + +type T40 = T4[0]; // string | boolean +>T40 : string | boolean + +type T41 = T4[1]; // number | undefined +>T41 : number | undefined + +type T42 = T4[2]; // number | undefined +>T42 : number | undefined + +type T4N = T4[number]; // string | number | boolean +>T4N : string | number | boolean + +function f1(t1: T1, t2: T2, t3: T3, t4: T4, x: number) { +>f1 : (t1: [string, number], t2: T2, t3: [string, ...number[]], t4: T4, x: number) => void +>t1 : [string, number] +>t2 : T2 +>t3 : [string, ...number[]] +>t4 : T4 +>x : number + + let [d10, d11, d12] = t1; // string, number +>d10 : string +>d11 : number +>d12 : any +>t1 : [string, number] + + let [d20, d21, d22] = t2; // string | boolean, number | undefined +>d20 : string | boolean +>d21 : number | undefined +>d22 : any +>t2 : T2 + + let [d30, d31, d32] = t3; // string, number, number +>d30 : string +>d31 : number +>d32 : number +>t3 : [string, ...number[]] + + let [d40, d41, d42] = t4; // string | boolean, number | undefined, number | undefined +>d40 : string | boolean +>d41 : number | undefined +>d42 : number | undefined +>t4 : T4 + + [d10, d11, d12] = t1; +>[d10, d11, d12] = t1 : [string, number] +>[d10, d11, d12] : [string, number, any] +>d10 : string +>d11 : number +>d12 : any +>t1 : [string, number] + + [d20, d21, d22] = t2; +>[d20, d21, d22] = t2 : T2 +>[d20, d21, d22] : [string | boolean, number | undefined, any] +>d20 : string | boolean +>d21 : number | undefined +>d22 : any +>t2 : T2 + + [d30, d31, d32] = t3; +>[d30, d31, d32] = t3 : [string, ...number[]] +>[d30, d31, d32] : [string, number, number] +>d30 : string +>d31 : number +>d32 : number +>t3 : [string, ...number[]] + + [d40, d41, d42] = t4; +>[d40, d41, d42] = t4 : T4 +>[d40, d41, d42] : [string | boolean, number | undefined, number | undefined] +>d40 : string | boolean +>d41 : number | undefined +>d42 : number | undefined +>t4 : T4 + + let t10 = t1[0]; // string +>t10 : string +>t1[0] : string +>t1 : [string, number] +>0 : 0 + + let t11 = t1[1]; // number +>t11 : number +>t1[1] : number +>t1 : [string, number] +>1 : 1 + + let t12 = t1[2]; // undefined +>t12 : undefined +>t1[2] : undefined +>t1 : [string, number] +>2 : 2 + + let t1x = t1[x]; // string | number +>t1x : string | number +>t1[x] : string | number +>t1 : [string, number] +>x : number + + let t20 = t2[0]; // string | boolean +>t20 : string | boolean +>t2[0] : string | boolean +>t2 : T2 +>0 : 0 + + let t21 = t2[1]; // number | undefined +>t21 : number | undefined +>t2[1] : number | undefined +>t2 : T2 +>1 : 1 + + let t22 = t2[2]; // undefined +>t22 : undefined +>t2[2] : undefined +>t2 : T2 +>2 : 2 + + let t2x = t2[x]; // string | number | boolean +>t2x : string | number | boolean +>t2[x] : string | number | boolean +>t2 : T2 +>x : number + + let t30 = t3[0]; // string +>t30 : string +>t3[0] : string +>t3 : [string, ...number[]] +>0 : 0 + + let t31 = t3[1]; // number +>t31 : number +>t3[1] : number +>t3 : [string, ...number[]] +>1 : 1 + + let t32 = t3[2]; // number +>t32 : number +>t3[2] : number +>t3 : [string, ...number[]] +>2 : 2 + + let t3x = t3[x]; // string | number +>t3x : string | number +>t3[x] : string | number +>t3 : [string, ...number[]] +>x : number + + let t40 = t4[0]; // string | boolean +>t40 : string | boolean +>t4[0] : string | boolean +>t4 : T4 +>0 : 0 + + let t41 = t4[1]; // number | undefined +>t41 : number | undefined +>t4[1] : number | undefined +>t4 : T4 +>1 : 1 + + let t42 = t4[2]; // number | undefined +>t42 : number | undefined +>t4[2] : number | undefined +>t4 : T4 +>2 : 2 + + let t4x = t4[x]; // string | number | boolean +>t4x : string | number | boolean +>t4[x] : string | number | boolean +>t4 : T4 +>x : number + + t1[1] = 42; +>t1[1] = 42 : 42 +>t1[1] : number +>t1 : [string, number] +>1 : 1 +>42 : 42 + + t2[1] = 42; +>t2[1] = 42 : 42 +>t2[1] : number | undefined +>t2 : T2 +>1 : 1 +>42 : 42 + + t3[1] = 42; +>t3[1] = 42 : 42 +>t3[1] : number +>t3 : [string, ...number[]] +>1 : 1 +>42 : 42 + + t4[1] = 42; +>t4[1] = 42 : 42 +>t4[1] : number | undefined +>t4 : T4 +>1 : 1 +>42 : 42 +} + +// Repro from #27543 + +type Unioned = [string] | [string, number]; +>Unioned : Unioned + +const ex: Unioned = ["hi"] as Unioned; +>ex : Unioned +>["hi"] as Unioned : Unioned +>["hi"] : [string] +>"hi" : "hi" + +const [x, y] = ex; +>x : string +>y : number | undefined +>ex : Unioned + From 48f2dd963c26aa685dd0803be694f63e65cca3eb Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 6 Oct 2018 18:17:10 -0700 Subject: [PATCH 022/262] Fix linting issue --- 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 6ee5ad85ced..d5230077eee 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12869,7 +12869,7 @@ namespace ts { return propType; } if (everyType(type, isTupleType)) { - let restType = mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); + const restType = mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); if (restType !== undefinedType) { return restType; } From b85e9e1cc151ae771601fd1cfdd9dd3a7c68616e Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 8 Oct 2018 14:36:37 -0700 Subject: [PATCH 023/262] Use relative module specifiers in error messages if possible (#27441) * Use relative module specifiers in error messages if possible * Dont share number --- src/compiler/checker.ts | 21 ++++++++++++---- src/compiler/moduleSpecifiers.ts | 10 +++++--- src/compiler/types.ts | 9 +++++-- .../aliasDoesNotDuplicateSignatures.symbols | 2 +- .../allowSyntheticDefaultImports8.errors.txt | 4 ++-- .../reference/ambientDeclarations.symbols | 2 +- .../ambientDeclarationsExternal.symbols | 4 ++-- .../baselines/reference/ambientErrors.symbols | 6 ++--- ...oduleWithInternalImportDeclaration.symbols | 2 +- ...leWithoutInternalImportDeclaration.symbols | 2 +- .../reference/augmentExportEquals3.symbols | 4 ++-- .../reference/augmentExportEquals3_1.symbols | 4 ++-- .../reference/augmentExportEquals4.symbols | 4 ++-- .../reference/augmentExportEquals4_1.symbols | 4 ++-- .../reference/augmentExportEquals5.symbols | 4 ++-- .../reference/augmentExportEquals6.symbols | 4 ++-- .../reference/augmentExportEquals6_1.symbols | 4 ++-- .../reference/bangInModuleName.symbols | 2 +- ...leImportedTypeUseInTypeArgPosition.symbols | 4 ++-- ...CrossFileImportTypeOfAmbientModule.symbols | 2 +- .../reference/declaredExternalModule.symbols | 2 +- ...ExternalModuleWithExportAssignment.symbols | 2 +- ...BindingFollowedWithNamedImport1.errors.txt | 24 +++++++++---------- ...ngFollowedWithNamedImport1InEs5.errors.txt | 24 +++++++++---------- ...lowedWithNamedImport1WithExport.errors.txt | 24 +++++++++---------- ...dingFollowedWithNamedImportDts1.errors.txt | 24 +++++++++---------- ...ImportNamedImportNoExportMember.errors.txt | 8 +++---- ...ImportNamedImportNoNamedExports.errors.txt | 8 +++---- ...gnmentMembersVisibleInAugmentation.symbols | 2 +- .../reference/exportDefaultVariable.symbols | 2 +- .../reference/exportEqualsOfModule.symbols | 8 +++---- .../exportSpellingSuggestion.errors.txt | 4 ++-- ...alModuleReferenceDoubleUnderscore1.symbols | 4 ++-- .../reference/mergedDeclarations7.symbols | 2 +- ...ntationDuringSyntheticDefaultCheck.symbols | 10 ++++---- ...uleMemberMissingErrorIsRelative.errors.txt | 9 +++++++ .../moduleMemberMissingErrorIsRelative.js | 13 ++++++++++ ...moduleMemberMissingErrorIsRelative.symbols | 6 +++++ .../moduleMemberMissingErrorIsRelative.types | 6 +++++ ...module_augmentUninstantiatedModule.symbols | 6 ++--- ...ientExternalModuleImportWithExport.symbols | 4 ++-- ...tExternalModuleImportWithoutExport.symbols | 4 ++-- ...ropertyIdentityWithPrivacyMismatch.symbols | 4 ++-- .../quotedModuleNameMustBeAmbient.symbols | 4 ++-- ...ransitiveImportHasValidDeclaration.symbols | 4 ++-- .../spellingSuggestionModule.symbols | 2 +- .../reference/tsxDynamicTagName5.symbols | 2 +- .../reference/tsxDynamicTagName7.symbols | 2 +- .../reference/tsxDynamicTagName8.symbols | 2 +- .../reference/tsxDynamicTagName9.symbols | 2 +- .../reference/tsxElementResolution17.symbols | 4 ++-- .../reference/tsxExternalModuleEmit1.symbols | 2 +- .../reference/tsxExternalModuleEmit2.symbols | 2 +- .../reference/tsxPreserveEmit1.symbols | 4 ++-- ...it.multiFileBackReferenceToSelf.errors.txt | 4 ++-- .../reference/umd-augmentation-3.symbols | 2 +- .../reference/umd-augmentation-4.symbols | 2 +- .../unclosedExportClause01.errors.txt | 16 ++++++------- .../moduleMemberMissingErrorIsRelative.ts | 4 ++++ 59 files changed, 207 insertions(+), 149 deletions(-) create mode 100644 tests/baselines/reference/moduleMemberMissingErrorIsRelative.errors.txt create mode 100644 tests/baselines/reference/moduleMemberMissingErrorIsRelative.js create mode 100644 tests/baselines/reference/moduleMemberMissingErrorIsRelative.symbols create mode 100644 tests/baselines/reference/moduleMemberMissingErrorIsRelative.types create mode 100644 tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1a525a9f239..fe2ce42652a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1935,7 +1935,7 @@ namespace ts { combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - const moduleName = getFullyQualifiedName(moduleSymbol); + const moduleName = getFullyQualifiedName(moduleSymbol, node); const declarationName = declarationNameToString(name); const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -2101,8 +2101,8 @@ namespace ts { } } - function getFullyQualifiedName(symbol: Symbol): string { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol: Symbol, containingLocation?: Node): string { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, SymbolFormatFlags.DoNotIncludeSymbolChain | SymbolFormatFlags.AllowAnyNodeKind); } /** @@ -3078,6 +3078,9 @@ namespace ts { if (flags & SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope) { nodeFlags |= NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; } + if (flags & SymbolFormatFlags.DoNotIncludeSymbolChain) { + nodeFlags |= NodeBuilderFlags.DoNotIncludeSymbolChain; + } const builder = flags & SymbolFormatFlags.AllowAnyNodeKind ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); @@ -3155,7 +3158,12 @@ namespace ts { const context: NodeBuilderContext = { enclosingDeclaration, flags: flags || NodeBuilderFlags.None, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: noop, moduleResolverHost: flags! & NodeBuilderFlags.DoNotIncludeSymbolChain ? { + getCommonSourceDirectory: (host as Program).getCommonSourceDirectory ? () => (host as Program).getCommonSourceDirectory() : () => "", + getSourceFiles: () => host.getSourceFiles(), + getCurrentDirectory: host.getCurrentDirectory && (() => host.getCurrentDirectory!()) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -3885,7 +3893,7 @@ namespace ts { // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. let chain: Symbol[]; const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & NodeBuilderFlags.UseFullyQualifiedType) && !(context.flags & NodeBuilderFlags.DoNotIncludeSymbolChain)) { chain = Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); Debug.assert(chain && chain.length > 0); } @@ -4140,6 +4148,9 @@ namespace ts { function createExpressionFromSymbolChain(chain: Symbol[], index: number): Expression { const typeParameterNodes = lookupTypeParameterNodes(chain, index, context); const symbol = chain[index]; + if (some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= NodeBuilderFlags.InInitialEntityName; diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index e50aaf99453..f28bc43e61a 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -260,6 +260,9 @@ namespace ts.moduleSpecifiers { } function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions): string | undefined { + if (!host.fileExists || !host.readFile) { + return undefined; + } const parts: NodeModulePathParts = getNodeModulePathParts(moduleFileName)!; if (!parts) { return undefined; @@ -267,8 +270,8 @@ namespace ts.moduleSpecifiers { const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); const packageJsonPath = combinePaths(packageRootPath, "package.json"); - const packageJsonContent = host.fileExists!(packageJsonPath) - ? JSON.parse(host.readFile!(packageJsonPath)!) + const packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)!) : undefined; const versionPaths = packageJsonContent && packageJsonContent.typesVersions ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -325,11 +328,12 @@ namespace ts.moduleSpecifiers { } function tryGetAnyFileFromPath(host: ModuleSpecifierResolutionHost, path: string) { + if (!host.fileExists) return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory const extensions = getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]); for (const e of extensions) { const fullPath = path + e; - if (host.fileExists!(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c7a5979d20b..c8f9c15aa84 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2908,7 +2908,7 @@ namespace ts { } /* @internal */ - export interface TypeCheckerHost { + export interface TypeCheckerHost extends ModuleSpecifierResolutionHost { getCompilerOptions(): CompilerOptions; getSourceFiles(): ReadonlyArray; @@ -3183,6 +3183,8 @@ namespace ts { InTypeAlias = 1 << 23, // Writing type in type alias declaration InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression InReverseMappedType = 1 << 25, + + /* @internal */ DoNotIncludeSymbolChain = 1 << 26, // Skip looking up and printing an accessible symbol chain } // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment @@ -3245,6 +3247,9 @@ namespace ts { // Prefer aliases which are not directly visible UseAliasDefinedOutsideCurrentScope = 0x00000008, + + // Skip building an accessible symbol chain + /* @internal */ DoNotIncludeSymbolChain = 0x00000010, } /* @internal */ @@ -5379,7 +5384,7 @@ namespace ts { reportInaccessibleThisError?(): void; reportPrivateInBaseOfClassExpression?(propertyName: string): void; reportInaccessibleUniqueSymbolError?(): void; - moduleResolverHost?: EmitHost; + moduleResolverHost?: ModuleSpecifierResolutionHost & { getSourceFiles(): ReadonlyArray, getCommonSourceDirectory(): string }; trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; } diff --git a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols index 21ae7940f96..912798f4a1b 100644 --- a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols +++ b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols @@ -6,7 +6,7 @@ declare namespace demoNS { >f : Symbol(f, Decl(demo.d.ts, 0, 26)) } declare module 'demoModule' { ->'demoModule' : Symbol('demoModule', Decl(demo.d.ts, 2, 1)) +>'demoModule' : Symbol("demoModule", Decl(demo.d.ts, 2, 1)) import alias = demoNS; >alias : Symbol(alias, Decl(demo.d.ts, 3, 29)) diff --git a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt index acb584f8fd9..ea5a7ddf30e 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt +++ b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +tests/cases/compiler/a.ts(1,10): error TS2305: Module '"./b"' has no exported member 'default'. ==== tests/cases/compiler/b.d.ts (0 errors) ==== @@ -9,6 +9,6 @@ tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' ==== tests/cases/compiler/a.ts (1 errors) ==== import { default as Foo } from "./b"; ~~~~~~~ -!!! error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +!!! error TS2305: Module '"./b"' has no exported member 'default'. Foo.bar(); Foo.foo(); \ No newline at end of file diff --git a/tests/baselines/reference/ambientDeclarations.symbols b/tests/baselines/reference/ambientDeclarations.symbols index 1436c698cff..b4a6c394a91 100644 --- a/tests/baselines/reference/ambientDeclarations.symbols +++ b/tests/baselines/reference/ambientDeclarations.symbols @@ -160,7 +160,7 @@ var q = M1.fn(); // Ambient external module in the global module // Ambient external module with a string literal name that is a top level external module name declare module 'external1' { ->'external1' : Symbol('external1', Decl(ambientDeclarations.ts, 67, 16)) +>'external1' : Symbol("external1", Decl(ambientDeclarations.ts, 67, 16)) var q; >q : Symbol(q, Decl(ambientDeclarations.ts, 72, 7)) diff --git a/tests/baselines/reference/ambientDeclarationsExternal.symbols b/tests/baselines/reference/ambientDeclarationsExternal.symbols index 49f0775e136..f0d2ec28221 100644 --- a/tests/baselines/reference/ambientDeclarationsExternal.symbols +++ b/tests/baselines/reference/ambientDeclarationsExternal.symbols @@ -20,7 +20,7 @@ var n: number; === tests/cases/conformance/ambient/decls.ts === // Ambient external module with export assignment declare module 'equ' { ->'equ' : Symbol('equ', Decl(decls.ts, 0, 0)) +>'equ' : Symbol("equ", Decl(decls.ts, 0, 0)) var x; >x : Symbol(x, Decl(decls.ts, 2, 7)) @@ -30,7 +30,7 @@ declare module 'equ' { } declare module 'equ2' { ->'equ2' : Symbol('equ2', Decl(decls.ts, 4, 1)) +>'equ2' : Symbol("equ2", Decl(decls.ts, 4, 1)) var x: number; >x : Symbol(x, Decl(decls.ts, 7, 7)) diff --git a/tests/baselines/reference/ambientErrors.symbols b/tests/baselines/reference/ambientErrors.symbols index 90efbe8383a..308cce2b734 100644 --- a/tests/baselines/reference/ambientErrors.symbols +++ b/tests/baselines/reference/ambientErrors.symbols @@ -90,16 +90,16 @@ module M2 { >M2 : Symbol(M2, Decl(ambientErrors.ts, 42, 1)) declare module 'nope' { } ->'nope' : Symbol('nope', Decl(ambientErrors.ts, 45, 11)) +>'nope' : Symbol("nope", Decl(ambientErrors.ts, 45, 11)) } // Ambient external module with a string literal name that isn't a top level external module name declare module '../foo' { } ->'../foo' : Symbol('../foo', Decl(ambientErrors.ts, 47, 1)) +>'../foo' : Symbol("../foo", Decl(ambientErrors.ts, 47, 1)) // Ambient external module with export assignment and other exported members declare module 'bar' { ->'bar' : Symbol('bar', Decl(ambientErrors.ts, 50, 27)) +>'bar' : Symbol("bar", Decl(ambientErrors.ts, 50, 27)) var n; >n : Symbol(n, Decl(ambientErrors.ts, 54, 7)) diff --git a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols index 621c7b3ebfc..75fb494da11 100644 --- a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols index 6827122959d..625e5392893 100644 --- a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithoutInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/augmentExportEquals3.symbols b/tests/baselines/reference/augmentExportEquals3.symbols index e4e7a8e1a5f..2644d6d5b21 100644 --- a/tests/baselines/reference/augmentExportEquals3.symbols +++ b/tests/baselines/reference/augmentExportEquals3.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === function foo() {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals3_1.symbols b/tests/baselines/reference/augmentExportEquals3_1.symbols index 2431b293dea..181ceb343b8 100644 --- a/tests/baselines/reference/augmentExportEquals3_1.symbols +++ b/tests/baselines/reference/augmentExportEquals3_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) function foo(): void; ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals4.symbols b/tests/baselines/reference/augmentExportEquals4.symbols index f1f63762545..75da60335c3 100644 --- a/tests/baselines/reference/augmentExportEquals4.symbols +++ b/tests/baselines/reference/augmentExportEquals4.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals4_1.symbols b/tests/baselines/reference/augmentExportEquals4_1.symbols index d2a3c001825..97d115e453e 100644 --- a/tests/baselines/reference/augmentExportEquals4_1.symbols +++ b/tests/baselines/reference/augmentExportEquals4_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals5.symbols b/tests/baselines/reference/augmentExportEquals5.symbols index 244073b6515..ef62f66817e 100644 --- a/tests/baselines/reference/augmentExportEquals5.symbols +++ b/tests/baselines/reference/augmentExportEquals5.symbols @@ -16,12 +16,12 @@ declare module "express" { >"express" : Symbol("express", Decl(express.d.ts, 4, 1)) function e(): e.Express; ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) >e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28)) >Express : Symbol(Express, Decl(express.d.ts, 52, 9)) namespace e { ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) interface IRoute { >IRoute : Symbol(IRoute, Decl(express.d.ts, 8, 17)) diff --git a/tests/baselines/reference/augmentExportEquals6.symbols b/tests/baselines/reference/augmentExportEquals6.symbols index 2125b650464..72ef677c592 100644 --- a/tests/baselines/reference/augmentExportEquals6.symbols +++ b/tests/baselines/reference/augmentExportEquals6.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) export class A {} >A : Symbol(A, Decl(file1.ts, 1, 15), Decl(file2.ts, 4, 26)) diff --git a/tests/baselines/reference/augmentExportEquals6_1.symbols b/tests/baselines/reference/augmentExportEquals6_1.symbols index b75f8131c01..e37b094549a 100644 --- a/tests/baselines/reference/augmentExportEquals6_1.symbols +++ b/tests/baselines/reference/augmentExportEquals6_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) class A {} >A : Symbol(A, Decl(file1.d.ts, 2, 19), Decl(file2.ts, 4, 24)) diff --git a/tests/baselines/reference/bangInModuleName.symbols b/tests/baselines/reference/bangInModuleName.symbols index ca3d4a161f5..fa1b84ba296 100644 --- a/tests/baselines/reference/bangInModuleName.symbols +++ b/tests/baselines/reference/bangInModuleName.symbols @@ -10,7 +10,7 @@ declare module "http" { } declare module 'intern/dojo/node!http' { ->'intern/dojo/node!http' : Symbol('intern/dojo/node!http', Decl(a.d.ts, 1, 1)) +>'intern/dojo/node!http' : Symbol("intern/dojo/node!http", Decl(a.d.ts, 1, 1)) import http = require('http'); >http : Symbol(http, Decl(a.d.ts, 3, 40)) diff --git a/tests/baselines/reference/declFileImportedTypeUseInTypeArgPosition.symbols b/tests/baselines/reference/declFileImportedTypeUseInTypeArgPosition.symbols index f9ee7a85bcd..c1591b3981b 100644 --- a/tests/baselines/reference/declFileImportedTypeUseInTypeArgPosition.symbols +++ b/tests/baselines/reference/declFileImportedTypeUseInTypeArgPosition.symbols @@ -4,7 +4,7 @@ class List { } >T : Symbol(T, Decl(declFileImportedTypeUseInTypeArgPosition.ts, 0, 11)) declare module 'mod1' { ->'mod1' : Symbol('mod1', Decl(declFileImportedTypeUseInTypeArgPosition.ts, 0, 17)) +>'mod1' : Symbol("mod1", Decl(declFileImportedTypeUseInTypeArgPosition.ts, 0, 17)) class Foo { >Foo : Symbol(Foo, Decl(declFileImportedTypeUseInTypeArgPosition.ts, 1, 23)) @@ -12,7 +12,7 @@ declare module 'mod1' { } declare module 'moo' { ->'moo' : Symbol('moo', Decl(declFileImportedTypeUseInTypeArgPosition.ts, 4, 1)) +>'moo' : Symbol("moo", Decl(declFileImportedTypeUseInTypeArgPosition.ts, 4, 1)) import x = require('mod1'); >x : Symbol(x, Decl(declFileImportedTypeUseInTypeArgPosition.ts, 6, 22)) diff --git a/tests/baselines/reference/declarationEmitCrossFileImportTypeOfAmbientModule.symbols b/tests/baselines/reference/declarationEmitCrossFileImportTypeOfAmbientModule.symbols index 368ebcf3650..596fd78705a 100644 --- a/tests/baselines/reference/declarationEmitCrossFileImportTypeOfAmbientModule.symbols +++ b/tests/baselines/reference/declarationEmitCrossFileImportTypeOfAmbientModule.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/types/component.d.ts === declare module '@namespace/component' { ->'@namespace/component' : Symbol('@namespace/component', Decl(component.d.ts, 0, 0)) +>'@namespace/component' : Symbol("@namespace/component", Decl(component.d.ts, 0, 0)) export class Foo {} >Foo : Symbol(Foo, Decl(component.d.ts, 0, 39)) diff --git a/tests/baselines/reference/declaredExternalModule.symbols b/tests/baselines/reference/declaredExternalModule.symbols index 9d60a99a2c2..c8ad49a8f3c 100644 --- a/tests/baselines/reference/declaredExternalModule.symbols +++ b/tests/baselines/reference/declaredExternalModule.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/declaredExternalModule.ts === declare module 'connect' { ->'connect' : Symbol('connect', Decl(declaredExternalModule.ts, 0, 0)) +>'connect' : Symbol("connect", Decl(declaredExternalModule.ts, 0, 0)) interface connectModule { >connectModule : Symbol(connectModule, Decl(declaredExternalModule.ts, 0, 26)) diff --git a/tests/baselines/reference/declaredExternalModuleWithExportAssignment.symbols b/tests/baselines/reference/declaredExternalModuleWithExportAssignment.symbols index 955cc2489d2..857a0ae8c8f 100644 --- a/tests/baselines/reference/declaredExternalModuleWithExportAssignment.symbols +++ b/tests/baselines/reference/declaredExternalModuleWithExportAssignment.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/declaredExternalModuleWithExportAssignment.ts === declare module 'connect' { ->'connect' : Symbol('connect', Decl(declaredExternalModuleWithExportAssignment.ts, 0, 0)) +>'connect' : Symbol("connect", Decl(declaredExternalModuleWithExportAssignment.ts, 0, 0)) interface connectModule { >connectModule : Symbol(connectModule, Decl(declaredExternalModuleWithExportAssignment.ts, 0, 26)) diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt index 86900c03bbe..65eae425bc5 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(3,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(5,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,30): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(9,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(3,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(5,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,30): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(9,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. ==== tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0.ts (0 errors) ==== @@ -15,24 +15,24 @@ tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27) var x1: number = defaultBinding1; import defaultBinding2, { a } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. var x1: number = defaultBinding2; import defaultBinding3, { a as b } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. var x1: number = defaultBinding3; import defaultBinding4, { x, a as y } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. var x1: number = defaultBinding4; import defaultBinding5, { x as z, } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. var x1: number = defaultBinding5; import defaultBinding6, { m, } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. var x1: number = defaultBinding6; \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt index 5649b5c2ed0..b8c06ab3c17 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(3,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(5,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,30): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(9,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(11,27): error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(3,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(5,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,30): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(9,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(11,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. ==== tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0.ts (0 errors) ==== @@ -15,24 +15,24 @@ tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(1 var x: number = defaultBinding1; import defaultBinding2, { a } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. var x: number = defaultBinding2; import defaultBinding3, { a as b } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. var x: number = defaultBinding3; import defaultBinding4, { x, a as y } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. var x: number = defaultBinding4; import defaultBinding5, { x as z, } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. var x: number = defaultBinding5; import defaultBinding6, { m, } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. +!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. var x: number = defaultBinding6; \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt index 6acc3edc77e..6d0526d474b 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt @@ -1,20 +1,20 @@ tests/cases/compiler/client.ts(1,1): error TS1191: An import declaration cannot have modifiers. tests/cases/compiler/client.ts(2,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(3,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(3,34): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +tests/cases/compiler/client.ts(3,34): error TS2305: Module '"./server"' has no exported member 'a'. tests/cases/compiler/client.ts(4,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(5,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(5,34): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +tests/cases/compiler/client.ts(5,34): error TS2305: Module '"./server"' has no exported member 'a'. tests/cases/compiler/client.ts(6,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(7,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(7,34): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. -tests/cases/compiler/client.ts(7,37): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +tests/cases/compiler/client.ts(7,34): error TS2305: Module '"./server"' has no exported member 'x'. +tests/cases/compiler/client.ts(7,37): error TS2305: Module '"./server"' has no exported member 'a'. tests/cases/compiler/client.ts(8,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(9,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(9,34): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. +tests/cases/compiler/client.ts(9,34): error TS2305: Module '"./server"' has no exported member 'x'. tests/cases/compiler/client.ts(10,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(11,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(11,34): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'm'. +tests/cases/compiler/client.ts(11,34): error TS2305: Module '"./server"' has no exported member 'm'. tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported variable 'x1'. @@ -33,7 +33,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x1: number = defaultBinding2; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -41,7 +41,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x1: number = defaultBinding3; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -49,9 +49,9 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. +!!! error TS2305: Module '"./server"' has no exported member 'x'. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x1: number = defaultBinding4; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -59,7 +59,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. +!!! error TS2305: Module '"./server"' has no exported member 'x'. export var x1: number = defaultBinding5; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -67,7 +67,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'm'. +!!! error TS2305: Module '"./server"' has no exported member 'm'. export var x1: number = defaultBinding6; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt index b078d0abfe3..b2313170af7 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/client.ts(3,27): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. -tests/cases/compiler/client.ts(5,27): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. -tests/cases/compiler/client.ts(7,27): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. -tests/cases/compiler/client.ts(7,30): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. -tests/cases/compiler/client.ts(9,27): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. -tests/cases/compiler/client.ts(11,27): error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'm'. +tests/cases/compiler/client.ts(3,27): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(5,27): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(7,27): error TS2305: Module '"./server"' has no exported member 'x'. +tests/cases/compiler/client.ts(7,30): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(9,27): error TS2305: Module '"./server"' has no exported member 'x'. +tests/cases/compiler/client.ts(11,27): error TS2305: Module '"./server"' has no exported member 'm'. ==== tests/cases/compiler/server.ts (0 errors) ==== @@ -15,23 +15,23 @@ tests/cases/compiler/client.ts(11,27): error TS2305: Module '"tests/cases/compil export var x1 = new defaultBinding1(); import defaultBinding2, { a } from "./server"; ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x2 = new defaultBinding2(); import defaultBinding3, { a as b } from "./server"; ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x3 = new defaultBinding3(); import defaultBinding4, { x, a as y } from "./server"; ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. +!!! error TS2305: Module '"./server"' has no exported member 'x'. ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'a'. +!!! error TS2305: Module '"./server"' has no exported member 'a'. export var x4 = new defaultBinding4(); import defaultBinding5, { x as z, } from "./server"; ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'x'. +!!! error TS2305: Module '"./server"' has no exported member 'x'. export var x5 = new defaultBinding5(); import defaultBinding6, { m, } from "./server"; ~ -!!! error TS2305: Module '"tests/cases/compiler/server"' has no exported member 'm'. +!!! error TS2305: Module '"./server"' has no exported member 'm'. export var x6 = new defaultBinding6(); \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportNamedImportNoExportMember.errors.txt b/tests/baselines/reference/es6ImportNamedImportNoExportMember.errors.txt index 31c8002f735..43dac773eb3 100644 --- a/tests/baselines/reference/es6ImportNamedImportNoExportMember.errors.txt +++ b/tests/baselines/reference/es6ImportNamedImportNoExportMember.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/es6ImportNamedImport_1.ts(1,10): error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoExportMember_0"' has no exported member 'a1'. -tests/cases/compiler/es6ImportNamedImport_1.ts(2,10): error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoExportMember_0"' has no exported member 'x1'. +tests/cases/compiler/es6ImportNamedImport_1.ts(1,10): error TS2305: Module '"./es6ImportNamedImportNoExportMember_0"' has no exported member 'a1'. +tests/cases/compiler/es6ImportNamedImport_1.ts(2,10): error TS2305: Module '"./es6ImportNamedImportNoExportMember_0"' has no exported member 'x1'. ==== tests/cases/compiler/es6ImportNamedImportNoExportMember_0.ts (0 errors) ==== @@ -9,7 +9,7 @@ tests/cases/compiler/es6ImportNamedImport_1.ts(2,10): error TS2305: Module '"tes ==== tests/cases/compiler/es6ImportNamedImport_1.ts (2 errors) ==== import { a1 } from "./es6ImportNamedImportNoExportMember_0"; ~~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoExportMember_0"' has no exported member 'a1'. +!!! error TS2305: Module '"./es6ImportNamedImportNoExportMember_0"' has no exported member 'a1'. import { x1 as x } from "./es6ImportNamedImportNoExportMember_0"; ~~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoExportMember_0"' has no exported member 'x1'. \ No newline at end of file +!!! error TS2305: Module '"./es6ImportNamedImportNoExportMember_0"' has no exported member 'x1'. \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportNamedImportNoNamedExports.errors.txt b/tests/baselines/reference/es6ImportNamedImportNoNamedExports.errors.txt index 66fa2d217c2..aed703af0fc 100644 --- a/tests/baselines/reference/es6ImportNamedImportNoNamedExports.errors.txt +++ b/tests/baselines/reference/es6ImportNamedImportNoNamedExports.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts(1,10): error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts(2,10): error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts(1,10): error TS2305: Module '"./es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. +tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts(2,10): error TS2305: Module '"./es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. ==== tests/cases/compiler/es6ImportNamedImportNoNamedExports_0.ts (0 errors) ==== @@ -9,7 +9,7 @@ tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts(2,10): error TS2305 ==== tests/cases/compiler/es6ImportNamedImportNoNamedExports_1.ts (2 errors) ==== import { a } from "./es6ImportNamedImportNoNamedExports_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. +!!! error TS2305: Module '"./es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. import { a as x } from "./es6ImportNamedImportNoNamedExports_0"; ~ -!!! error TS2305: Module '"tests/cases/compiler/es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. \ No newline at end of file +!!! error TS2305: Module '"./es6ImportNamedImportNoNamedExports_0"' has no exported member 'a'. \ No newline at end of file diff --git a/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols index a5cf5aa514c..a9aecc513c4 100644 --- a/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols +++ b/tests/baselines/reference/exportAssignmentMembersVisibleInAugmentation.symbols @@ -3,7 +3,7 @@ export = foo; >foo : Symbol(foo, Decl(index.d.ts, 0, 13)) declare namespace foo { ->foo : Symbol(foo, Decl(index.d.ts, 0, 13), Decl(a.ts, 0, 27), Decl(b.ts, 0, 27)) +>foo : Symbol("/node_modules/foo/index.d.ts", Decl(index.d.ts, 0, 13), Decl(a.ts, 0, 27), Decl(b.ts, 0, 27)) export type T = number; >T : Symbol(T, Decl(index.d.ts, 1, 23)) diff --git a/tests/baselines/reference/exportDefaultVariable.symbols b/tests/baselines/reference/exportDefaultVariable.symbols index bed0641334b..667a1c43ba1 100644 --- a/tests/baselines/reference/exportDefaultVariable.symbols +++ b/tests/baselines/reference/exportDefaultVariable.symbols @@ -5,7 +5,7 @@ declare var io: any; >io : Symbol(io, Decl(exportDefaultVariable.ts, 2, 11)) declare module 'module' { ->'module' : Symbol('module', Decl(exportDefaultVariable.ts, 2, 20)) +>'module' : Symbol("module", Decl(exportDefaultVariable.ts, 2, 20)) export default io; >io : Symbol(io, Decl(exportDefaultVariable.ts, 2, 11)) diff --git a/tests/baselines/reference/exportEqualsOfModule.symbols b/tests/baselines/reference/exportEqualsOfModule.symbols index f664137d18b..b8df48fd0c6 100644 --- a/tests/baselines/reference/exportEqualsOfModule.symbols +++ b/tests/baselines/reference/exportEqualsOfModule.symbols @@ -1,13 +1,13 @@ === tests/cases/compiler/exportEqualsOfModule.ts === declare module '~popsicle/dist/request' { ->'~popsicle/dist/request' : Symbol('~popsicle/dist/request', Decl(exportEqualsOfModule.ts, 0, 0)) +>'~popsicle/dist/request' : Symbol("~popsicle/dist/request", Decl(exportEqualsOfModule.ts, 0, 0)) export class Request {} >Request : Symbol(Request, Decl(exportEqualsOfModule.ts, 0, 41)) } declare module '~popsicle/dist/common' { ->'~popsicle/dist/common' : Symbol('~popsicle/dist/common', Decl(exportEqualsOfModule.ts, 2, 1)) +>'~popsicle/dist/common' : Symbol("~popsicle/dist/common", Decl(exportEqualsOfModule.ts, 2, 1)) import { Request } from '~popsicle/dist/request'; >Request : Symbol(Request, Decl(exportEqualsOfModule.ts, 5, 12)) @@ -17,7 +17,7 @@ declare module '~popsicle/dist/common' { } declare module 'popsicle' { ->'popsicle' : Symbol('popsicle', Decl(exportEqualsOfModule.ts, 7, 1)) +>'popsicle' : Symbol("popsicle", Decl(exportEqualsOfModule.ts, 7, 1)) import alias = require('~popsicle/dist/common'); >alias : Symbol(alias, Decl(exportEqualsOfModule.ts, 9, 27)) @@ -27,7 +27,7 @@ declare module 'popsicle' { } declare module 'popsicle-proxy-agent' { ->'popsicle-proxy-agent' : Symbol('popsicle-proxy-agent', Decl(exportEqualsOfModule.ts, 12, 1)) +>'popsicle-proxy-agent' : Symbol("popsicle-proxy-agent", Decl(exportEqualsOfModule.ts, 12, 1)) import { Request } from 'popsicle'; >Request : Symbol(Request, Decl(exportEqualsOfModule.ts, 15, 12)) diff --git a/tests/baselines/reference/exportSpellingSuggestion.errors.txt b/tests/baselines/reference/exportSpellingSuggestion.errors.txt index cf8011fec45..8515003f39c 100644 --- a/tests/baselines/reference/exportSpellingSuggestion.errors.txt +++ b/tests/baselines/reference/exportSpellingSuggestion.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/modules/b.ts(1,10): error TS2724: Module '"tests/cases/conformance/es6/modules/a"' has no exported member 'assertNevar'. Did you mean 'assertNever'? +tests/cases/conformance/es6/modules/b.ts(1,10): error TS2724: Module '"./a"' has no exported member 'assertNevar'. Did you mean 'assertNever'? ==== tests/cases/conformance/es6/modules/a.ts (0 errors) ==== @@ -9,6 +9,6 @@ tests/cases/conformance/es6/modules/b.ts(1,10): error TS2724: Module '"tests/cas ==== tests/cases/conformance/es6/modules/b.ts (1 errors) ==== import { assertNevar } from "./a"; ~~~~~~~~~~~ -!!! error TS2724: Module '"tests/cases/conformance/es6/modules/a"' has no exported member 'assertNevar'. Did you mean 'assertNever'? +!!! error TS2724: Module '"./a"' has no exported member 'assertNevar'. Did you mean 'assertNever'? !!! related TS2728 tests/cases/conformance/es6/modules/a.ts:1:17: 'assertNever' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/externalModuleReferenceDoubleUnderscore1.symbols b/tests/baselines/reference/externalModuleReferenceDoubleUnderscore1.symbols index 7abc62fd422..f253ccc8213 100644 --- a/tests/baselines/reference/externalModuleReferenceDoubleUnderscore1.symbols +++ b/tests/baselines/reference/externalModuleReferenceDoubleUnderscore1.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/externalModuleReferenceDoubleUnderscore1.ts === declare module 'timezonecomplete' { ->'timezonecomplete' : Symbol('timezonecomplete', Decl(externalModuleReferenceDoubleUnderscore1.ts, 0, 0)) +>'timezonecomplete' : Symbol("timezonecomplete", Decl(externalModuleReferenceDoubleUnderscore1.ts, 0, 0)) import basics = require("__timezonecomplete/basics"); >basics : Symbol(basics, Decl(externalModuleReferenceDoubleUnderscore1.ts, 0, 35)) @@ -12,7 +12,7 @@ declare module 'timezonecomplete' { } declare module '__timezonecomplete/basics' { ->'__timezonecomplete/basics' : Symbol('__timezonecomplete/basics', Decl(externalModuleReferenceDoubleUnderscore1.ts, 3, 1)) +>'__timezonecomplete/basics' : Symbol("__timezonecomplete/basics", Decl(externalModuleReferenceDoubleUnderscore1.ts, 3, 1)) export enum TimeUnit { >TimeUnit : Symbol(TimeUnit, Decl(externalModuleReferenceDoubleUnderscore1.ts, 5, 44)) diff --git a/tests/baselines/reference/mergedDeclarations7.symbols b/tests/baselines/reference/mergedDeclarations7.symbols index dbc437d4f81..96daeec2f78 100644 --- a/tests/baselines/reference/mergedDeclarations7.symbols +++ b/tests/baselines/reference/mergedDeclarations7.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/passport.d.ts === declare module 'passport' { ->'passport' : Symbol('passport', Decl(passport.d.ts, 0, 0)) +>'passport' : Symbol("passport", Decl(passport.d.ts, 0, 0)) namespace passport { >passport : Symbol(passport, Decl(passport.d.ts, 0, 27), Decl(passport.d.ts, 11, 9)) diff --git a/tests/baselines/reference/moduleAugmentationDuringSyntheticDefaultCheck.symbols b/tests/baselines/reference/moduleAugmentationDuringSyntheticDefaultCheck.symbols index 115bb3b1a2c..e0b4b180f3e 100644 --- a/tests/baselines/reference/moduleAugmentationDuringSyntheticDefaultCheck.symbols +++ b/tests/baselines/reference/moduleAugmentationDuringSyntheticDefaultCheck.symbols @@ -6,12 +6,12 @@ import moment = require("moment-timezone"); === tests/cases/compiler/node_modules/moment/index.d.ts === declare function moment(): moment.Moment; ->moment : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) +>moment : Symbol("tests/cases/compiler/node_modules/moment/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) >moment : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41)) >Moment : Symbol(Moment, Decl(index.d.ts, 1, 26)) declare namespace moment { ->moment : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) +>moment : Symbol("tests/cases/compiler/node_modules/moment/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) interface Moment extends Object { >Moment : Symbol(Moment, Decl(index.d.ts, 1, 26), Decl(idx.ts, 1, 25), Decl(idx.ts, 6, 34), Decl(index.d.ts, 2, 25)) @@ -32,7 +32,7 @@ export = moment; >moment : Symbol(moment, Decl(index.d.ts, 0, 6)) declare module "moment" { ->"moment" : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) +>"moment" : Symbol("tests/cases/compiler/node_modules/moment/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) interface Moment { >Moment : Symbol(Moment, Decl(index.d.ts, 1, 26), Decl(idx.ts, 1, 25), Decl(idx.ts, 6, 34), Decl(index.d.ts, 2, 25)) @@ -46,7 +46,7 @@ import * as _moment from "moment"; >_moment : Symbol(_moment, Decl(idx.ts, 0, 6)) declare module "moment" { ->"moment" : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) +>"moment" : Symbol("tests/cases/compiler/node_modules/moment/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(index.d.ts, 1, 16)) interface Moment { >Moment : Symbol(Moment, Decl(index.d.ts, 1, 26), Decl(idx.ts, 1, 25), Decl(idx.ts, 6, 34), Decl(index.d.ts, 2, 25)) @@ -57,7 +57,7 @@ declare module "moment" { } } declare module "moment-timezone" { ->"moment-timezone" : Symbol(moment, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(idx.ts, 5, 1)) +>"moment-timezone" : Symbol("tests/cases/compiler/node_modules/moment/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 41), Decl(idx.ts, 0, 34), Decl(idx.ts, 5, 1)) interface Moment { >Moment : Symbol(Moment, Decl(index.d.ts, 1, 26), Decl(idx.ts, 1, 25), Decl(idx.ts, 6, 34), Decl(index.d.ts, 2, 25)) diff --git a/tests/baselines/reference/moduleMemberMissingErrorIsRelative.errors.txt b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.errors.txt new file mode 100644 index 00000000000..526ea629f2a --- /dev/null +++ b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.errors.txt @@ -0,0 +1,9 @@ +tests/cases/compiler/folder/bar.ts(1,9): error TS2305: Module '"./foo"' has no exported member 'nosuch'. + + +==== tests/cases/compiler/folder/foo.ts (0 errors) ==== + export {}; +==== tests/cases/compiler/folder/bar.ts (1 errors) ==== + import {nosuch} from './foo'; + ~~~~~~ +!!! error TS2305: Module '"./foo"' has no exported member 'nosuch'. \ No newline at end of file diff --git a/tests/baselines/reference/moduleMemberMissingErrorIsRelative.js b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.js new file mode 100644 index 00000000000..5a081fb924a --- /dev/null +++ b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts] //// + +//// [foo.ts] +export {}; +//// [bar.ts] +import {nosuch} from './foo'; + +//// [foo.js] +"use strict"; +exports.__esModule = true; +//// [bar.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/moduleMemberMissingErrorIsRelative.symbols b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.symbols new file mode 100644 index 00000000000..8650f888c28 --- /dev/null +++ b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.symbols @@ -0,0 +1,6 @@ +=== tests/cases/compiler/folder/foo.ts === +export {}; +No type information for this code.=== tests/cases/compiler/folder/bar.ts === +import {nosuch} from './foo'; +>nosuch : Symbol(nosuch, Decl(bar.ts, 0, 8)) + diff --git a/tests/baselines/reference/moduleMemberMissingErrorIsRelative.types b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.types new file mode 100644 index 00000000000..ef779f2abdb --- /dev/null +++ b/tests/baselines/reference/moduleMemberMissingErrorIsRelative.types @@ -0,0 +1,6 @@ +=== tests/cases/compiler/folder/foo.ts === +export {}; +No type information for this code.=== tests/cases/compiler/folder/bar.ts === +import {nosuch} from './foo'; +>nosuch : any + diff --git a/tests/baselines/reference/module_augmentUninstantiatedModule.symbols b/tests/baselines/reference/module_augmentUninstantiatedModule.symbols index e75f6b5567c..7d07a1db707 100644 --- a/tests/baselines/reference/module_augmentUninstantiatedModule.symbols +++ b/tests/baselines/reference/module_augmentUninstantiatedModule.symbols @@ -3,10 +3,10 @@ declare module "foo" { >"foo" : Symbol("foo", Decl(module_augmentUninstantiatedModule.ts, 0, 0)) namespace M {} ->M : Symbol(M, Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) +>M : Symbol("tests/cases/compiler/module_augmentUninstantiatedModule.ts", Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) var M; ->M : Symbol(M, Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) +>M : Symbol("tests/cases/compiler/module_augmentUninstantiatedModule.ts", Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) export = M; >M : Symbol(M, Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6)) @@ -16,5 +16,5 @@ declare module "bar" { >"bar" : Symbol("bar", Decl(module_augmentUninstantiatedModule.ts, 4, 1)) module "foo" {} ->"foo" : Symbol(M, Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) +>"foo" : Symbol("tests/cases/compiler/module_augmentUninstantiatedModule.ts", Decl(module_augmentUninstantiatedModule.ts, 0, 22), Decl(module_augmentUninstantiatedModule.ts, 2, 6), Decl(module_augmentUninstantiatedModule.ts, 6, 22)) } diff --git a/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithExport.symbols b/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithExport.symbols index 07cb1012e8e..1cb26013b33 100644 --- a/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithExport.symbols +++ b/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithExport.symbols @@ -84,7 +84,7 @@ export class c_public { // private elements // Export - Error ambient modules allowed only in global declare module 'm' { ->'m' : Symbol('m', Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require2.ts, 0, 0)) +>'m' : Symbol("m", Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require2.ts, 0, 0)) export class c_private { >c_private : Symbol(c_private, Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require2.ts, 2, 20)) @@ -97,7 +97,7 @@ declare module 'm' { === tests/cases/compiler/privacyTopLevelAmbientExternalModuleImportWithExport_require3.ts === declare module 'm2' { ->'m2' : Symbol('m2', Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require3.ts, 0, 0)) +>'m2' : Symbol("m2", Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require3.ts, 0, 0)) export class c_private { >c_private : Symbol(c_private, Decl(privacyTopLevelAmbientExternalModuleImportWithExport_require3.ts, 0, 21)) diff --git a/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithoutExport.symbols b/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithoutExport.symbols index 9b10bef8008..2665eb60446 100644 --- a/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithoutExport.symbols +++ b/tests/baselines/reference/privacyTopLevelAmbientExternalModuleImportWithoutExport.symbols @@ -84,7 +84,7 @@ export class c_public { // private elements // Export - Error ambient modules allowed only in global declare module 'm' { ->'m' : Symbol('m', Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require2.ts, 0, 0)) +>'m' : Symbol("m", Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require2.ts, 0, 0)) export class c_private { >c_private : Symbol(c_private, Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require2.ts, 2, 20)) @@ -96,7 +96,7 @@ declare module 'm' { === tests/cases/compiler/privacyTopLevelAmbientExternalModuleImportWithoutExport_require3.ts === declare module 'm2' { ->'m2' : Symbol('m2', Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require3.ts, 0, 0)) +>'m2' : Symbol("m2", Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require3.ts, 0, 0)) export class c_private { >c_private : Symbol(c_private, Decl(privacyTopLevelAmbientExternalModuleImportWithoutExport_require3.ts, 0, 21)) diff --git a/tests/baselines/reference/propertyIdentityWithPrivacyMismatch.symbols b/tests/baselines/reference/propertyIdentityWithPrivacyMismatch.symbols index dff1ab6639a..c1a487bbb09 100644 --- a/tests/baselines/reference/propertyIdentityWithPrivacyMismatch.symbols +++ b/tests/baselines/reference/propertyIdentityWithPrivacyMismatch.symbols @@ -38,7 +38,7 @@ var y: Foo2; === tests/cases/compiler/propertyIdentityWithPrivacyMismatch_0.ts === declare module 'mod1' { ->'mod1' : Symbol('mod1', Decl(propertyIdentityWithPrivacyMismatch_0.ts, 0, 0)) +>'mod1' : Symbol("mod1", Decl(propertyIdentityWithPrivacyMismatch_0.ts, 0, 0)) class Foo { >Foo : Symbol(Foo, Decl(propertyIdentityWithPrivacyMismatch_0.ts, 0, 23)) @@ -48,7 +48,7 @@ declare module 'mod1' { } } declare module 'mod2' { ->'mod2' : Symbol('mod2', Decl(propertyIdentityWithPrivacyMismatch_0.ts, 4, 1)) +>'mod2' : Symbol("mod2", Decl(propertyIdentityWithPrivacyMismatch_0.ts, 4, 1)) class Foo { >Foo : Symbol(Foo, Decl(propertyIdentityWithPrivacyMismatch_0.ts, 5, 23)) diff --git a/tests/baselines/reference/quotedModuleNameMustBeAmbient.symbols b/tests/baselines/reference/quotedModuleNameMustBeAmbient.symbols index 667383b9286..27a8fd6ec70 100644 --- a/tests/baselines/reference/quotedModuleNameMustBeAmbient.symbols +++ b/tests/baselines/reference/quotedModuleNameMustBeAmbient.symbols @@ -1,7 +1,7 @@ === tests/cases/compiler/quotedModuleNameMustBeAmbient.ts === module 'M' {} ->'M' : Symbol('M', Decl(quotedModuleNameMustBeAmbient.ts, 0, 0)) +>'M' : Symbol("M", Decl(quotedModuleNameMustBeAmbient.ts, 0, 0)) declare module 'M2' {} ->'M2' : Symbol('M2', Decl(quotedModuleNameMustBeAmbient.ts, 0, 13)) +>'M2' : Symbol("M2", Decl(quotedModuleNameMustBeAmbient.ts, 0, 13)) diff --git a/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.symbols b/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.symbols index aecfd012973..7d17a6cb0a2 100644 --- a/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.symbols +++ b/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.symbols @@ -1,6 +1,6 @@ === tests/cases/compiler/node_modules/react/index.d.ts === declare namespace React { ->React : Symbol(React, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 0)) +>React : Symbol("tests/cases/compiler/node_modules/react/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 0)) export interface DetailedHTMLProps {} >DetailedHTMLProps : Symbol(DetailedHTMLProps, Decl(index.d.ts, 0, 25)) @@ -20,7 +20,7 @@ export as namespace React; === tests/cases/compiler/node_modules/create-emotion-styled/types/react/index.d.ts === /// declare module 'react' { // augment ->'react' : Symbol(React, Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 0)) +>'react' : Symbol("tests/cases/compiler/node_modules/react/index.d.ts", Decl(index.d.ts, 0, 0), Decl(index.d.ts, 0, 0)) interface HTMLAttributes { >HTMLAttributes : Symbol(HTMLAttributes, Decl(index.d.ts, 1, 47), Decl(index.d.ts, 1, 24)) diff --git a/tests/baselines/reference/spellingSuggestionModule.symbols b/tests/baselines/reference/spellingSuggestionModule.symbols index 3dc64cd2ec7..2997c80ba4b 100644 --- a/tests/baselines/reference/spellingSuggestionModule.symbols +++ b/tests/baselines/reference/spellingSuggestionModule.symbols @@ -6,7 +6,7 @@ declare module "foobar" { export const x: number; } foobar; declare module 'barfoo' { export const x: number; } ->'barfoo' : Symbol('barfoo', Decl(spellingSuggestionModule.ts, 1, 7)) +>'barfoo' : Symbol("barfoo", Decl(spellingSuggestionModule.ts, 1, 7)) >x : Symbol(x, Decl(spellingSuggestionModule.ts, 3, 38)) barfoo; diff --git a/tests/baselines/reference/tsxDynamicTagName5.symbols b/tests/baselines/reference/tsxDynamicTagName5.symbols index f5782923945..fc9b308bea6 100644 --- a/tests/baselines/reference/tsxDynamicTagName5.symbols +++ b/tests/baselines/reference/tsxDynamicTagName5.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) class Component { } >Component : Symbol(Component, Decl(react.d.ts, 0, 24)) diff --git a/tests/baselines/reference/tsxDynamicTagName7.symbols b/tests/baselines/reference/tsxDynamicTagName7.symbols index 405887092d7..8be4d7e1577 100644 --- a/tests/baselines/reference/tsxDynamicTagName7.symbols +++ b/tests/baselines/reference/tsxDynamicTagName7.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) class Component { } >Component : Symbol(Component, Decl(react.d.ts, 0, 24)) diff --git a/tests/baselines/reference/tsxDynamicTagName8.symbols b/tests/baselines/reference/tsxDynamicTagName8.symbols index 937c4a2de6f..09ab1a43e79 100644 --- a/tests/baselines/reference/tsxDynamicTagName8.symbols +++ b/tests/baselines/reference/tsxDynamicTagName8.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) class Component { } >Component : Symbol(Component, Decl(react.d.ts, 0, 24)) diff --git a/tests/baselines/reference/tsxDynamicTagName9.symbols b/tests/baselines/reference/tsxDynamicTagName9.symbols index 2a8dfb2de8d..a703e383282 100644 --- a/tests/baselines/reference/tsxDynamicTagName9.symbols +++ b/tests/baselines/reference/tsxDynamicTagName9.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) class Component { } >Component : Symbol(Component, Decl(react.d.ts, 0, 24)) diff --git a/tests/baselines/reference/tsxElementResolution17.symbols b/tests/baselines/reference/tsxElementResolution17.symbols index 2a591207f04..a807f8d06c3 100644 --- a/tests/baselines/reference/tsxElementResolution17.symbols +++ b/tests/baselines/reference/tsxElementResolution17.symbols @@ -24,7 +24,7 @@ declare module JSX { } declare module 'elements1' { ->'elements1' : Symbol('elements1', Decl(file.tsx, 3, 1)) +>'elements1' : Symbol("elements1", Decl(file.tsx, 3, 1)) class MyElement { >MyElement : Symbol(MyElement, Decl(file.tsx, 5, 28)) @@ -33,7 +33,7 @@ declare module 'elements1' { } declare module 'elements2' { ->'elements2' : Symbol('elements2', Decl(file.tsx, 9, 1)) +>'elements2' : Symbol("elements2", Decl(file.tsx, 9, 1)) class MyElement { >MyElement : Symbol(MyElement, Decl(file.tsx, 11, 28)) diff --git a/tests/baselines/reference/tsxExternalModuleEmit1.symbols b/tests/baselines/reference/tsxExternalModuleEmit1.symbols index a70f1f70781..01a86b1f572 100644 --- a/tests/baselines/reference/tsxExternalModuleEmit1.symbols +++ b/tests/baselines/reference/tsxExternalModuleEmit1.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) class Component { } >Component : Symbol(Component, Decl(react.d.ts, 0, 24)) diff --git a/tests/baselines/reference/tsxExternalModuleEmit2.symbols b/tests/baselines/reference/tsxExternalModuleEmit2.symbols index 5d3a586ee42..38bc43800c2 100644 --- a/tests/baselines/reference/tsxExternalModuleEmit2.symbols +++ b/tests/baselines/reference/tsxExternalModuleEmit2.symbols @@ -1,6 +1,6 @@ === tests/cases/conformance/jsx/modules.d.ts === declare module 'mod' { ->'mod' : Symbol('mod', Decl(modules.d.ts, 0, 0)) +>'mod' : Symbol("mod", Decl(modules.d.ts, 0, 0)) var y: any; >y : Symbol(y, Decl(modules.d.ts, 1, 5)) diff --git a/tests/baselines/reference/tsxPreserveEmit1.symbols b/tests/baselines/reference/tsxPreserveEmit1.symbols index 98ffd3282d5..41da78ba004 100644 --- a/tests/baselines/reference/tsxPreserveEmit1.symbols +++ b/tests/baselines/reference/tsxPreserveEmit1.symbols @@ -33,7 +33,7 @@ module M { === tests/cases/conformance/jsx/react.d.ts === declare module 'react' { ->'react' : Symbol('react', Decl(react.d.ts, 0, 0)) +>'react' : Symbol("react", Decl(react.d.ts, 0, 0)) var x: any; >x : Symbol(x, Decl(react.d.ts, 1, 4)) @@ -52,7 +52,7 @@ declare module ReactRouter { >Thing : Symbol(Thing, Decl(react.d.ts, 6, 16)) } declare module 'react-router' { ->'react-router' : Symbol('react-router', Decl(react.d.ts, 8, 1)) +>'react-router' : Symbol("react-router", Decl(react.d.ts, 8, 1)) export = ReactRouter; >ReactRouter : Symbol(ReactRouter, Decl(react.d.ts, 3, 1)) diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt index 540dd917fa0..a6373dbda56 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index"' has no exported member 'fa'. +tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"./node_modules/ext/ts3.1"' has no exported member 'fa'. ==== tests/cases/conformance/declarationEmit/tsconfig.json (0 errors) ==== @@ -30,7 +30,7 @@ tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"te ==== tests/cases/conformance/declarationEmit/main.ts (1 errors) ==== import { fa } from "ext"; ~~ -!!! error TS2305: Module '"tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index"' has no exported member 'fa'. +!!! error TS2305: Module '"./node_modules/ext/ts3.1"' has no exported member 'fa'. import { fb } from "ext/other"; export const va = fa(); diff --git a/tests/baselines/reference/umd-augmentation-3.symbols b/tests/baselines/reference/umd-augmentation-3.symbols index 606c7cd2398..9ddd303bfc7 100644 --- a/tests/baselines/reference/umd-augmentation-3.symbols +++ b/tests/baselines/reference/umd-augmentation-3.symbols @@ -44,7 +44,7 @@ export = M2D; >M2D : Symbol(M2D, Decl(index.d.ts, 2, 13)) declare namespace M2D { ->M2D : Symbol(M2D, Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) +>M2D : Symbol("tests/cases/conformance/externalModules/node_modules/math2d/index.d.ts", Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) interface Point { >Point : Symbol(Point, Decl(index.d.ts, 4, 23)) diff --git a/tests/baselines/reference/umd-augmentation-4.symbols b/tests/baselines/reference/umd-augmentation-4.symbols index 90341d679f0..4a2e8090e9f 100644 --- a/tests/baselines/reference/umd-augmentation-4.symbols +++ b/tests/baselines/reference/umd-augmentation-4.symbols @@ -42,7 +42,7 @@ export = M2D; >M2D : Symbol(M2D, Decl(index.d.ts, 2, 13)) declare namespace M2D { ->M2D : Symbol(M2D, Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) +>M2D : Symbol("tests/cases/conformance/externalModules/node_modules/math2d/index.d.ts", Decl(index.d.ts, 2, 13), Decl(math2d-augment.d.ts, 0, 33)) interface Point { >Point : Symbol(Point, Decl(index.d.ts, 4, 23)) diff --git a/tests/baselines/reference/unclosedExportClause01.errors.txt b/tests/baselines/reference/unclosedExportClause01.errors.txt index 9c6cae88ba1..4cc6363bb73 100644 --- a/tests/baselines/reference/unclosedExportClause01.errors.txt +++ b/tests/baselines/reference/unclosedExportClause01.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/t2.ts(1,13): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t2.ts(1,13): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t2.ts(1,18): error TS1005: ',' expected. -tests/cases/compiler/t3.ts(1,10): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t3.ts(1,10): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t3.ts(1,15): error TS1005: ',' expected. tests/cases/compiler/t4.ts(1,17): error TS1005: ',' expected. -tests/cases/compiler/t4.ts(1,17): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t4.ts(1,17): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t4.ts(1,22): error TS1005: ',' expected. -tests/cases/compiler/t5.ts(1,18): error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +tests/cases/compiler/t5.ts(1,18): error TS2305: Module '"./t1"' has no exported member 'from'. tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. @@ -15,14 +15,14 @@ tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. ==== tests/cases/compiler/t2.ts (2 errors) ==== export { x, from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. ==== tests/cases/compiler/t3.ts (2 errors) ==== export { from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. @@ -31,13 +31,13 @@ tests/cases/compiler/t5.ts(1,23): error TS1005: ',' expected. ~~~~ !!! error TS1005: ',' expected. ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. ==== tests/cases/compiler/t5.ts (2 errors) ==== export { x as a, from "./t1" ~~~~ -!!! error TS2305: Module '"tests/cases/compiler/t1"' has no exported member 'from'. +!!! error TS2305: Module '"./t1"' has no exported member 'from'. ~~~~~~ !!! error TS1005: ',' expected. \ No newline at end of file diff --git a/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts b/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts new file mode 100644 index 00000000000..8cb8e1d2948 --- /dev/null +++ b/tests/cases/compiler/moduleMemberMissingErrorIsRelative.ts @@ -0,0 +1,4 @@ +// @filename: folder/foo.ts +export {}; +// @filename: folder/bar.ts +import {nosuch} from './foo'; \ No newline at end of file From dd9b8cab34a3e389e924d768eb656cf50656f582 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 8 Oct 2018 14:42:51 -0700 Subject: [PATCH 024/262] Have scanJsDocToken scan keywords (#27162) * Have scanJsDocToken scan keywords * Update API --- src/compiler/parser.ts | 19 +- src/compiler/scanner.ts | 166 +++++++++--------- src/compiler/types.ts | 79 ++++++++- ...ocComments.parsesCorrectly.@link tags.json | 4 +- ...cComments.parsesCorrectly.templateTag.json | 4 +- ...Comments.parsesCorrectly.templateTag2.json | 4 +- ...Comments.parsesCorrectly.templateTag3.json | 4 +- ...Comments.parsesCorrectly.templateTag4.json | 4 +- ...Comments.parsesCorrectly.templateTag5.json | 4 +- ...Comments.parsesCorrectly.templateTag6.json | 4 +- .../reference/api/tsserverlibrary.d.ts | 3 +- tests/baselines/reference/api/typescript.d.ts | 3 +- .../jsdocUnexpectedCharacter.symbols | 5 + .../reference/jsdocUnexpectedCharacter.types | 6 + .../reference/paramTagWrapping.errors.txt | 8 +- .../compiler/jsdocUnexpectedCharacter.ts | 7 + 16 files changed, 213 insertions(+), 111 deletions(-) create mode 100644 tests/baselines/reference/jsdocUnexpectedCharacter.symbols create mode 100644 tests/baselines/reference/jsdocUnexpectedCharacter.types create mode 100644 tests/cases/compiler/jsdocUnexpectedCharacter.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 115031bae7c..056edccdbd2 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6512,7 +6512,7 @@ namespace ts { } } - function skipWhitespaceOrAsterisk(next: () => void): void { + function skipWhitespaceOrAsterisk(): void { if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -6527,7 +6527,7 @@ namespace ts { else if (token() === SyntaxKind.AsteriskToken) { precedingLineBreak = false; } - next(); + nextJSDocToken(); } } @@ -6537,9 +6537,8 @@ namespace ts { atToken.end = scanner.getTextPos(); nextJSDocToken(); - // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` - const tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); - skipWhitespaceOrAsterisk(nextToken); + const tagName = parseJSDocIdentifierName(/*message*/ undefined); + skipWhitespaceOrAsterisk(); let tag: JSDocTag | undefined; switch (tagName.escapedText) { @@ -6683,7 +6682,7 @@ namespace ts { } function tryParseTypeExpression(): JSDocTypeExpression | undefined { - skipWhitespaceOrAsterisk(nextJSDocToken); + skipWhitespaceOrAsterisk(); return token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; } @@ -6723,7 +6722,7 @@ namespace ts { function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(nextJSDocToken); + skipWhitespaceOrAsterisk(); const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); skipWhitespace(); @@ -6857,7 +6856,7 @@ namespace ts { function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag { const typeExpression = tryParseTypeExpression(); - skipWhitespaceOrAsterisk(nextJSDocToken); + skipWhitespaceOrAsterisk(); const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, atToken.pos); typedefTag.atToken = atToken; @@ -7110,7 +7109,7 @@ namespace ts { return entity; } - function parseJSDocIdentifierName(message?: DiagnosticMessage, next: () => void = nextJSDocToken): Identifier { + function parseJSDocIdentifierName(message?: DiagnosticMessage): Identifier { if (!tokenIsIdentifierOrKeyword(token())) { return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected); } @@ -7121,7 +7120,7 @@ namespace ts { result.escapedText = escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - next(); + nextJSDocToken(); return result; } } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index b339220c38e..1a5c4336b63 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -60,81 +60,87 @@ namespace ts { tryScan(callback: () => T): T; } - const textToToken = createMapFromTemplate({ - "abstract": SyntaxKind.AbstractKeyword, - "any": SyntaxKind.AnyKeyword, - "as": SyntaxKind.AsKeyword, - "boolean": SyntaxKind.BooleanKeyword, - "break": SyntaxKind.BreakKeyword, - "case": SyntaxKind.CaseKeyword, - "catch": SyntaxKind.CatchKeyword, - "class": SyntaxKind.ClassKeyword, - "continue": SyntaxKind.ContinueKeyword, - "const": SyntaxKind.ConstKeyword, - "constructor": SyntaxKind.ConstructorKeyword, - "debugger": SyntaxKind.DebuggerKeyword, - "declare": SyntaxKind.DeclareKeyword, - "default": SyntaxKind.DefaultKeyword, - "delete": SyntaxKind.DeleteKeyword, - "do": SyntaxKind.DoKeyword, - "else": SyntaxKind.ElseKeyword, - "enum": SyntaxKind.EnumKeyword, - "export": SyntaxKind.ExportKeyword, - "extends": SyntaxKind.ExtendsKeyword, - "false": SyntaxKind.FalseKeyword, - "finally": SyntaxKind.FinallyKeyword, - "for": SyntaxKind.ForKeyword, - "from": SyntaxKind.FromKeyword, - "function": SyntaxKind.FunctionKeyword, - "get": SyntaxKind.GetKeyword, - "if": SyntaxKind.IfKeyword, - "implements": SyntaxKind.ImplementsKeyword, - "import": SyntaxKind.ImportKeyword, - "in": SyntaxKind.InKeyword, - "infer": SyntaxKind.InferKeyword, - "instanceof": SyntaxKind.InstanceOfKeyword, - "interface": SyntaxKind.InterfaceKeyword, - "is": SyntaxKind.IsKeyword, - "keyof": SyntaxKind.KeyOfKeyword, - "let": SyntaxKind.LetKeyword, - "module": SyntaxKind.ModuleKeyword, - "namespace": SyntaxKind.NamespaceKeyword, - "never": SyntaxKind.NeverKeyword, - "new": SyntaxKind.NewKeyword, - "null": SyntaxKind.NullKeyword, - "number": SyntaxKind.NumberKeyword, - "object": SyntaxKind.ObjectKeyword, - "package": SyntaxKind.PackageKeyword, - "private": SyntaxKind.PrivateKeyword, - "protected": SyntaxKind.ProtectedKeyword, - "public": SyntaxKind.PublicKeyword, - "readonly": SyntaxKind.ReadonlyKeyword, - "require": SyntaxKind.RequireKeyword, - "global": SyntaxKind.GlobalKeyword, - "return": SyntaxKind.ReturnKeyword, - "set": SyntaxKind.SetKeyword, - "static": SyntaxKind.StaticKeyword, - "string": SyntaxKind.StringKeyword, - "super": SyntaxKind.SuperKeyword, - "switch": SyntaxKind.SwitchKeyword, - "symbol": SyntaxKind.SymbolKeyword, - "this": SyntaxKind.ThisKeyword, - "throw": SyntaxKind.ThrowKeyword, - "true": SyntaxKind.TrueKeyword, - "try": SyntaxKind.TryKeyword, - "type": SyntaxKind.TypeKeyword, - "typeof": SyntaxKind.TypeOfKeyword, - "undefined": SyntaxKind.UndefinedKeyword, - "unique": SyntaxKind.UniqueKeyword, - "unknown": SyntaxKind.UnknownKeyword, - "var": SyntaxKind.VarKeyword, - "void": SyntaxKind.VoidKeyword, - "while": SyntaxKind.WhileKeyword, - "with": SyntaxKind.WithKeyword, - "yield": SyntaxKind.YieldKeyword, - "async": SyntaxKind.AsyncKeyword, - "await": SyntaxKind.AwaitKeyword, - "of": SyntaxKind.OfKeyword, + const textToKeywordObj: MapLike = { + abstract: SyntaxKind.AbstractKeyword, + any: SyntaxKind.AnyKeyword, + as: SyntaxKind.AsKeyword, + boolean: SyntaxKind.BooleanKeyword, + break: SyntaxKind.BreakKeyword, + case: SyntaxKind.CaseKeyword, + catch: SyntaxKind.CatchKeyword, + class: SyntaxKind.ClassKeyword, + continue: SyntaxKind.ContinueKeyword, + const: SyntaxKind.ConstKeyword, + ["" + "constructor"]: SyntaxKind.ConstructorKeyword, + debugger: SyntaxKind.DebuggerKeyword, + declare: SyntaxKind.DeclareKeyword, + default: SyntaxKind.DefaultKeyword, + delete: SyntaxKind.DeleteKeyword, + do: SyntaxKind.DoKeyword, + else: SyntaxKind.ElseKeyword, + enum: SyntaxKind.EnumKeyword, + export: SyntaxKind.ExportKeyword, + extends: SyntaxKind.ExtendsKeyword, + false: SyntaxKind.FalseKeyword, + finally: SyntaxKind.FinallyKeyword, + for: SyntaxKind.ForKeyword, + from: SyntaxKind.FromKeyword, + function: SyntaxKind.FunctionKeyword, + get: SyntaxKind.GetKeyword, + if: SyntaxKind.IfKeyword, + implements: SyntaxKind.ImplementsKeyword, + import: SyntaxKind.ImportKeyword, + in: SyntaxKind.InKeyword, + infer: SyntaxKind.InferKeyword, + instanceof: SyntaxKind.InstanceOfKeyword, + interface: SyntaxKind.InterfaceKeyword, + is: SyntaxKind.IsKeyword, + keyof: SyntaxKind.KeyOfKeyword, + let: SyntaxKind.LetKeyword, + module: SyntaxKind.ModuleKeyword, + namespace: SyntaxKind.NamespaceKeyword, + never: SyntaxKind.NeverKeyword, + new: SyntaxKind.NewKeyword, + null: SyntaxKind.NullKeyword, + number: SyntaxKind.NumberKeyword, + object: SyntaxKind.ObjectKeyword, + package: SyntaxKind.PackageKeyword, + private: SyntaxKind.PrivateKeyword, + protected: SyntaxKind.ProtectedKeyword, + public: SyntaxKind.PublicKeyword, + readonly: SyntaxKind.ReadonlyKeyword, + require: SyntaxKind.RequireKeyword, + global: SyntaxKind.GlobalKeyword, + return: SyntaxKind.ReturnKeyword, + set: SyntaxKind.SetKeyword, + static: SyntaxKind.StaticKeyword, + string: SyntaxKind.StringKeyword, + super: SyntaxKind.SuperKeyword, + switch: SyntaxKind.SwitchKeyword, + symbol: SyntaxKind.SymbolKeyword, + this: SyntaxKind.ThisKeyword, + throw: SyntaxKind.ThrowKeyword, + true: SyntaxKind.TrueKeyword, + try: SyntaxKind.TryKeyword, + type: SyntaxKind.TypeKeyword, + typeof: SyntaxKind.TypeOfKeyword, + undefined: SyntaxKind.UndefinedKeyword, + unique: SyntaxKind.UniqueKeyword, + unknown: SyntaxKind.UnknownKeyword, + var: SyntaxKind.VarKeyword, + void: SyntaxKind.VoidKeyword, + while: SyntaxKind.WhileKeyword, + with: SyntaxKind.WithKeyword, + yield: SyntaxKind.YieldKeyword, + async: SyntaxKind.AsyncKeyword, + await: SyntaxKind.AwaitKeyword, + of: SyntaxKind.OfKeyword, + }; + + const textToKeyword = createMapFromTemplate(textToKeywordObj); + + const textToToken = createMapFromTemplate({ + ...textToKeywordObj, "{": SyntaxKind.OpenBraceToken, "}": SyntaxKind.CloseBraceToken, "(": SyntaxKind.OpenParenToken, @@ -1288,15 +1294,15 @@ namespace ts { return result; } - function getIdentifierToken(): SyntaxKind { + function getIdentifierToken(): SyntaxKind.Identifier | KeywordSyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter const len = tokenValue.length; if (len >= 2 && len <= 11) { const ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z) { - token = textToToken.get(tokenValue)!; - if (token !== undefined) { - return token; + const keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -2016,7 +2022,7 @@ namespace ts { pos++; } tokenValue = text.substring(tokenPos, pos); - return token = SyntaxKind.Identifier; + return token = getIdentifierToken(); } else { return token = SyntaxKind.Unknown; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c8f9c15aa84..3bd103579f1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -24,7 +24,84 @@ namespace ts { | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral - | SyntaxKind.Unknown; + | SyntaxKind.Unknown + | KeywordSyntaxKind; + + export type KeywordSyntaxKind = + | SyntaxKind.AbstractKeyword + | SyntaxKind.AnyKeyword + | SyntaxKind.AsKeyword + | SyntaxKind.BooleanKeyword + | SyntaxKind.BreakKeyword + | SyntaxKind.CaseKeyword + | SyntaxKind.CatchKeyword + | SyntaxKind.ClassKeyword + | SyntaxKind.ContinueKeyword + | SyntaxKind.ConstKeyword + | SyntaxKind.ConstructorKeyword + | SyntaxKind.DebuggerKeyword + | SyntaxKind.DeclareKeyword + | SyntaxKind.DefaultKeyword + | SyntaxKind.DeleteKeyword + | SyntaxKind.DoKeyword + | SyntaxKind.ElseKeyword + | SyntaxKind.EnumKeyword + | SyntaxKind.ExportKeyword + | SyntaxKind.ExtendsKeyword + | SyntaxKind.FalseKeyword + | SyntaxKind.FinallyKeyword + | SyntaxKind.ForKeyword + | SyntaxKind.FromKeyword + | SyntaxKind.FunctionKeyword + | SyntaxKind.GetKeyword + | SyntaxKind.IfKeyword + | SyntaxKind.ImplementsKeyword + | SyntaxKind.ImportKeyword + | SyntaxKind.InKeyword + | SyntaxKind.InferKeyword + | SyntaxKind.InstanceOfKeyword + | SyntaxKind.InterfaceKeyword + | SyntaxKind.IsKeyword + | SyntaxKind.KeyOfKeyword + | SyntaxKind.LetKeyword + | SyntaxKind.ModuleKeyword + | SyntaxKind.NamespaceKeyword + | SyntaxKind.NeverKeyword + | SyntaxKind.NewKeyword + | SyntaxKind.NullKeyword + | SyntaxKind.NumberKeyword + | SyntaxKind.ObjectKeyword + | SyntaxKind.PackageKeyword + | SyntaxKind.PrivateKeyword + | SyntaxKind.ProtectedKeyword + | SyntaxKind.PublicKeyword + | SyntaxKind.ReadonlyKeyword + | SyntaxKind.RequireKeyword + | SyntaxKind.GlobalKeyword + | SyntaxKind.ReturnKeyword + | SyntaxKind.SetKeyword + | SyntaxKind.StaticKeyword + | SyntaxKind.StringKeyword + | SyntaxKind.SuperKeyword + | SyntaxKind.SwitchKeyword + | SyntaxKind.SymbolKeyword + | SyntaxKind.ThisKeyword + | SyntaxKind.ThrowKeyword + | SyntaxKind.TrueKeyword + | SyntaxKind.TryKeyword + | SyntaxKind.TypeKeyword + | SyntaxKind.TypeOfKeyword + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword + | SyntaxKind.WithKeyword + | SyntaxKind.YieldKeyword + | SyntaxKind.AsyncKeyword + | SyntaxKind.AwaitKeyword + | SyntaxKind.OfKeyword; export type JsxTokenSyntaxKind = | SyntaxKind.LessThanSlashToken diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json index 2ea60ed3e42..c694d240371 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json @@ -6,7 +6,7 @@ "0": { "kind": "JSDocTag", "pos": 63, - "end": 67, + "end": 68, "atToken": { "kind": "AtToken", "pos": 63, @@ -22,7 +22,7 @@ }, "length": 1, "pos": 63, - "end": 67 + "end": 68 }, "comment": "{@link first link}\nInside {@link link text} thing" } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index cd453fce8c5..4d16157d91d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -31,7 +31,7 @@ } }, "length": 1, - "pos": 17, + "pos": 18, "end": 19 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index bfc59a6a3bb..3f5f2a54ec7 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 17, + "pos": 18, "end": 21 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index e6ad0c0d0f3..193c5c0eb01 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 17, + "pos": 18, "end": 22 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index e6ad0c0d0f3..193c5c0eb01 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 17, + "pos": 18, "end": 22 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index f09001e97e2..fca64bcb430 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 17, + "pos": 18, "end": 23 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 566a03b96ea..90158499b17 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 17, + "pos": 18, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 17, + "pos": 18, "end": 24 }, "comment": "Description of type parameters." diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 1971cbbc754..0120e49f0a5 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index d6bd508999d..fdd11aa3484 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, diff --git a/tests/baselines/reference/jsdocUnexpectedCharacter.symbols b/tests/baselines/reference/jsdocUnexpectedCharacter.symbols new file mode 100644 index 00000000000..5a4379ebb8c --- /dev/null +++ b/tests/baselines/reference/jsdocUnexpectedCharacter.symbols @@ -0,0 +1,5 @@ +=== /a.js === +/** @x # */ +var UI = {}; +>UI : Symbol(UI, Decl(a.js, 1, 3)) + diff --git a/tests/baselines/reference/jsdocUnexpectedCharacter.types b/tests/baselines/reference/jsdocUnexpectedCharacter.types new file mode 100644 index 00000000000..897e534894d --- /dev/null +++ b/tests/baselines/reference/jsdocUnexpectedCharacter.types @@ -0,0 +1,6 @@ +=== /a.js === +/** @x # */ +var UI = {}; +>UI : {} +>{} : {} + diff --git a/tests/baselines/reference/paramTagWrapping.errors.txt b/tests/baselines/reference/paramTagWrapping.errors.txt index 3263443dbac..48100f0e746 100644 --- a/tests/baselines/reference/paramTagWrapping.errors.txt +++ b/tests/baselines/reference/paramTagWrapping.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/jsdoc/bad.js(2,10): error TS1003: Identifier expected. -tests/cases/conformance/jsdoc/bad.js(2,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. +tests/cases/conformance/jsdoc/bad.js(2,11): error TS1003: Identifier expected. +tests/cases/conformance/jsdoc/bad.js(2,11): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(5,4): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(5,4): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(6,19): error TS1003: Identifier expected. @@ -27,9 +27,9 @@ tests/cases/conformance/jsdoc/bad.js(9,20): error TS7006: Parameter 'z' implicit ==== tests/cases/conformance/jsdoc/bad.js (9 errors) ==== /** * @param * - + !!! error TS1003: Identifier expected. - + !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * {number} x Arg x. * @param {number} diff --git a/tests/cases/compiler/jsdocUnexpectedCharacter.ts b/tests/cases/compiler/jsdocUnexpectedCharacter.ts new file mode 100644 index 00000000000..ef7a2f78c99 --- /dev/null +++ b/tests/cases/compiler/jsdocUnexpectedCharacter.ts @@ -0,0 +1,7 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: /a.js +/** @x # */ +var UI = {}; From 03a3978d65b1dea3d2ea2356edf775f6ec2e5e31 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 8 Oct 2018 15:56:39 -0700 Subject: [PATCH 025/262] Use ambient modules as references to keep track of reporting and usage of modules correctly Fixes #27585 --- src/compiler/builderState.ts | 31 +++++++++++++++++++++ src/testRunner/unittests/tscWatchMode.ts | 35 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index f5f2538a60b..1689733fac6 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -148,8 +148,39 @@ namespace ts.BuilderState { }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + const checker = program.getTypeChecker(); + for (const moduleName of sourceFile.moduleAugmentations) { + if (!isStringLiteral(moduleName)) { continue; } + const symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { continue; } + + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + + // From ambient modules + for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } + return referencedFiles; + function addReferenceFromAmbientModule(symbol: Symbol) { + // Add any file other than our own as reference + for (const declaration of symbol.declarations) { + const declarationSourceFile = getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } + function addReferencedFile(referencedPath: Path) { if (!referencedFiles) { referencedFiles = createMap(); diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index c4b7d6adf44..7678bfe0625 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1386,6 +1386,41 @@ foo().hello` // File a need not be rewritten assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); }); + + it("updates errors when ambient modules of program changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `declare module 'a' { + type foo = number; +}` + }; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: "{}" + }; + const files = [aFile, config, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + + // Create bts with same file contents + const bTsPath = `${currentDirectory}/b.ts`; + host.writeFile(bTsPath, aFile.content); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, "b.ts", libFile.path]); + checkOutputErrorsIncremental(host, [ + "a.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n", + "b.ts(2,8): error TS2300: Duplicate identifier 'foo'.\n" + ]); + + // Delete bTs + host.deleteFile(bTsPath); + host.runQueuedTimeoutCallbacks(); + checkProgramActualFiles(watch(), [aFile.path, libFile.path]); + checkOutputErrorsIncremental(host, emptyArray); + }); }); describe("tsc-watch emit with outFile or out setting", () => { From 2e5a39a3cebfcd4a712bd1a72ab9962acbe75d3d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 8 Oct 2018 16:35:03 -0700 Subject: [PATCH 026/262] Error when indexing out of bounds in a tuple or union of tuples --- src/compiler/checker.ts | 14 ++++++-------- src/compiler/diagnosticMessages.json | 4 ---- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3b2c4efc662..33d23bd11ee 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9312,7 +9312,12 @@ namespace ts { propType; } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { - return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); + const restType = mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); + if (restType === undefinedType && accessNode) { + const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + return restType; } } if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) { @@ -18964,13 +18969,6 @@ namespace ts { error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - if (isTupleType(objectType) && !objectType.target.hasRestElement && isNumericLiteral(indexExpression)) { - const index = +indexExpression.text; - const length = getTypeReferenceArity(objectType); - if (index >= length) { - error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, length); - } - } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ce1ccf17145..01d95bc2b85 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2481,10 +2481,6 @@ "category": "Error", "code": 2732 }, - "Index '{0}' is out-of-bounds in tuple of length {1}.": { - "category": "Error", - "code": 2733 - }, "It is highly likely that you are missing a semicolon.": { "category": "Error", "code": 2734 From 209f30c2f13956cc051d6dfc631a66898a559d36 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 8 Oct 2018 16:46:45 -0700 Subject: [PATCH 027/262] Update test --- .../cases/conformance/types/keyof/keyofAndIndexedAccess.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts index 4a69af307af..cf05bdfed81 100644 --- a/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts +++ b/tests/cases/conformance/types/keyof/keyofAndIndexedAccess.ts @@ -63,12 +63,11 @@ type Q21 = Shape[WIDTH_OR_HEIGHT]; // number type Q30 = [string, number][0]; // string type Q31 = [string, number][1]; // number -type Q32 = [string, number][2]; // string | number +type Q32 = [string, number][number]; // string | number type Q33 = [string, number][E.A]; // string type Q34 = [string, number][E.B]; // number -type Q35 = [string, number][E.C]; // string | number -type Q36 = [string, number]["0"]; // string -type Q37 = [string, number]["1"]; // string +type Q35 = [string, number]["0"]; // string +type Q36 = [string, number]["1"]; // string type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" From 840214f1eae0138674c3fd2bf8fac20f1e3bab78 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 8 Oct 2018 16:47:10 -0700 Subject: [PATCH 028/262] Accept new baselines --- .../bestCommonTypeOfTuple.errors.txt | 16 +- .../bestCommonTypeOfTuple2.errors.txt | 20 +- .../reference/castingTuple.errors.txt | 4 +- .../emptyTuplesTypeAssertion01.errors.txt | 4 +- .../emptyTuplesTypeAssertion02.errors.txt | 4 +- .../genericCallWithTupleType.errors.txt | 12 +- .../reference/indexerWithTuple.errors.txt | 16 +- .../reference/keyofAndIndexedAccess.js | 14 +- .../reference/keyofAndIndexedAccess.symbols | 2525 ++++++++--------- .../reference/keyofAndIndexedAccess.types | 16 +- .../reference/tupleLengthCheck.errors.txt | 8 +- .../baselines/reference/tupleTypes.errors.txt | 8 +- .../reference/unionsOfTupleTypes1.errors.txt | 15 +- 13 files changed, 1330 insertions(+), 1332 deletions(-) diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt index 2c57099c3e8..e3c5dcc7986 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2733: Index '3' is out-of-bounds in tuple of length 3. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2339: Property '2' does not exist on type '[E1, E2]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2339: Property '2' does not exist on type '[number, any]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2339: Property '3' does not exist on type '[E1, E2, number]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts (4 errors) ==== @@ -28,13 +28,13 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT t4 = [E1.one, E2.two, 20]; var e1 = t1[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. var e2 = t2[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[E1, E2]'. var e3 = t3[2]; // any ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, any]'. var e4 = t4[3]; // number ~ -!!! error TS2733: Index '3' is out-of-bounds in tuple of length 3. \ No newline at end of file +!!! error TS2339: Property '3' does not exist on type '[E1, E2, number]'. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt index 80f40c74a07..d2fd301e131 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2339: Property '4' does not exist on type '[C, base]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2339: Property '4' does not exist on type '[C, D]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2339: Property '4' does not exist on type '[C1, D1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2339: Property '2' does not exist on type '[base1, C1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2339: Property '2' does not exist on type '[C1, F]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts (5 errors) ==== @@ -24,17 +24,17 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT var e11 = t1[4]; // base ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, base]'. var e21 = t2[4]; // {} ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, D]'. var e31 = t3[4]; // C1 ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C1, D1]'. var e41 = t4[2]; // base1 ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[base1, C1]'. var e51 = t5[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[C1, F]'. \ No newline at end of file diff --git a/tests/baselines/reference/castingTuple.errors.txt b/tests/baselines/reference/castingTuple.errors.txt index e8bc9133a8a..08e2b32a858 100644 --- a/tests/baselines/reference/castingTuple.errors.txt +++ b/tests/baselines/reference/castingTuple.errors.txt @@ -6,7 +6,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(14,15): error TS2352: Conver tests/cases/conformance/types/tuple/castingTuple.ts(15,14): error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. tests/cases/conformance/types/tuple/castingTuple.ts(18,21): error TS2352: Conversion of type '[C, D]' to type '[C, D, A]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property '2' is missing in type '[C, D]'. -tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2733: Index '5' is out-of-bounds in tuple of length 3. +tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2339: Property '5' does not exist on type '[C, D, A]'. tests/cases/conformance/types/tuple/castingTuple.ts(30,10): error TS2352: Conversion of type '[number, string]' to type '[number, number]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'string' is not comparable to type 'number'. tests/cases/conformance/types/tuple/castingTuple.ts(31,10): error TS2352: Conversion of type '[C, D]' to type '[A, I]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. @@ -50,7 +50,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot var eleFromCDA1 = classCDATuple[2]; // A var eleFromCDA2 = classCDATuple[5]; // C | D | A ~ -!!! error TS2733: Index '5' is out-of-bounds in tuple of length 3. +!!! error TS2339: Property '5' does not exist on type '[C, D, A]'. var t10: [E1, E2] = [E1.one, E2.one]; var t11 = <[number, number]>t10; var array1 = <{}[]>emptyObjTuple; diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt b/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt index 4b85b821a89..e3b857412cc 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt +++ b/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion01.ts(2,11): error TS2733: Index '0' is out-of-bounds in tuple of length 0. +tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion01.ts(2,11): error TS2339: Property '0' does not exist on type '[]'. ==== tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion01.ts (1 errors) ==== let x = <[]>[]; let y = x[0]; ~ -!!! error TS2733: Index '0' is out-of-bounds in tuple of length 0. \ No newline at end of file +!!! error TS2339: Property '0' does not exist on type '[]'. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt b/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt index 3969ed0fc2d..34d22dc673a 100644 --- a/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt +++ b/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion02.ts(2,11): error TS2733: Index '0' is out-of-bounds in tuple of length 0. +tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion02.ts(2,11): error TS2339: Property '0' does not exist on type '[]'. ==== tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion02.ts (1 errors) ==== let x = [] as []; let y = x[0]; ~ -!!! error TS2733: Index '0' is out-of-bounds in tuple of length 0. \ No newline at end of file +!!! error TS2339: Property '0' does not exist on type '[]'. \ No newline at end of file diff --git a/tests/baselines/reference/genericCallWithTupleType.errors.txt b/tests/baselines/reference/genericCallWithTupleType.errors.txt index 6f902ebe757..b8f354545de 100644 --- a/tests/baselines/reference/genericCallWithTupleType.errors.txt +++ b/tests/baselines/reference/genericCallWithTupleType.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(12,1): error TS2322: Type '[string, number, boolean, boolean]' is not assignable to type '[string, number]'. Types of property 'length' are incompatible. Type '4' is not assignable to type '2'. -tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(13,20): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(13,20): error TS2339: Property '2' does not exist on type '[string, number]'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,1): error TS2322: Type '{ a: string; }' is not assignable to type 'undefined'. -tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,11): error TS2733: Index '3' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(15,20): error TS2733: Index '3' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,11): error TS2339: Property '3' does not exist on type '[string, number]'. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(15,20): error TS2339: Property '3' does not exist on type '[string, number]'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,14): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,17): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(23,14): error TS2322: Type '{}' is not assignable to type 'string'. @@ -32,15 +32,15 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup !!! error TS2322: Type '4' is not assignable to type '2'. var e3 = i1.tuple1[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[string, number]'. i1.tuple1[3] = { a: "string" }; ~~~~~~~~~~~~ !!! error TS2322: Type '{ a: string; }' is not assignable to type 'undefined'. ~ -!!! error TS2733: Index '3' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '3' does not exist on type '[string, number]'. var e4 = i1.tuple1[3]; // {} ~ -!!! error TS2733: Index '3' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '3' does not exist on type '[string, number]'. i2.tuple1 = ["foo", 5]; i2.tuple1 = ["foo", "bar"]; i2.tuple1 = [5, "bar"]; diff --git a/tests/baselines/reference/indexerWithTuple.errors.txt b/tests/baselines/reference/indexerWithTuple.errors.txt index 4e931a3ad6e..45cddd9313f 100644 --- a/tests/baselines/reference/indexerWithTuple.errors.txt +++ b/tests/baselines/reference/indexerWithTuple.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/tuple/indexerWithTuple.ts(11,25): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/tuple/indexerWithTuple.ts(17,27): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/tuple/indexerWithTuple.ts(20,30): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(11,25): error TS2339: Property '2' does not exist on type '[string, number]'. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(17,27): error TS2339: Property '2' does not exist on type '[number, [string, number]]'. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(20,30): error TS2339: Property '2' does not exist on type '[number, string | number]'. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2339: Property '2' does not exist on type '[boolean, string | number]'. ==== tests/cases/conformance/types/tuple/indexerWithTuple.ts (4 errors) ==== @@ -17,7 +17,7 @@ tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2733: In var ele11 = strNumTuple[1]; // number var ele12 = strNumTuple[2]; // string | number ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[string, number]'. var ele13 = strNumTuple[idx0]; // string | number var ele14 = strNumTuple[idx1]; // string | number var ele15 = strNumTuple["0"]; // string @@ -25,12 +25,12 @@ tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2733: In var strNumTuple1 = numTupleTuple[1]; //[string, number]; var ele17 = numTupleTuple[2]; // number | [string, number] ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, [string, number]]'. var eleUnion10 = unionTuple1[0]; // number var eleUnion11 = unionTuple1[1]; // string | number var eleUnion12 = unionTuple1[2]; // string | number ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string | number]'. var eleUnion13 = unionTuple1[idx0]; // string | number var eleUnion14 = unionTuple1[idx1]; // string | number var eleUnion15 = unionTuple1["0"]; // number @@ -40,7 +40,7 @@ tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2733: In var eleUnion21 = unionTuple2[1]; // string | number var eleUnion22 = unionTuple2[2]; // string | number | boolean ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[boolean, string | number]'. var eleUnion23 = unionTuple2[idx0]; // string | number | boolean var eleUnion24 = unionTuple2[idx1]; // string | number | boolean var eleUnion25 = unionTuple2["0"]; // boolean diff --git a/tests/baselines/reference/keyofAndIndexedAccess.js b/tests/baselines/reference/keyofAndIndexedAccess.js index 29a39b32251..b7d794285fa 100644 --- a/tests/baselines/reference/keyofAndIndexedAccess.js +++ b/tests/baselines/reference/keyofAndIndexedAccess.js @@ -61,12 +61,11 @@ type Q21 = Shape[WIDTH_OR_HEIGHT]; // number type Q30 = [string, number][0]; // string type Q31 = [string, number][1]; // number -type Q32 = [string, number][2]; // string | number +type Q32 = [string, number][number]; // string | number type Q33 = [string, number][E.A]; // string type Q34 = [string, number][E.B]; // number -type Q35 = [string, number][E.C]; // string | number -type Q36 = [string, number]["0"]; // string -type Q37 = [string, number]["1"]; // string +type Q35 = [string, number]["0"]; // string +type Q36 = [string, number]["1"]; // string type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" @@ -1147,12 +1146,11 @@ declare type Q20 = Shape[NAME]; declare type Q21 = Shape[WIDTH_OR_HEIGHT]; declare type Q30 = [string, number][0]; declare type Q31 = [string, number][1]; -declare type Q32 = [string, number][2]; +declare type Q32 = [string, number][number]; declare type Q33 = [string, number][E.A]; declare type Q34 = [string, number][E.B]; -declare type Q35 = [string, number][E.C]; -declare type Q36 = [string, number]["0"]; -declare type Q37 = [string, number]["1"]; +declare type Q35 = [string, number]["0"]; +declare type Q36 = [string, number]["1"]; declare type Q40 = (Shape | Options)["visible"]; declare type Q41 = (Shape & Options)["visible"]; declare type Q50 = Dictionary["howdy"]; diff --git a/tests/baselines/reference/keyofAndIndexedAccess.symbols b/tests/baselines/reference/keyofAndIndexedAccess.symbols index d69da8b8ed7..9881365b470 100644 --- a/tests/baselines/reference/keyofAndIndexedAccess.symbols +++ b/tests/baselines/reference/keyofAndIndexedAccess.symbols @@ -174,11 +174,11 @@ type Q30 = [string, number][0]; // string type Q31 = [string, number][1]; // number >Q31 : Symbol(Q31, Decl(keyofAndIndexedAccess.ts, 60, 31)) -type Q32 = [string, number][2]; // string | number +type Q32 = [string, number][number]; // string | number >Q32 : Symbol(Q32, Decl(keyofAndIndexedAccess.ts, 61, 31)) type Q33 = [string, number][E.A]; // string ->Q33 : Symbol(Q33, Decl(keyofAndIndexedAccess.ts, 62, 31)) +>Q33 : Symbol(Q33, Decl(keyofAndIndexedAccess.ts, 62, 36)) >E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 21, 48)) >A : Symbol(E.A, Decl(keyofAndIndexedAccess.ts, 23, 14)) @@ -187,2153 +187,2148 @@ type Q34 = [string, number][E.B]; // number >E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 21, 48)) >B : Symbol(E.B, Decl(keyofAndIndexedAccess.ts, 23, 17)) -type Q35 = [string, number][E.C]; // string | number +type Q35 = [string, number]["0"]; // string >Q35 : Symbol(Q35, Decl(keyofAndIndexedAccess.ts, 64, 33)) ->E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 21, 48)) ->C : Symbol(E.C, Decl(keyofAndIndexedAccess.ts, 23, 20)) -type Q36 = [string, number]["0"]; // string +type Q36 = [string, number]["1"]; // string >Q36 : Symbol(Q36, Decl(keyofAndIndexedAccess.ts, 65, 33)) -type Q37 = [string, number]["1"]; // string ->Q37 : Symbol(Q37, Decl(keyofAndIndexedAccess.ts, 66, 33)) - type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" ->Q40 : Symbol(Q40, Decl(keyofAndIndexedAccess.ts, 67, 33)) +>Q40 : Symbol(Q40, Decl(keyofAndIndexedAccess.ts, 66, 33)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) >Options : Symbol(Options, Decl(keyofAndIndexedAccess.ts, 14, 1)) type Q41 = (Shape & Options)["visible"]; // true & "yes" | true & "no" | false & "yes" | false & "no" ->Q41 : Symbol(Q41, Decl(keyofAndIndexedAccess.ts, 69, 40)) +>Q41 : Symbol(Q41, Decl(keyofAndIndexedAccess.ts, 68, 40)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) >Options : Symbol(Options, Decl(keyofAndIndexedAccess.ts, 14, 1)) type Q50 = Dictionary["howdy"]; // Shape ->Q50 : Symbol(Q50, Decl(keyofAndIndexedAccess.ts, 70, 40)) +>Q50 : Symbol(Q50, Decl(keyofAndIndexedAccess.ts, 69, 40)) >Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 18, 1)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) type Q51 = Dictionary[123]; // Shape ->Q51 : Symbol(Q51, Decl(keyofAndIndexedAccess.ts, 72, 38)) +>Q51 : Symbol(Q51, Decl(keyofAndIndexedAccess.ts, 71, 38)) >Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 18, 1)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) type Q52 = Dictionary[E.B]; // Shape ->Q52 : Symbol(Q52, Decl(keyofAndIndexedAccess.ts, 73, 34)) +>Q52 : Symbol(Q52, Decl(keyofAndIndexedAccess.ts, 72, 34)) >Dictionary : Symbol(Dictionary, Decl(keyofAndIndexedAccess.ts, 18, 1)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) >E : Symbol(E, Decl(keyofAndIndexedAccess.ts, 21, 48)) >B : Symbol(E.B, Decl(keyofAndIndexedAccess.ts, 23, 17)) declare let cond: boolean; ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) function getProperty(obj: T, key: K) { ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 78, 21)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 78, 23)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 78, 21)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 78, 43)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 78, 21)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 78, 50)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 78, 23)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 77, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 77, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 77, 21)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 77, 43)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 77, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 77, 50)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 77, 23)) return obj[key]; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 78, 43)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 78, 50)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 77, 43)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 77, 50)) } function setProperty(obj: T, key: K, value: T[K]) { ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 82, 21)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 82, 23)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 82, 21)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 82, 43)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 82, 21)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 82, 50)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 82, 23)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 82, 58)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 82, 21)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 82, 23)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 81, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 81, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 81, 21)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 81, 43)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 81, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 81, 50)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 81, 23)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 81, 58)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 81, 21)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 81, 23)) obj[key] = value; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 82, 43)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 82, 50)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 82, 58)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 81, 43)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 81, 50)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 81, 58)) } function f10(shape: Shape) { ->f10 : Symbol(f10, Decl(keyofAndIndexedAccess.ts, 84, 1)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) +>f10 : Symbol(f10, Decl(keyofAndIndexedAccess.ts, 83, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) let name = getProperty(shape, "name"); // string ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 87, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 86, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) let widthOrHeight = getProperty(shape, cond ? "width" : "height"); // number ->widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 88, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 87, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) let nameOrVisible = getProperty(shape, cond ? "name" : "visible"); // string | boolean ->nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 89, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 88, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) setProperty(shape, "name", "rectangle"); ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) setProperty(shape, cond ? "width" : "height", 10); ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) setProperty(shape, cond ? "name" : "visible", true); // Technically not safe ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 86, 13)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 85, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) } function f11(a: Shape[]) { ->f11 : Symbol(f11, Decl(keyofAndIndexedAccess.ts, 93, 1)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 95, 13)) +>f11 : Symbol(f11, Decl(keyofAndIndexedAccess.ts, 92, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 94, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) let len = getProperty(a, "length"); // number ->len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 96, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 95, 13)) +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 95, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 94, 13)) setProperty(a, "length", len); ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 95, 13)) ->len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 96, 7)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 94, 13)) +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 95, 7)) } function f12(t: [Shape, boolean]) { ->f12 : Symbol(f12, Decl(keyofAndIndexedAccess.ts, 98, 1)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 100, 13)) +>f12 : Symbol(f12, Decl(keyofAndIndexedAccess.ts, 97, 1)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 99, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) let len = getProperty(t, "length"); ->len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 101, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 100, 13)) +>len : Symbol(len, Decl(keyofAndIndexedAccess.ts, 100, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 99, 13)) let s2 = getProperty(t, "0"); // Shape ->s2 : Symbol(s2, Decl(keyofAndIndexedAccess.ts, 102, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 100, 13)) +>s2 : Symbol(s2, Decl(keyofAndIndexedAccess.ts, 101, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 99, 13)) let b2 = getProperty(t, "1"); // boolean ->b2 : Symbol(b2, Decl(keyofAndIndexedAccess.ts, 103, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 100, 13)) +>b2 : Symbol(b2, Decl(keyofAndIndexedAccess.ts, 102, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 99, 13)) } function f13(foo: any, bar: any) { ->f13 : Symbol(f13, Decl(keyofAndIndexedAccess.ts, 104, 1)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 106, 13)) ->bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 106, 22)) +>f13 : Symbol(f13, Decl(keyofAndIndexedAccess.ts, 103, 1)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 105, 13)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 105, 22)) let x = getProperty(foo, "x"); // any ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 107, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 106, 13)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 106, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 105, 13)) let y = getProperty(foo, "100"); // any ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 108, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 106, 13)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 107, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 105, 13)) let z = getProperty(foo, bar); // any ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 109, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 106, 13)) ->bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 106, 22)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 108, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 105, 13)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 105, 22)) } class Component { ->Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 110, 1)) ->PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 112, 16)) +>Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 109, 1)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 111, 16)) props: PropType; ->props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 112, 27)) ->PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 112, 16)) +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 111, 27)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 111, 16)) getProperty(key: K) { ->getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 114, 16)) ->PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 112, 16)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 114, 42)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 114, 16)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 113, 16)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 111, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 113, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 113, 16)) return this.props[key]; ->this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 112, 27)) ->this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 110, 1)) ->props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 112, 27)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 114, 42)) +>this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 111, 27)) +>this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 109, 1)) +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 111, 27)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 113, 42)) } setProperty(key: K, value: PropType[K]) { ->setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 117, 16)) ->PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 112, 16)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 117, 42)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 117, 16)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 117, 49)) ->PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 112, 16)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 117, 16)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 116, 16)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 111, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 116, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 116, 16)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 116, 49)) +>PropType : Symbol(PropType, Decl(keyofAndIndexedAccess.ts, 111, 16)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 116, 16)) this.props[key] = value; ->this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 112, 27)) ->this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 110, 1)) ->props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 112, 27)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 117, 42)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 117, 49)) +>this.props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 111, 27)) +>this : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 109, 1)) +>props : Symbol(Component.props, Decl(keyofAndIndexedAccess.ts, 111, 27)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 116, 42)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 116, 49)) } } function f20(component: Component) { ->f20 : Symbol(f20, Decl(keyofAndIndexedAccess.ts, 120, 1)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 110, 1)) +>f20 : Symbol(f20, Decl(keyofAndIndexedAccess.ts, 119, 1)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>Component : Symbol(Component, Decl(keyofAndIndexedAccess.ts, 109, 1)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) let name = component.getProperty("name"); // string ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 123, 7)) ->component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 122, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) let widthOrHeight = component.getProperty(cond ? "width" : "height"); // number ->widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 124, 7)) ->component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>widthOrHeight : Symbol(widthOrHeight, Decl(keyofAndIndexedAccess.ts, 123, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) let nameOrVisible = component.getProperty(cond ? "name" : "visible"); // string | boolean ->nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 125, 7)) ->component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 113, 20)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>nameOrVisible : Symbol(nameOrVisible, Decl(keyofAndIndexedAccess.ts, 124, 7)) +>component.getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>getProperty : Symbol(Component.getProperty, Decl(keyofAndIndexedAccess.ts, 112, 20)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) component.setProperty("name", "rectangle"); ->component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) component.setProperty(cond ? "width" : "height", 10) ->component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) component.setProperty(cond ? "name" : "visible", true); // Technically not safe ->component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 122, 13)) ->setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 116, 5)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>component.setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>component : Symbol(component, Decl(keyofAndIndexedAccess.ts, 121, 13)) +>setProperty : Symbol(Component.setProperty, Decl(keyofAndIndexedAccess.ts, 115, 5)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) } function pluck(array: T[], key: K) { ->pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 129, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 131, 15)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 131, 17)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 131, 15)) ->array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 131, 37)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 131, 15)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 131, 48)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 131, 17)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 128, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 130, 15)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 130, 17)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 130, 15)) +>array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 130, 37)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 130, 15)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 130, 48)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 130, 17)) return array.map(x => x[key]); >array.map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) ->array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 131, 37)) +>array : Symbol(array, Decl(keyofAndIndexedAccess.ts, 130, 37)) >map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 132, 21)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 132, 21)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 131, 48)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 131, 21)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 131, 21)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 130, 48)) } function f30(shapes: Shape[]) { ->f30 : Symbol(f30, Decl(keyofAndIndexedAccess.ts, 133, 1)) ->shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 135, 13)) +>f30 : Symbol(f30, Decl(keyofAndIndexedAccess.ts, 132, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 134, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) let names = pluck(shapes, "name"); // string[] ->names : Symbol(names, Decl(keyofAndIndexedAccess.ts, 136, 7)) ->pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 129, 1)) ->shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 135, 13)) +>names : Symbol(names, Decl(keyofAndIndexedAccess.ts, 135, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 128, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 134, 13)) let widths = pluck(shapes, "width"); // number[] ->widths : Symbol(widths, Decl(keyofAndIndexedAccess.ts, 137, 7)) ->pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 129, 1)) ->shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 135, 13)) +>widths : Symbol(widths, Decl(keyofAndIndexedAccess.ts, 136, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 128, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 134, 13)) let nameOrVisibles = pluck(shapes, cond ? "name" : "visible"); // (string | boolean)[] ->nameOrVisibles : Symbol(nameOrVisibles, Decl(keyofAndIndexedAccess.ts, 138, 7)) ->pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 129, 1)) ->shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 135, 13)) ->cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 76, 11)) +>nameOrVisibles : Symbol(nameOrVisibles, Decl(keyofAndIndexedAccess.ts, 137, 7)) +>pluck : Symbol(pluck, Decl(keyofAndIndexedAccess.ts, 128, 1)) +>shapes : Symbol(shapes, Decl(keyofAndIndexedAccess.ts, 134, 13)) +>cond : Symbol(cond, Decl(keyofAndIndexedAccess.ts, 75, 11)) } function f31(key: K) { ->f31 : Symbol(f31, Decl(keyofAndIndexedAccess.ts, 139, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 141, 13)) +>f31 : Symbol(f31, Decl(keyofAndIndexedAccess.ts, 138, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 140, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 141, 36)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 141, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 140, 36)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 140, 13)) const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 142, 9)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 141, 9)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 142, 26)) ->width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 142, 39)) ->height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 142, 49)) ->visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 142, 61)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 141, 26)) +>width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 141, 39)) +>height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 141, 49)) +>visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 141, 61)) return shape[key]; // Shape[K] ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 142, 9)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 141, 36)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 141, 9)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 140, 36)) } function f32(key: K) { ->f32 : Symbol(f32, Decl(keyofAndIndexedAccess.ts, 144, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 146, 13)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 146, 43)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 146, 13)) +>f32 : Symbol(f32, Decl(keyofAndIndexedAccess.ts, 143, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 145, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 145, 43)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 145, 13)) const shape: Shape = { name: "foo", width: 5, height: 10, visible: true }; ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 147, 9)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 146, 9)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 147, 26)) ->width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 147, 39)) ->height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 147, 49)) ->visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 147, 61)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 146, 26)) +>width : Symbol(width, Decl(keyofAndIndexedAccess.ts, 146, 39)) +>height : Symbol(height, Decl(keyofAndIndexedAccess.ts, 146, 49)) +>visible : Symbol(visible, Decl(keyofAndIndexedAccess.ts, 146, 61)) return shape[key]; // Shape[K] ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 147, 9)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 146, 43)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 146, 9)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 145, 43)) } function f33(shape: S, key: K) { ->f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 149, 1)) ->S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 151, 13)) +>f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 148, 1)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 150, 13)) >Shape : Symbol(Shape, Decl(keyofAndIndexedAccess.ts, 0, 0)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 151, 29)) ->S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 151, 13)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 151, 49)) ->S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 151, 13)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 151, 58)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 151, 29)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 150, 29)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 150, 13)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 150, 49)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 150, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 150, 58)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 150, 29)) let name = getProperty(shape, "name"); ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 152, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 151, 49)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 151, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 150, 49)) let prop = getProperty(shape, key); ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 153, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 151, 49)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 151, 58)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 152, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>shape : Symbol(shape, Decl(keyofAndIndexedAccess.ts, 150, 49)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 150, 58)) return prop; ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 153, 7)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 152, 7)) } function f34(ts: TaggedShape) { ->f34 : Symbol(f34, Decl(keyofAndIndexedAccess.ts, 155, 1)) ->ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 157, 13)) +>f34 : Symbol(f34, Decl(keyofAndIndexedAccess.ts, 154, 1)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 156, 13)) >TaggedShape : Symbol(TaggedShape, Decl(keyofAndIndexedAccess.ts, 5, 1)) let tag1 = f33(ts, "tag"); ->tag1 : Symbol(tag1, Decl(keyofAndIndexedAccess.ts, 158, 7)) ->f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 149, 1)) ->ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 157, 13)) +>tag1 : Symbol(tag1, Decl(keyofAndIndexedAccess.ts, 157, 7)) +>f33 : Symbol(f33, Decl(keyofAndIndexedAccess.ts, 148, 1)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 156, 13)) let tag2 = getProperty(ts, "tag"); ->tag2 : Symbol(tag2, Decl(keyofAndIndexedAccess.ts, 159, 7)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 157, 13)) +>tag2 : Symbol(tag2, Decl(keyofAndIndexedAccess.ts, 158, 7)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>ts : Symbol(ts, Decl(keyofAndIndexedAccess.ts, 156, 13)) } class C { ->C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 160, 1)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 159, 1)) public x: string; ->x : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 162, 9)) +>x : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 161, 9)) protected y: string; ->y : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 163, 21)) +>y : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 162, 21)) private z: string; ->z : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 164, 24)) +>z : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 163, 24)) } // Indexed access expressions have always permitted access to private and protected members. // For consistency we also permit such access in indexed access types. function f40(c: C) { ->f40 : Symbol(f40, Decl(keyofAndIndexedAccess.ts, 166, 1)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 170, 13)) ->C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 160, 1)) +>f40 : Symbol(f40, Decl(keyofAndIndexedAccess.ts, 165, 1)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 169, 13)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 159, 1)) type X = C["x"]; ->X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 170, 20)) ->C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 160, 1)) +>X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 169, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 159, 1)) type Y = C["y"]; ->Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 171, 20)) ->C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 160, 1)) +>Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 170, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 159, 1)) type Z = C["z"]; ->Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 172, 20)) ->C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 160, 1)) +>Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 171, 20)) +>C : Symbol(C, Decl(keyofAndIndexedAccess.ts, 159, 1)) let x: X = c["x"]; ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 174, 7)) ->X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 170, 20)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 170, 13)) ->"x" : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 162, 9)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 173, 7)) +>X : Symbol(X, Decl(keyofAndIndexedAccess.ts, 169, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 169, 13)) +>"x" : Symbol(C.x, Decl(keyofAndIndexedAccess.ts, 161, 9)) let y: Y = c["y"]; ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 175, 7)) ->Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 171, 20)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 170, 13)) ->"y" : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 163, 21)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 174, 7)) +>Y : Symbol(Y, Decl(keyofAndIndexedAccess.ts, 170, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 169, 13)) +>"y" : Symbol(C.y, Decl(keyofAndIndexedAccess.ts, 162, 21)) let z: Z = c["z"]; ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 176, 7)) ->Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 172, 20)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 170, 13)) ->"z" : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 164, 24)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 175, 7)) +>Z : Symbol(Z, Decl(keyofAndIndexedAccess.ts, 171, 20)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 169, 13)) +>"z" : Symbol(C.z, Decl(keyofAndIndexedAccess.ts, 163, 24)) } function f50(k: keyof T, s: string) { ->f50 : Symbol(f50, Decl(keyofAndIndexedAccess.ts, 177, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 179, 13)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 179, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 179, 13)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 179, 27)) +>f50 : Symbol(f50, Decl(keyofAndIndexedAccess.ts, 176, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 178, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 178, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 178, 13)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 178, 27)) const x1 = s as keyof T; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 180, 9)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 179, 27)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 179, 13)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 179, 9)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 178, 27)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 178, 13)) const x2 = k as string; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 181, 9)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 179, 16)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 180, 9)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 178, 16)) } function f51(k: K, s: string) { ->f51 : Symbol(f51, Decl(keyofAndIndexedAccess.ts, 182, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 184, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 184, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 184, 13)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 184, 35)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 184, 15)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 184, 40)) +>f51 : Symbol(f51, Decl(keyofAndIndexedAccess.ts, 181, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 183, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 183, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 183, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 183, 35)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 183, 15)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 183, 40)) const x1 = s as keyof T; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 185, 9)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 184, 40)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 184, 13)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 184, 9)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 183, 40)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 183, 13)) const x2 = k as string; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 186, 9)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 184, 35)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 185, 9)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 183, 35)) } function f52(obj: { [x: string]: boolean }, k: Exclude, s: string, n: number) { ->f52 : Symbol(f52, Decl(keyofAndIndexedAccess.ts, 187, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 189, 13)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 189, 16)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 189, 24)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 189, 46)) +>f52 : Symbol(f52, Decl(keyofAndIndexedAccess.ts, 186, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 188, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 188, 16)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 188, 24)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 188, 46)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 189, 13)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 189, 75)) ->n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 189, 86)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 188, 13)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 188, 75)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 188, 86)) const x1 = obj[s]; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 190, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 189, 16)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 189, 75)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 189, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 188, 16)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 188, 75)) const x2 = obj[n]; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 191, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 189, 16)) ->n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 189, 86)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 190, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 188, 16)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 188, 86)) const x3 = obj[k]; ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 192, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 189, 16)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 189, 46)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 191, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 188, 16)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 188, 46)) } function f53>(obj: { [x: string]: boolean }, k: K, s: string, n: number) { ->f53 : Symbol(f53, Decl(keyofAndIndexedAccess.ts, 193, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 195, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 195, 15)) +>f53 : Symbol(f53, Decl(keyofAndIndexedAccess.ts, 192, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 194, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 194, 15)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 195, 13)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 195, 52)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 195, 60)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 195, 82)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 195, 15)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 195, 88)) ->n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 195, 99)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 194, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 194, 52)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 194, 60)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 194, 82)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 194, 15)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 194, 88)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 194, 99)) const x1 = obj[s]; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 196, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 195, 52)) ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 195, 88)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 195, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 194, 52)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 194, 88)) const x2 = obj[n]; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 197, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 195, 52)) ->n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 195, 99)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 196, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 194, 52)) +>n : Symbol(n, Decl(keyofAndIndexedAccess.ts, 194, 99)) const x3 = obj[k]; ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 198, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 195, 52)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 195, 82)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 197, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 194, 52)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 194, 82)) } function f54(obj: T, key: keyof T) { ->f54 : Symbol(f54, Decl(keyofAndIndexedAccess.ts, 199, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 201, 13)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 201, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 201, 13)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 201, 23)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 201, 13)) +>f54 : Symbol(f54, Decl(keyofAndIndexedAccess.ts, 198, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 200, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 200, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 200, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 200, 23)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 200, 13)) for (let s in obj[key]) { ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 202, 12)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 201, 16)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 201, 23)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 201, 12)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 200, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 200, 23)) } const b = "foo" in obj[key]; ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 204, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 201, 16)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 201, 23)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 203, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 200, 16)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 200, 23)) } function f55(obj: T, key: K) { ->f55 : Symbol(f55, Decl(keyofAndIndexedAccess.ts, 205, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 207, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 207, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 207, 13)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 207, 35)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 207, 13)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 207, 42)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 207, 15)) +>f55 : Symbol(f55, Decl(keyofAndIndexedAccess.ts, 204, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 206, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 206, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 206, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 206, 35)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 206, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 206, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 206, 15)) for (let s in obj[key]) { ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 208, 12)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 207, 35)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 207, 42)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 207, 12)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 206, 35)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 206, 42)) } const b = "foo" in obj[key]; ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 210, 9)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 207, 35)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 207, 42)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 209, 9)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 206, 35)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 206, 42)) } function f60(source: T, target: T) { ->f60 : Symbol(f60, Decl(keyofAndIndexedAccess.ts, 211, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 213, 13)) ->source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 213, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 213, 13)) ->target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 213, 26)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 213, 13)) +>f60 : Symbol(f60, Decl(keyofAndIndexedAccess.ts, 210, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 212, 13)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 212, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 212, 13)) +>target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 212, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 212, 13)) for (let k in source) { ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 214, 12)) ->source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 213, 16)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 213, 12)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 212, 16)) target[k] = source[k]; ->target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 213, 26)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 214, 12)) ->source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 213, 16)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 214, 12)) +>target : Symbol(target, Decl(keyofAndIndexedAccess.ts, 212, 26)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 213, 12)) +>source : Symbol(source, Decl(keyofAndIndexedAccess.ts, 212, 16)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 213, 12)) } } function f70(func: (k1: keyof (T | U), k2: keyof (T & U)) => void) { ->f70 : Symbol(f70, Decl(keyofAndIndexedAccess.ts, 217, 1)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 219, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 219, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 219, 22)) ->k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 219, 26)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 219, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 219, 22)) ->k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 219, 44)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 219, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 219, 22)) +>f70 : Symbol(f70, Decl(keyofAndIndexedAccess.ts, 216, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 218, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 218, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 218, 22)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 218, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 218, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 218, 22)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 218, 44)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 218, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 218, 22)) func<{ a: any, b: any }, { a: any, c: any }>('a', 'a'); ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 219, 13)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 218, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 219, 10)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 219, 18)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 219, 30)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 219, 38)) + + func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 218, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 220, 10)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 220, 18)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 220, 30)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 220, 38)) - func<{ a: any, b: any }, { a: any, c: any }>('a', 'b'); ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 219, 13)) + func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 218, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 221, 10)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 221, 18)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 221, 30)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 221, 38)) - - func<{ a: any, b: any }, { a: any, c: any }>('a', 'c'); ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 219, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 222, 10)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 222, 18)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 222, 30)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 222, 38)) } function f71(func: (x: T, y: U) => Partial) { ->f71 : Symbol(f71, Decl(keyofAndIndexedAccess.ts, 223, 1)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 225, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 225, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 225, 22)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 225, 26)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 225, 20)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 225, 31)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 225, 22)) +>f71 : Symbol(f71, Decl(keyofAndIndexedAccess.ts, 222, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 224, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 224, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 224, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 224, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 224, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 224, 31)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 224, 22)) >Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 225, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 225, 22)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 224, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 224, 22)) let x = func({ a: 1, b: "hello" }, { c: true }); ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 226, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 225, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 226, 18)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 226, 24)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 226, 40)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 225, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 224, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 225, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 225, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 225, 40)) x.a; // number | undefined ->x.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 226, 18)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 226, 7)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 226, 18)) +>x.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 225, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 225, 7)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 225, 18)) x.b; // string | undefined ->x.b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 226, 24)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 226, 7)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 226, 24)) +>x.b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 225, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 225, 7)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 225, 24)) x.c; // boolean | undefined ->x.c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 226, 40)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 226, 7)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 226, 40)) +>x.c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 225, 40)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 225, 7)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 225, 40)) } function f72(func: (x: T, y: U, k: K) => (T & U)[K]) { ->f72 : Symbol(f72, Decl(keyofAndIndexedAccess.ts, 230, 1)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 232, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 232, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 232, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 232, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 232, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 232, 22)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 232, 55)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 232, 20)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 232, 60)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 232, 22)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 232, 66)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 232, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 232, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 232, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 232, 25)) +>f72 : Symbol(f72, Decl(keyofAndIndexedAccess.ts, 229, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 231, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 231, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 231, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 231, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 231, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 231, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 231, 55)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 231, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 231, 60)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 231, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 231, 66)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 231, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 231, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 231, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 231, 25)) let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 233, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 232, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 232, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 231, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 232, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 232, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 232, 40)) + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 233, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 231, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 233, 18)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 233, 24)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 233, 40)) - let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 234, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 232, 13)) + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 234, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 231, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 234, 18)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 234, 24)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 234, 40)) - - let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 235, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 232, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 235, 18)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 235, 24)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 235, 40)) } function f73(func: (x: T, y: U, k: K) => (T & U)[K]) { ->f73 : Symbol(f73, Decl(keyofAndIndexedAccess.ts, 236, 1)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 238, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 238, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 238, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 238, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 238, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 238, 22)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 238, 51)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 238, 20)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 238, 56)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 238, 22)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 238, 62)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 238, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 238, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 238, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 238, 25)) +>f73 : Symbol(f73, Decl(keyofAndIndexedAccess.ts, 235, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 237, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 237, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 237, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 237, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 237, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 237, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 237, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 237, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 237, 56)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 237, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 237, 62)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 237, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 237, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 237, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 237, 25)) let a = func({ a: 1, b: "hello" }, { c: true }, 'a'); // number ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 239, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 238, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 238, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 237, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 238, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 238, 24)) +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 238, 40)) + + let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 239, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 237, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 239, 18)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 239, 24)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 239, 40)) - let b = func({ a: 1, b: "hello" }, { c: true }, 'b'); // string ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 240, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 238, 13)) + let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean +>c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 240, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 237, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 240, 18)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 240, 24)) >c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 240, 40)) - - let c = func({ a: 1, b: "hello" }, { c: true }, 'c'); // boolean ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 241, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 238, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 241, 18)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 241, 24)) ->c : Symbol(c, Decl(keyofAndIndexedAccess.ts, 241, 40)) } function f74(func: (x: T, y: U, k: K) => (T | U)[K]) { ->f74 : Symbol(f74, Decl(keyofAndIndexedAccess.ts, 242, 1)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 244, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 244, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 244, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 244, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 244, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 244, 22)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 244, 51)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 244, 20)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 244, 56)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 244, 22)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 244, 62)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 244, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 244, 20)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 244, 22)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 244, 25)) +>f74 : Symbol(f74, Decl(keyofAndIndexedAccess.ts, 241, 1)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 243, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 243, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 243, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 243, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 243, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 243, 22)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 243, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 243, 20)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 243, 56)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 243, 22)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 243, 62)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 243, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 243, 20)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 243, 22)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 243, 25)) let a = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'a'); // number ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 245, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 244, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 244, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 243, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 244, 18)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 244, 24)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 244, 40)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 244, 46)) + + let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 245, 7)) +>func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 243, 13)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 245, 18)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 245, 24)) >a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 245, 40)) >b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 245, 46)) - - let b = func({ a: 1, b: "hello" }, { a: 2, b: true }, 'b'); // string | boolean ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 246, 7)) ->func : Symbol(func, Decl(keyofAndIndexedAccess.ts, 244, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 246, 18)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 246, 24)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 246, 40)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 246, 46)) } function f80(obj: T) { ->f80 : Symbol(f80, Decl(keyofAndIndexedAccess.ts, 247, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 249, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 249, 29)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 249, 13)) +>f80 : Symbol(f80, Decl(keyofAndIndexedAccess.ts, 246, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 248, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 248, 29)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 248, 13)) let a1 = obj.a; // { x: any } ->a1 : Symbol(a1, Decl(keyofAndIndexedAccess.ts, 250, 7)) ->obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) +>a1 : Symbol(a1, Decl(keyofAndIndexedAccess.ts, 249, 7)) +>obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) let a2 = obj['a']; // { x: any } ->a2 : Symbol(a2, Decl(keyofAndIndexedAccess.ts, 251, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) +>a2 : Symbol(a2, Decl(keyofAndIndexedAccess.ts, 250, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) let a3 = obj['a'] as T['a']; // T["a"] ->a3 : Symbol(a3, Decl(keyofAndIndexedAccess.ts, 252, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 249, 13)) +>a3 : Symbol(a3, Decl(keyofAndIndexedAccess.ts, 251, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 248, 13)) let x1 = obj.a.x; // any ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 253, 7)) ->obj.a.x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 249, 29)) ->obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 249, 29)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 252, 7)) +>obj.a.x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 248, 29)) +>obj.a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 248, 29)) let x2 = obj['a']['x']; // any ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 254, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 249, 29)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 253, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 248, 29)) let x3 = obj['a']['x'] as T['a']['x']; // T["a"]["x"] ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 255, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 249, 42)) ->'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 249, 24)) ->'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 249, 29)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 249, 13)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 254, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 248, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 248, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 248, 29)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 248, 13)) } function f81(obj: T) { ->f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 256, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 258, 13)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 258, 24)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 258, 29)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 258, 42)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 258, 13)) +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 255, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 257, 13)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 257, 24)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 257, 29)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 257, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 257, 13)) return obj['a']['x'] as T['a']['x']; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 258, 42)) ->'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 258, 24)) ->'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 258, 29)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 258, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 257, 42)) +>'a' : Symbol(a, Decl(keyofAndIndexedAccess.ts, 257, 24)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 257, 29)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 257, 13)) } function f82() { ->f82 : Symbol(f82, Decl(keyofAndIndexedAccess.ts, 260, 1)) +>f82 : Symbol(f82, Decl(keyofAndIndexedAccess.ts, 259, 1)) let x1 = f81({ a: { x: "hello" } }); // string ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 263, 7)) ->f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 256, 1)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 263, 18)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 263, 23)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 262, 7)) +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 255, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 262, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 262, 23)) let x2 = f81({ a: { x: 42 } }); // number ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 264, 7)) ->f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 256, 1)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 264, 18)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 264, 23)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 263, 7)) +>f81 : Symbol(f81, Decl(keyofAndIndexedAccess.ts, 255, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 263, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 263, 23)) } function f83(obj: T, key: K) { ->f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 265, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 267, 13)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 267, 26)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 267, 39)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 267, 51)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 267, 13)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 267, 71)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 267, 13)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 267, 78)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 267, 51)) +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 264, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 266, 13)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 266, 26)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 266, 39)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 266, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 266, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 266, 71)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 266, 13)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 266, 78)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 266, 51)) return obj[key]['x'] as T[K]['x']; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 267, 71)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 267, 78)) ->'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 267, 39)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 267, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 267, 51)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 266, 71)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 266, 78)) +>'x' : Symbol(x, Decl(keyofAndIndexedAccess.ts, 266, 39)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 266, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 266, 51)) } function f84() { ->f84 : Symbol(f84, Decl(keyofAndIndexedAccess.ts, 269, 1)) +>f84 : Symbol(f84, Decl(keyofAndIndexedAccess.ts, 268, 1)) let x1 = f83({ foo: { x: "hello" } }, "foo"); // string ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 272, 7)) ->f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 265, 1)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 272, 18)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 272, 25)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 271, 7)) +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 264, 1)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 271, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 271, 25)) let x2 = f83({ bar: { x: 42 } }, "bar"); // number ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 273, 7)) ->f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 265, 1)) ->bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 273, 18)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 273, 25)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 272, 7)) +>f83 : Symbol(f83, Decl(keyofAndIndexedAccess.ts, 264, 1)) +>bar : Symbol(bar, Decl(keyofAndIndexedAccess.ts, 272, 18)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 272, 25)) } class C1 { ->C1 : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) +>C1 : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) x: number; ->x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) get(key: K) { ->get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 277, 14)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 278, 8)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 278, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 278, 8)) +>get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 276, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 277, 8)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 277, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 277, 8)) return this[key]; ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 278, 30)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 277, 30)) } set(key: K, value: this[K]) { ->set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 280, 5)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 281, 8)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 281, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 281, 8)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 281, 37)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 281, 8)) +>set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 279, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 280, 8)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 280, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 280, 8)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 280, 37)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 280, 8)) this[key] = value; ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 281, 30)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 281, 37)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 280, 30)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 280, 37)) } foo() { ->foo : Symbol(C1.foo, Decl(keyofAndIndexedAccess.ts, 283, 5)) +>foo : Symbol(C1.foo, Decl(keyofAndIndexedAccess.ts, 282, 5)) let x1 = this.x; // number ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 285, 11)) ->this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 284, 11)) +>this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) let x2 = this["x"]; // number ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 286, 11)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 285, 11)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) let x3 = this.get("x"); // this["x"] ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 287, 11)) ->this.get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 277, 14)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 277, 14)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 286, 11)) +>this.get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 276, 14)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>get : Symbol(C1.get, Decl(keyofAndIndexedAccess.ts, 276, 14)) let x4 = getProperty(this, "x"); // this["x"] ->x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 288, 11)) ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) +>x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 287, 11)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) this.x = 42; ->this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) +>this.x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>x : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) this["x"] = 42; ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 276, 10)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>"x" : Symbol(C1.x, Decl(keyofAndIndexedAccess.ts, 275, 10)) this.set("x", 42); ->this.set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 280, 5)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) ->set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 280, 5)) +>this.set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 279, 5)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) +>set : Symbol(C1.set, Decl(keyofAndIndexedAccess.ts, 279, 5)) setProperty(this, "x", 42); ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 274, 1)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>this : Symbol(C1, Decl(keyofAndIndexedAccess.ts, 273, 1)) } } type S2 = { ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) a: string; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 296, 11)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 295, 11)) b: string; ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 297, 14)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 296, 14)) }; function f90(x1: S2[keyof S2], x2: T[keyof S2], x3: S2[K]) { ->f90 : Symbol(f90, Decl(keyofAndIndexedAccess.ts, 299, 2)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 301, 13)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 301, 26)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 301, 13)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) ->S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 294, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 301, 26)) +>f90 : Symbol(f90, Decl(keyofAndIndexedAccess.ts, 298, 2)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 300, 13)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 300, 26)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 300, 13)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) +>S2 : Symbol(S2, Decl(keyofAndIndexedAccess.ts, 293, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 300, 26)) x1 = x2; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) x1 = x3; ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) x2 = x1; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) x2 = x3; ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) x3 = x1; ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) x3 = x2; ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) x1.length; >x1.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 301, 47)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 300, 47)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) x2.length; >x2.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 301, 64)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 300, 64)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) x3.length; >x3.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 301, 81)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 300, 81)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } function f91(x: T, y: T[keyof T], z: T[K]) { ->f91 : Symbol(f91, Decl(keyofAndIndexedAccess.ts, 311, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 313, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 313, 35)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 313, 40)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 313, 55)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 313, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 313, 15)) +>f91 : Symbol(f91, Decl(keyofAndIndexedAccess.ts, 310, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 312, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 312, 35)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 312, 40)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 312, 55)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 312, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 312, 15)) let a: {}; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 314, 7)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 313, 7)) a = x; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 314, 7)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 313, 35)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 313, 7)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 312, 35)) a = y; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 314, 7)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 313, 40)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 313, 7)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 312, 40)) a = z; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 314, 7)) ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 313, 55)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 313, 7)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 312, 55)) } function f92(x: T, y: T[keyof T], z: T[K]) { ->f92 : Symbol(f92, Decl(keyofAndIndexedAccess.ts, 318, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 320, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 320, 35)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 320, 40)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 320, 55)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 320, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 320, 15)) +>f92 : Symbol(f92, Decl(keyofAndIndexedAccess.ts, 317, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 319, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 319, 35)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 319, 40)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 319, 55)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 319, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 319, 15)) let a: {} | null | undefined; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 321, 7)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 320, 7)) a = x; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 321, 7)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 320, 35)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 320, 7)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 319, 35)) a = y; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 321, 7)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 320, 40)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 320, 7)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 319, 40)) a = z; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 321, 7)) ->z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 320, 55)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 320, 7)) +>z : Symbol(z, Decl(keyofAndIndexedAccess.ts, 319, 55)) } // Repros from #12011 class Base { ->Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 325, 1)) +>Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 324, 1)) get(prop: K) { ->get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 329, 12)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 330, 8)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 330, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 330, 8)) +>get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 328, 12)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 329, 8)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 329, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 329, 8)) return this[prop]; ->this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 325, 1)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 330, 30)) +>this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 324, 1)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 329, 30)) } set(prop: K, value: this[K]) { ->set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 332, 5)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 333, 8)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 333, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 333, 8)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 333, 38)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 333, 8)) +>set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 331, 5)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 332, 8)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 332, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 332, 8)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 332, 38)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 332, 8)) this[prop] = value; ->this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 325, 1)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 333, 30)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 333, 38)) +>this : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 324, 1)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 332, 30)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 332, 38)) } } class Person extends Base { ->Person : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 336, 1)) ->Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 325, 1)) +>Person : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 335, 1)) +>Base : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 324, 1)) parts: number; ->parts : Symbol(Person.parts, Decl(keyofAndIndexedAccess.ts, 338, 27)) +>parts : Symbol(Person.parts, Decl(keyofAndIndexedAccess.ts, 337, 27)) constructor(parts: number) { ->parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 340, 16)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 339, 16)) super(); ->super : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 325, 1)) +>super : Symbol(Base, Decl(keyofAndIndexedAccess.ts, 324, 1)) this.set("parts", parts); ->this.set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 332, 5)) ->this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 336, 1)) ->set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 332, 5)) ->parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 340, 16)) +>this.set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 331, 5)) +>this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 335, 1)) +>set : Symbol(Base.set, Decl(keyofAndIndexedAccess.ts, 331, 5)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 339, 16)) } getParts() { ->getParts : Symbol(Person.getParts, Decl(keyofAndIndexedAccess.ts, 343, 5)) +>getParts : Symbol(Person.getParts, Decl(keyofAndIndexedAccess.ts, 342, 5)) return this.get("parts") ->this.get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 329, 12)) ->this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 336, 1)) ->get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 329, 12)) +>this.get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 328, 12)) +>this : Symbol(Person, Decl(keyofAndIndexedAccess.ts, 335, 1)) +>get : Symbol(Base.get, Decl(keyofAndIndexedAccess.ts, 328, 12)) } } class OtherPerson { ->OtherPerson : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 347, 1)) +>OtherPerson : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 346, 1)) parts: number; ->parts : Symbol(OtherPerson.parts, Decl(keyofAndIndexedAccess.ts, 349, 19)) +>parts : Symbol(OtherPerson.parts, Decl(keyofAndIndexedAccess.ts, 348, 19)) constructor(parts: number) { ->parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 351, 16)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 350, 16)) setProperty(this, "parts", parts); ->setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 80, 1)) ->this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 347, 1)) ->parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 351, 16)) +>setProperty : Symbol(setProperty, Decl(keyofAndIndexedAccess.ts, 79, 1)) +>this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 346, 1)) +>parts : Symbol(parts, Decl(keyofAndIndexedAccess.ts, 350, 16)) } getParts() { ->getParts : Symbol(OtherPerson.getParts, Decl(keyofAndIndexedAccess.ts, 353, 5)) +>getParts : Symbol(OtherPerson.getParts, Decl(keyofAndIndexedAccess.ts, 352, 5)) return getProperty(this, "parts") ->getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 76, 26)) ->this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 347, 1)) +>getProperty : Symbol(getProperty, Decl(keyofAndIndexedAccess.ts, 75, 26)) +>this : Symbol(OtherPerson, Decl(keyofAndIndexedAccess.ts, 346, 1)) } } // Modified repro from #12544 function path(obj: T, key1: K1): T[K1]; ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 361, 37)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) ->key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 361, 44)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 360, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 360, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 360, 14)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 360, 37)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 360, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 360, 44)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 360, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 360, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 360, 16)) function path(obj: T, key1: K1, key2: K2): T[K1][K2]; ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 362, 61)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) ->key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 362, 68)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) ->key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 362, 78)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 361, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 361, 61)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 361, 68)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 361, 78)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 361, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 361, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 361, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 361, 36)) function path(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3]; ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 363, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 363, 36)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 363, 16)) ->K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 363, 60)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 363, 16)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 363, 36)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 363, 89)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 363, 96)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 363, 16)) ->key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 363, 106)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 363, 36)) ->key3 : Symbol(key3, Decl(keyofAndIndexedAccess.ts, 363, 116)) ->K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 363, 60)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 363, 14)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 363, 16)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 363, 36)) ->K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 363, 60)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 362, 60)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 362, 89)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 362, 96)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 362, 106)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) +>key3 : Symbol(key3, Decl(keyofAndIndexedAccess.ts, 362, 116)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 362, 60)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 362, 14)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 362, 16)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 362, 36)) +>K3 : Symbol(K3, Decl(keyofAndIndexedAccess.ts, 362, 60)) function path(obj: any, ...keys: (string | number)[]): any; ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 363, 14)) +>keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 363, 23)) + +function path(obj: any, ...keys: (string | number)[]): any { +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) >obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 364, 14)) >keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 364, 23)) -function path(obj: any, ...keys: (string | number)[]): any { ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 365, 14)) ->keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 365, 23)) - let result = obj; ->result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 366, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 365, 14)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 365, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 364, 14)) for (let k of keys) { ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 367, 12)) ->keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 365, 23)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 366, 12)) +>keys : Symbol(keys, Decl(keyofAndIndexedAccess.ts, 364, 23)) result = result[k]; ->result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 366, 7)) ->result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 366, 7)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 367, 12)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 365, 7)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 365, 7)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 366, 12)) } return result; ->result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 366, 7)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 365, 7)) } type Thing = { ->Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 371, 1)) +>Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 370, 1)) a: { x: number, y: string }, ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 373, 14)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 374, 8)) ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 374, 19)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 372, 14)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 373, 8)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 373, 19)) b: boolean ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 374, 32)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 373, 32)) }; function f1(thing: Thing) { ->f1 : Symbol(f1, Decl(keyofAndIndexedAccess.ts, 376, 2)) ->thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 379, 12)) ->Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 371, 1)) +>f1 : Symbol(f1, Decl(keyofAndIndexedAccess.ts, 375, 2)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 378, 12)) +>Thing : Symbol(Thing, Decl(keyofAndIndexedAccess.ts, 370, 1)) let x1 = path(thing, 'a'); // { x: number, y: string } ->x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 380, 7)) ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 379, 12)) +>x1 : Symbol(x1, Decl(keyofAndIndexedAccess.ts, 379, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 378, 12)) let x2 = path(thing, 'a', 'y'); // string ->x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 381, 7)) ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 379, 12)) +>x2 : Symbol(x2, Decl(keyofAndIndexedAccess.ts, 380, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 378, 12)) let x3 = path(thing, 'b'); // boolean ->x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 382, 7)) ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 379, 12)) +>x3 : Symbol(x3, Decl(keyofAndIndexedAccess.ts, 381, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 378, 12)) let x4 = path(thing, ...['a', 'x']); // any ->x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 383, 7)) ->path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 357, 1), Decl(keyofAndIndexedAccess.ts, 361, 62), Decl(keyofAndIndexedAccess.ts, 362, 100), Decl(keyofAndIndexedAccess.ts, 363, 142), Decl(keyofAndIndexedAccess.ts, 364, 59)) ->thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 379, 12)) +>x4 : Symbol(x4, Decl(keyofAndIndexedAccess.ts, 382, 7)) +>path : Symbol(path, Decl(keyofAndIndexedAccess.ts, 356, 1), Decl(keyofAndIndexedAccess.ts, 360, 62), Decl(keyofAndIndexedAccess.ts, 361, 100), Decl(keyofAndIndexedAccess.ts, 362, 142), Decl(keyofAndIndexedAccess.ts, 363, 59)) +>thing : Symbol(thing, Decl(keyofAndIndexedAccess.ts, 378, 12)) } // Repro from comment in #12114 const assignTo2 = (object: T, key1: K1, key2: K2) => ->assignTo2 : Symbol(assignTo2, Decl(keyofAndIndexedAccess.ts, 388, 5)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 388, 19)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 388, 21)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 388, 19)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 388, 41)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 388, 19)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 388, 21)) ->object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 388, 66)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 388, 19)) ->key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 388, 76)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 388, 21)) ->key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 388, 86)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 388, 41)) +>assignTo2 : Symbol(assignTo2, Decl(keyofAndIndexedAccess.ts, 387, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 387, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 387, 21)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 387, 19)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 387, 41)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 387, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 387, 21)) +>object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 387, 66)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 387, 19)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 387, 76)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 387, 21)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 387, 86)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 387, 41)) (value: T[K1][K2]) => object[key1][key2] = value; ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 389, 5)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 388, 19)) ->K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 388, 21)) ->K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 388, 41)) ->object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 388, 66)) ->key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 388, 76)) ->key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 388, 86)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 389, 5)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 388, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 387, 19)) +>K1 : Symbol(K1, Decl(keyofAndIndexedAccess.ts, 387, 21)) +>K2 : Symbol(K2, Decl(keyofAndIndexedAccess.ts, 387, 41)) +>object : Symbol(object, Decl(keyofAndIndexedAccess.ts, 387, 66)) +>key1 : Symbol(key1, Decl(keyofAndIndexedAccess.ts, 387, 76)) +>key2 : Symbol(key2, Decl(keyofAndIndexedAccess.ts, 387, 86)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 388, 5)) // Modified repro from #12573 declare function one(handler: (t: T) => void): T ->one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 389, 53)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 393, 21)) ->handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 393, 24)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 393, 34)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 393, 21)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 393, 21)) +>one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 388, 53)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 392, 21)) +>handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 392, 24)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 392, 34)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 392, 21)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 392, 21)) var empty = one(() => {}) // inferred as {}, expected ->empty : Symbol(empty, Decl(keyofAndIndexedAccess.ts, 394, 3)) ->one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 389, 53)) +>empty : Symbol(empty, Decl(keyofAndIndexedAccess.ts, 393, 3)) +>one : Symbol(one, Decl(keyofAndIndexedAccess.ts, 388, 53)) type Handlers = { [K in keyof T]: (t: T[K]) => void } ->Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 394, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 14)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 396, 22)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 14)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 396, 38)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 14)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 396, 22)) +>Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 393, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 395, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 395, 22)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 395, 14)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 395, 38)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 395, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 395, 22)) declare function on(handlerHash: Handlers): T ->on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 396, 56)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 397, 20)) ->handlerHash : Symbol(handlerHash, Decl(keyofAndIndexedAccess.ts, 397, 23)) ->Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 394, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 397, 20)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 397, 20)) +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 395, 56)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 20)) +>handlerHash : Symbol(handlerHash, Decl(keyofAndIndexedAccess.ts, 396, 23)) +>Handlers : Symbol(Handlers, Decl(keyofAndIndexedAccess.ts, 393, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 20)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 396, 20)) var hashOfEmpty1 = on({ test: () => {} }); // {} ->hashOfEmpty1 : Symbol(hashOfEmpty1, Decl(keyofAndIndexedAccess.ts, 398, 3)) ->on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 396, 56)) ->test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 398, 23)) +>hashOfEmpty1 : Symbol(hashOfEmpty1, Decl(keyofAndIndexedAccess.ts, 397, 3)) +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 395, 56)) +>test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 397, 23)) var hashOfEmpty2 = on({ test: (x: boolean) => {} }); // { test: boolean } ->hashOfEmpty2 : Symbol(hashOfEmpty2, Decl(keyofAndIndexedAccess.ts, 399, 3)) ->on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 396, 56)) ->test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 399, 23)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 399, 31)) +>hashOfEmpty2 : Symbol(hashOfEmpty2, Decl(keyofAndIndexedAccess.ts, 398, 3)) +>on : Symbol(on, Decl(keyofAndIndexedAccess.ts, 395, 56)) +>test : Symbol(test, Decl(keyofAndIndexedAccess.ts, 398, 23)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 398, 31)) // Repro from #12624 interface Options1 { ->Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 399, 52)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 403, 19)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 403, 24)) +>Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 398, 52)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 402, 19)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 402, 24)) data?: Data ->data : Symbol(Options1.data, Decl(keyofAndIndexedAccess.ts, 403, 36)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 403, 19)) +>data : Symbol(Options1.data, Decl(keyofAndIndexedAccess.ts, 402, 36)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 402, 19)) computed?: Computed; ->computed : Symbol(Options1.computed, Decl(keyofAndIndexedAccess.ts, 404, 15)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 403, 24)) +>computed : Symbol(Options1.computed, Decl(keyofAndIndexedAccess.ts, 403, 15)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 402, 24)) } declare class Component1 { ->Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 406, 1)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 408, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 408, 30)) +>Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 405, 1)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 407, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 407, 30)) constructor(options: Options1); ->options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 409, 16)) ->Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 399, 52)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 408, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 408, 30)) +>options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 408, 16)) +>Options1 : Symbol(Options1, Decl(keyofAndIndexedAccess.ts, 398, 52)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 407, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 407, 30)) get(key: K): (Data & Computed)[K]; ->get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 409, 51)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 410, 8)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 408, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 408, 30)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 410, 43)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 410, 8)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 408, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 408, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 410, 8)) +>get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 408, 51)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 409, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 407, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 407, 30)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 409, 43)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 409, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 407, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 407, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 409, 8)) } let c1 = new Component1({ ->c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 413, 3)) ->Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 406, 1)) +>c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 412, 3)) +>Component1 : Symbol(Component1, Decl(keyofAndIndexedAccess.ts, 405, 1)) data: { ->data : Symbol(data, Decl(keyofAndIndexedAccess.ts, 413, 25)) +>data : Symbol(data, Decl(keyofAndIndexedAccess.ts, 412, 25)) hello: "" ->hello : Symbol(hello, Decl(keyofAndIndexedAccess.ts, 414, 11)) +>hello : Symbol(hello, Decl(keyofAndIndexedAccess.ts, 413, 11)) } }); c1.get("hello"); ->c1.get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 409, 51)) ->c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 413, 3)) ->get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 409, 51)) +>c1.get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 408, 51)) +>c1 : Symbol(c1, Decl(keyofAndIndexedAccess.ts, 412, 3)) +>get : Symbol(Component1.get, Decl(keyofAndIndexedAccess.ts, 408, 51)) // Repro from #12625 interface Options2 { ->Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 419, 16)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 423, 19)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 423, 24)) +>Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 418, 16)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 422, 19)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 422, 24)) data?: Data ->data : Symbol(Options2.data, Decl(keyofAndIndexedAccess.ts, 423, 36)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 423, 19)) +>data : Symbol(Options2.data, Decl(keyofAndIndexedAccess.ts, 422, 36)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 422, 19)) computed?: Computed; ->computed : Symbol(Options2.computed, Decl(keyofAndIndexedAccess.ts, 424, 15)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 423, 24)) +>computed : Symbol(Options2.computed, Decl(keyofAndIndexedAccess.ts, 423, 15)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 422, 24)) } declare class Component2 { ->Component2 : Symbol(Component2, Decl(keyofAndIndexedAccess.ts, 426, 1)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 428, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 428, 30)) +>Component2 : Symbol(Component2, Decl(keyofAndIndexedAccess.ts, 425, 1)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 427, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 427, 30)) constructor(options: Options2); ->options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 429, 16)) ->Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 419, 16)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 428, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 428, 30)) +>options : Symbol(options, Decl(keyofAndIndexedAccess.ts, 428, 16)) +>Options2 : Symbol(Options2, Decl(keyofAndIndexedAccess.ts, 418, 16)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 427, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 427, 30)) get(key: K): (Data & Computed)[K]; ->get : Symbol(Component2.get, Decl(keyofAndIndexedAccess.ts, 429, 51)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 430, 8)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 428, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 428, 30)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 430, 47)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 430, 8)) ->Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 428, 25)) ->Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 428, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 430, 8)) +>get : Symbol(Component2.get, Decl(keyofAndIndexedAccess.ts, 428, 51)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 429, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 427, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 427, 30)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 429, 47)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 429, 8)) +>Data : Symbol(Data, Decl(keyofAndIndexedAccess.ts, 427, 25)) +>Computed : Symbol(Computed, Decl(keyofAndIndexedAccess.ts, 427, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 429, 8)) } // Repro from #12641 interface R { ->R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 431, 1)) +>R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 430, 1)) p: number; ->p : Symbol(R.p, Decl(keyofAndIndexedAccess.ts, 435, 13)) +>p : Symbol(R.p, Decl(keyofAndIndexedAccess.ts, 434, 13)) } function f(p: K) { ->f : Symbol(f, Decl(keyofAndIndexedAccess.ts, 437, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 439, 11)) ->R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 431, 1)) ->p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 439, 30)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 439, 11)) +>f : Symbol(f, Decl(keyofAndIndexedAccess.ts, 436, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 438, 11)) +>R : Symbol(R, Decl(keyofAndIndexedAccess.ts, 430, 1)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 438, 30)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 438, 11)) let a: any; ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 440, 7)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 439, 7)) a[p].add; // any ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 440, 7)) ->p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 439, 30)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 439, 7)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 438, 30)) } // Repro from #12651 type MethodDescriptor = { ->MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 442, 1)) +>MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 441, 1)) name: string; ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 446, 25)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 445, 25)) args: any[]; ->args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 447, 14)) +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 446, 14)) returnValue: any; ->returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 448, 13)) +>returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 447, 13)) } declare function dispatchMethod(name: M['name'], args: M['args']): M['returnValue']; ->dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 450, 1)) ->M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 452, 32)) ->MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 442, 1)) ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 452, 60)) ->M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 452, 32)) ->args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 452, 76)) ->M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 452, 32)) ->M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 452, 32)) +>dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 449, 1)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 451, 32)) +>MethodDescriptor : Symbol(MethodDescriptor, Decl(keyofAndIndexedAccess.ts, 441, 1)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 451, 60)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 451, 32)) +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 451, 76)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 451, 32)) +>M : Symbol(M, Decl(keyofAndIndexedAccess.ts, 451, 32)) type SomeMethodDescriptor = { ->SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 452, 112)) +>SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 451, 112)) name: "someMethod"; ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 454, 29)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 453, 29)) args: [string, number]; ->args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 455, 20)) +>args : Symbol(args, Decl(keyofAndIndexedAccess.ts, 454, 20)) returnValue: string[]; ->returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 456, 24)) +>returnValue : Symbol(returnValue, Decl(keyofAndIndexedAccess.ts, 455, 24)) } let result = dispatchMethod("someMethod", ["hello", 35]); ->result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 460, 3)) ->dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 450, 1)) ->SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 452, 112)) +>result : Symbol(result, Decl(keyofAndIndexedAccess.ts, 459, 3)) +>dispatchMethod : Symbol(dispatchMethod, Decl(keyofAndIndexedAccess.ts, 449, 1)) +>SomeMethodDescriptor : Symbol(SomeMethodDescriptor, Decl(keyofAndIndexedAccess.ts, 451, 112)) // Repro from #13073 type KeyTypes = "a" | "b" ->KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 460, 79)) +>KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 459, 79)) let MyThingy: { [key in KeyTypes]: string[] }; ->MyThingy : Symbol(MyThingy, Decl(keyofAndIndexedAccess.ts, 465, 3)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 465, 17)) ->KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 460, 79)) +>MyThingy : Symbol(MyThingy, Decl(keyofAndIndexedAccess.ts, 464, 3)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 464, 17)) +>KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 459, 79)) function addToMyThingy(key: S) { ->addToMyThingy : Symbol(addToMyThingy, Decl(keyofAndIndexedAccess.ts, 465, 46)) ->S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 467, 23)) ->KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 460, 79)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 467, 43)) ->S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 467, 23)) +>addToMyThingy : Symbol(addToMyThingy, Decl(keyofAndIndexedAccess.ts, 464, 46)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 466, 23)) +>KeyTypes : Symbol(KeyTypes, Decl(keyofAndIndexedAccess.ts, 459, 79)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 466, 43)) +>S : Symbol(S, Decl(keyofAndIndexedAccess.ts, 466, 23)) MyThingy[key].push("a"); >MyThingy[key].push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) ->MyThingy : Symbol(MyThingy, Decl(keyofAndIndexedAccess.ts, 465, 3)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 467, 43)) +>MyThingy : Symbol(MyThingy, Decl(keyofAndIndexedAccess.ts, 464, 3)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 466, 43)) >push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) } // Repro from #13102 type Handler = { ->Handler : Symbol(Handler, Decl(keyofAndIndexedAccess.ts, 469, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 473, 13)) +>Handler : Symbol(Handler, Decl(keyofAndIndexedAccess.ts, 468, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 472, 13)) onChange: (name: keyof T) => void; ->onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 473, 19)) ->name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 474, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 473, 13)) +>onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 472, 19)) +>name : Symbol(name, Decl(keyofAndIndexedAccess.ts, 473, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 472, 13)) }; function onChangeGenericFunction(handler: Handler) { ->onChangeGenericFunction : Symbol(onChangeGenericFunction, Decl(keyofAndIndexedAccess.ts, 475, 2)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 477, 33)) ->handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 477, 36)) ->Handler : Symbol(Handler, Decl(keyofAndIndexedAccess.ts, 469, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 477, 33)) ->preset : Symbol(preset, Decl(keyofAndIndexedAccess.ts, 477, 58)) +>onChangeGenericFunction : Symbol(onChangeGenericFunction, Decl(keyofAndIndexedAccess.ts, 474, 2)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 476, 33)) +>handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 476, 36)) +>Handler : Symbol(Handler, Decl(keyofAndIndexedAccess.ts, 468, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 476, 33)) +>preset : Symbol(preset, Decl(keyofAndIndexedAccess.ts, 476, 58)) handler.onChange('preset') ->handler.onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 473, 19)) ->handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 477, 36)) ->onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 473, 19)) +>handler.onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 472, 19)) +>handler : Symbol(handler, Decl(keyofAndIndexedAccess.ts, 476, 36)) +>onChange : Symbol(onChange, Decl(keyofAndIndexedAccess.ts, 472, 19)) } // Repro from #13285 function updateIds, K extends string>( ->updateIds : Symbol(updateIds, Decl(keyofAndIndexedAccess.ts, 479, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 483, 19)) +>updateIds : Symbol(updateIds, Decl(keyofAndIndexedAccess.ts, 478, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 482, 19)) >Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 483, 47)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 483, 47)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 482, 47)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 482, 47)) obj: T, ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 483, 66)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 483, 19)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 482, 66)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 482, 19)) idFields: K[], ->idFields : Symbol(idFields, Decl(keyofAndIndexedAccess.ts, 484, 11)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 483, 47)) +>idFields : Symbol(idFields, Decl(keyofAndIndexedAccess.ts, 483, 11)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 482, 47)) idMapping: { [oldId: string]: string } ->idMapping : Symbol(idMapping, Decl(keyofAndIndexedAccess.ts, 485, 18)) ->oldId : Symbol(oldId, Decl(keyofAndIndexedAccess.ts, 486, 18)) +>idMapping : Symbol(idMapping, Decl(keyofAndIndexedAccess.ts, 484, 18)) +>oldId : Symbol(oldId, Decl(keyofAndIndexedAccess.ts, 485, 18)) ): Record { >Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 483, 47)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 482, 47)) for (const idField of idFields) { ->idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 488, 14)) ->idFields : Symbol(idFields, Decl(keyofAndIndexedAccess.ts, 484, 11)) +>idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 487, 14)) +>idFields : Symbol(idFields, Decl(keyofAndIndexedAccess.ts, 483, 11)) const newId = idMapping[obj[idField]]; ->newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 489, 13)) ->idMapping : Symbol(idMapping, Decl(keyofAndIndexedAccess.ts, 485, 18)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 483, 66)) ->idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 488, 14)) +>newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 488, 13)) +>idMapping : Symbol(idMapping, Decl(keyofAndIndexedAccess.ts, 484, 18)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 482, 66)) +>idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 487, 14)) if (newId) { ->newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 489, 13)) +>newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 488, 13)) obj[idField] = newId; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 483, 66)) ->idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 488, 14)) ->newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 489, 13)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 482, 66)) +>idField : Symbol(idField, Decl(keyofAndIndexedAccess.ts, 487, 14)) +>newId : Symbol(newId, Decl(keyofAndIndexedAccess.ts, 488, 13)) } } return obj; ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 483, 66)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 482, 66)) } // Repro from #13285 function updateIds2( ->updateIds2 : Symbol(updateIds2, Decl(keyofAndIndexedAccess.ts, 495, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 499, 20)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 499, 33)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 499, 54)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 499, 20)) +>updateIds2 : Symbol(updateIds2, Decl(keyofAndIndexedAccess.ts, 494, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 498, 20)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 498, 33)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 498, 54)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 498, 20)) obj: T, ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 499, 74)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 499, 20)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 498, 74)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 498, 20)) key: K, ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 500, 11)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 499, 54)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 499, 11)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 498, 54)) stringMap: { [oldId: string]: string } ->stringMap : Symbol(stringMap, Decl(keyofAndIndexedAccess.ts, 501, 11)) ->oldId : Symbol(oldId, Decl(keyofAndIndexedAccess.ts, 502, 18)) +>stringMap : Symbol(stringMap, Decl(keyofAndIndexedAccess.ts, 500, 11)) +>oldId : Symbol(oldId, Decl(keyofAndIndexedAccess.ts, 501, 18)) ) { var x = obj[key]; ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 504, 7)) ->obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 499, 74)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 500, 11)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 503, 7)) +>obj : Symbol(obj, Decl(keyofAndIndexedAccess.ts, 498, 74)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 499, 11)) stringMap[x]; // Should be OK. ->stringMap : Symbol(stringMap, Decl(keyofAndIndexedAccess.ts, 501, 11)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 504, 7)) +>stringMap : Symbol(stringMap, Decl(keyofAndIndexedAccess.ts, 500, 11)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 503, 7)) } // Repro from #13514 declare function head>(list: T): T[0]; ->head : Symbol(head, Decl(keyofAndIndexedAccess.ts, 506, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 510, 22)) +>head : Symbol(head, Decl(keyofAndIndexedAccess.ts, 505, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 509, 22)) >Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->list : Symbol(list, Decl(keyofAndIndexedAccess.ts, 510, 44)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 510, 22)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 510, 22)) +>list : Symbol(list, Decl(keyofAndIndexedAccess.ts, 509, 44)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 509, 22)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 509, 22)) // Repro from #13604 class A { ->A : Symbol(A, Decl(keyofAndIndexedAccess.ts, 510, 59)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 514, 8)) +>A : Symbol(A, Decl(keyofAndIndexedAccess.ts, 509, 59)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 513, 8)) props: T & { foo: string }; ->props : Symbol(A.props, Decl(keyofAndIndexedAccess.ts, 514, 12)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 514, 8)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 515, 13)) +>props : Symbol(A.props, Decl(keyofAndIndexedAccess.ts, 513, 12)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 513, 8)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 514, 13)) } class B extends A<{ x: number}> { ->B : Symbol(B, Decl(keyofAndIndexedAccess.ts, 516, 1)) ->A : Symbol(A, Decl(keyofAndIndexedAccess.ts, 510, 59)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 518, 19)) +>B : Symbol(B, Decl(keyofAndIndexedAccess.ts, 515, 1)) +>A : Symbol(A, Decl(keyofAndIndexedAccess.ts, 509, 59)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 517, 19)) f(p: this["props"]) { ->f : Symbol(B.f, Decl(keyofAndIndexedAccess.ts, 518, 33)) ->p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 519, 3)) +>f : Symbol(B.f, Decl(keyofAndIndexedAccess.ts, 517, 33)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 518, 3)) p.x; ->p.x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 518, 19)) ->p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 519, 3)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 518, 19)) +>p.x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 517, 19)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 518, 3)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 517, 19)) } } // Repro from #13749 class Form { ->Form : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 522, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) +>Form : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 521, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) private childFormFactories: {[K in keyof T]: (v: T[K]) => Form} ->childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 526, 15)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 527, 34)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) ->v : Symbol(v, Decl(keyofAndIndexedAccess.ts, 527, 50)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 527, 34)) ->Form : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 522, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 527, 34)) +>childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 525, 15)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 526, 34)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) +>v : Symbol(v, Decl(keyofAndIndexedAccess.ts, 526, 50)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 526, 34)) +>Form : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 521, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 526, 34)) public set(prop: K, value: T[K]) { ->set : Symbol(Form.set, Decl(keyofAndIndexedAccess.ts, 527, 73)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 529, 15)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 529, 34)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 529, 15)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 529, 42)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 526, 11)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 529, 15)) +>set : Symbol(Form.set, Decl(keyofAndIndexedAccess.ts, 526, 73)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 528, 15)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 528, 34)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 528, 15)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 528, 42)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 525, 11)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 528, 15)) this.childFormFactories[prop](value) ->this.childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 526, 15)) ->this : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 522, 1)) ->childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 526, 15)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 529, 34)) ->value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 529, 42)) +>this.childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 525, 15)) +>this : Symbol(Form, Decl(keyofAndIndexedAccess.ts, 521, 1)) +>childFormFactories : Symbol(Form.childFormFactories, Decl(keyofAndIndexedAccess.ts, 525, 15)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 528, 34)) +>value : Symbol(value, Decl(keyofAndIndexedAccess.ts, 528, 42)) } } // Repro from #13787 class SampleClass

{ ->SampleClass : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 532, 1)) ->P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 536, 18)) +>SampleClass : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 531, 1)) +>P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 535, 18)) public props: Readonly

; ->props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 536, 22)) +>props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 535, 22)) >Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) ->P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 536, 18)) +>P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 535, 18)) constructor(props: P) { ->props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 538, 16)) ->P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 536, 18)) +>props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 537, 16)) +>P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 535, 18)) this.props = Object.freeze(props); ->this.props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 536, 22)) ->this : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 532, 1)) ->props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 536, 22)) +>this.props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 535, 22)) +>this : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 531, 1)) +>props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 535, 22)) >Object.freeze : Symbol(ObjectConstructor.freeze, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >freeze : Symbol(ObjectConstructor.freeze, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 538, 16)) +>props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 537, 16)) } } interface Foo { ->Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 541, 1)) +>Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 540, 1)) foo: string; ->foo : Symbol(Foo.foo, Decl(keyofAndIndexedAccess.ts, 543, 15)) +>foo : Symbol(Foo.foo, Decl(keyofAndIndexedAccess.ts, 542, 15)) } declare function merge(obj1: T, obj2: U): T & U; ->merge : Symbol(merge, Decl(keyofAndIndexedAccess.ts, 545, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 547, 23)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 547, 25)) ->obj1 : Symbol(obj1, Decl(keyofAndIndexedAccess.ts, 547, 29)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 547, 23)) ->obj2 : Symbol(obj2, Decl(keyofAndIndexedAccess.ts, 547, 37)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 547, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 547, 23)) ->U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 547, 25)) +>merge : Symbol(merge, Decl(keyofAndIndexedAccess.ts, 544, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 546, 23)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 546, 25)) +>obj1 : Symbol(obj1, Decl(keyofAndIndexedAccess.ts, 546, 29)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 546, 23)) +>obj2 : Symbol(obj2, Decl(keyofAndIndexedAccess.ts, 546, 37)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 546, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 546, 23)) +>U : Symbol(U, Decl(keyofAndIndexedAccess.ts, 546, 25)) class AnotherSampleClass extends SampleClass { ->AnotherSampleClass : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 547, 54)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 549, 25)) ->SampleClass : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 532, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 549, 25)) ->Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 541, 1)) +>AnotherSampleClass : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 546, 54)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 548, 25)) +>SampleClass : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 531, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 548, 25)) +>Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 540, 1)) constructor(props: T) { ->props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 550, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 549, 25)) +>props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 549, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 548, 25)) const foo: Foo = { foo: "bar" }; ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 551, 13)) ->Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 541, 1)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 551, 26)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 550, 13)) +>Foo : Symbol(Foo, Decl(keyofAndIndexedAccess.ts, 540, 1)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 550, 26)) super(merge(props, foo)); ->super : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 532, 1)) ->merge : Symbol(merge, Decl(keyofAndIndexedAccess.ts, 545, 1)) ->props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 550, 16)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 551, 13)) +>super : Symbol(SampleClass, Decl(keyofAndIndexedAccess.ts, 531, 1)) +>merge : Symbol(merge, Decl(keyofAndIndexedAccess.ts, 544, 1)) +>props : Symbol(props, Decl(keyofAndIndexedAccess.ts, 549, 16)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 550, 13)) } public brokenMethod() { ->brokenMethod : Symbol(AnotherSampleClass.brokenMethod, Decl(keyofAndIndexedAccess.ts, 553, 5)) +>brokenMethod : Symbol(AnotherSampleClass.brokenMethod, Decl(keyofAndIndexedAccess.ts, 552, 5)) this.props.foo.concat; >this.props.foo.concat : Symbol(String.concat, Decl(lib.es5.d.ts, --, --)) ->this.props.foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 543, 15)) ->this.props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 536, 22)) ->this : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 547, 54)) ->props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 536, 22)) ->foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 543, 15)) +>this.props.foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 542, 15)) +>this.props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 535, 22)) +>this : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 546, 54)) +>props : Symbol(SampleClass.props, Decl(keyofAndIndexedAccess.ts, 535, 22)) +>foo : Symbol(foo, Decl(keyofAndIndexedAccess.ts, 542, 15)) >concat : Symbol(String.concat, Decl(lib.es5.d.ts, --, --)) } } new AnotherSampleClass({}); ->AnotherSampleClass : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 547, 54)) +>AnotherSampleClass : Symbol(AnotherSampleClass, Decl(keyofAndIndexedAccess.ts, 546, 54)) // Positive repro from #17166 function f3>(t: T, k: K, tk: T[K]): void { ->f3 : Symbol(f3, Decl(keyofAndIndexedAccess.ts, 559, 27)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 562, 12)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 562, 14)) +>f3 : Symbol(f3, Decl(keyofAndIndexedAccess.ts, 558, 27)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 561, 12)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 561, 14)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 562, 12)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 562, 51)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 562, 12)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 562, 56)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 562, 14)) ->tk : Symbol(tk, Decl(keyofAndIndexedAccess.ts, 562, 62)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 562, 12)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 562, 14)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 561, 12)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 561, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 561, 12)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 561, 56)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 561, 14)) +>tk : Symbol(tk, Decl(keyofAndIndexedAccess.ts, 561, 62)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 561, 12)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 561, 14)) for (let key in t) { ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 563, 12)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 562, 51)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 562, 12)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 561, 51)) key = k // ok, K ==> keyof T ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 563, 12)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 562, 56)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 562, 12)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 561, 56)) t[key] = tk; // ok, T[K] ==> T[keyof T] ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 562, 51)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 563, 12)) ->tk : Symbol(tk, Decl(keyofAndIndexedAccess.ts, 562, 62)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 561, 51)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 562, 12)) +>tk : Symbol(tk, Decl(keyofAndIndexedAccess.ts, 561, 62)) } } // # 21185 type Predicates = { ->Predicates : Symbol(Predicates, Decl(keyofAndIndexedAccess.ts, 567, 1)) ->TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 570, 16)) +>Predicates : Symbol(Predicates, Decl(keyofAndIndexedAccess.ts, 566, 1)) +>TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 569, 16)) [T in keyof TaggedRecord]: (variant: TaggedRecord[keyof TaggedRecord]) => variant is TaggedRecord[T] ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 571, 3)) ->TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 570, 16)) ->variant : Symbol(variant, Decl(keyofAndIndexedAccess.ts, 571, 30)) ->TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 570, 16)) ->TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 570, 16)) ->variant : Symbol(variant, Decl(keyofAndIndexedAccess.ts, 571, 30)) ->TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 570, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 571, 3)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 570, 3)) +>TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 569, 16)) +>variant : Symbol(variant, Decl(keyofAndIndexedAccess.ts, 570, 30)) +>TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 569, 16)) +>TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 569, 16)) +>variant : Symbol(variant, Decl(keyofAndIndexedAccess.ts, 570, 30)) +>TaggedRecord : Symbol(TaggedRecord, Decl(keyofAndIndexedAccess.ts, 569, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 570, 3)) } // Repros from #23592 type Example = { [K in keyof T]: T[K]["prop"] }; ->Example : Symbol(Example, Decl(keyofAndIndexedAccess.ts, 572, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 576, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 576, 26)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 576, 13)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 576, 42)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 576, 63)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 576, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 576, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 576, 63)) +>Example : Symbol(Example, Decl(keyofAndIndexedAccess.ts, 571, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 575, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 575, 26)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 575, 13)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 575, 42)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 575, 63)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 575, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 575, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 575, 63)) type Result = Example<{ a: { prop: string }; b: { prop: number } }>; ->Result : Symbol(Result, Decl(keyofAndIndexedAccess.ts, 576, 93)) ->Example : Symbol(Example, Decl(keyofAndIndexedAccess.ts, 572, 1)) ->a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 577, 23)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 577, 28)) ->b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 577, 44)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 577, 49)) +>Result : Symbol(Result, Decl(keyofAndIndexedAccess.ts, 575, 93)) +>Example : Symbol(Example, Decl(keyofAndIndexedAccess.ts, 571, 1)) +>a : Symbol(a, Decl(keyofAndIndexedAccess.ts, 576, 23)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 576, 28)) +>b : Symbol(b, Decl(keyofAndIndexedAccess.ts, 576, 44)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 576, 49)) type Helper2 = { [K in keyof T]: Extract }; ->Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 577, 68)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 579, 21)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 13)) +>Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 576, 68)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 578, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 578, 21)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 578, 13)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 13)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 579, 21)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 579, 51)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 578, 13)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 578, 21)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 578, 51)) type Example2 = { [K in keyof Helper2]: Helper2[K]["prop"] }; ->Example2 : Symbol(Example2, Decl(keyofAndIndexedAccess.ts, 579, 67)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 580, 14)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 580, 22)) ->Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 577, 68)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 580, 14)) ->Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 577, 68)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 580, 14)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 580, 22)) +>Example2 : Symbol(Example2, Decl(keyofAndIndexedAccess.ts, 578, 67)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 579, 22)) +>Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 576, 68)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 14)) +>Helper2 : Symbol(Helper2, Decl(keyofAndIndexedAccess.ts, 576, 68)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 579, 14)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 579, 22)) type Result2 = Example2<{ 1: { prop: string }; 2: { prop: number } }>; ->Result2 : Symbol(Result2, Decl(keyofAndIndexedAccess.ts, 580, 70)) ->Example2 : Symbol(Example2, Decl(keyofAndIndexedAccess.ts, 579, 67)) ->1 : Symbol(1, Decl(keyofAndIndexedAccess.ts, 581, 25)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 581, 30)) ->2 : Symbol(2, Decl(keyofAndIndexedAccess.ts, 581, 46)) ->prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 581, 51)) +>Result2 : Symbol(Result2, Decl(keyofAndIndexedAccess.ts, 579, 70)) +>Example2 : Symbol(Example2, Decl(keyofAndIndexedAccess.ts, 578, 67)) +>1 : Symbol(1, Decl(keyofAndIndexedAccess.ts, 580, 25)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 580, 30)) +>2 : Symbol(2, Decl(keyofAndIndexedAccess.ts, 580, 46)) +>prop : Symbol(prop, Decl(keyofAndIndexedAccess.ts, 580, 51)) // Repro from #23618 type DBBoolTable = { [k in K]: 0 | 1 } ->DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 581, 70)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 585, 17)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 585, 40)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 585, 17)) +>DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 580, 70)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 584, 17)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 584, 40)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 584, 17)) enum Flag { ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 585, 56)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 584, 56)) FLAG_1 = "flag_1", ->FLAG_1 : Symbol(Flag.FLAG_1, Decl(keyofAndIndexedAccess.ts, 586, 11)) +>FLAG_1 : Symbol(Flag.FLAG_1, Decl(keyofAndIndexedAccess.ts, 585, 11)) FLAG_2 = "flag_2" ->FLAG_2 : Symbol(Flag.FLAG_2, Decl(keyofAndIndexedAccess.ts, 587, 22)) +>FLAG_2 : Symbol(Flag.FLAG_2, Decl(keyofAndIndexedAccess.ts, 586, 22)) } type SimpleDBRecord = { staticField: number } & DBBoolTable ->SimpleDBRecord : Symbol(SimpleDBRecord, Decl(keyofAndIndexedAccess.ts, 589, 1)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 591, 20)) ->staticField : Symbol(staticField, Decl(keyofAndIndexedAccess.ts, 591, 44)) ->DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 581, 70)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 591, 20)) +>SimpleDBRecord : Symbol(SimpleDBRecord, Decl(keyofAndIndexedAccess.ts, 588, 1)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 590, 20)) +>staticField : Symbol(staticField, Decl(keyofAndIndexedAccess.ts, 590, 44)) +>DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 580, 70)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 590, 20)) function getFlagsFromSimpleRecord(record: SimpleDBRecord, flags: Flag[]) { ->getFlagsFromSimpleRecord : Symbol(getFlagsFromSimpleRecord, Decl(keyofAndIndexedAccess.ts, 591, 86)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 592, 34)) ->record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 592, 55)) ->SimpleDBRecord : Symbol(SimpleDBRecord, Decl(keyofAndIndexedAccess.ts, 589, 1)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 592, 34)) ->flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 592, 84)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 592, 34)) +>getFlagsFromSimpleRecord : Symbol(getFlagsFromSimpleRecord, Decl(keyofAndIndexedAccess.ts, 590, 86)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 591, 34)) +>record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 591, 55)) +>SimpleDBRecord : Symbol(SimpleDBRecord, Decl(keyofAndIndexedAccess.ts, 588, 1)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 591, 34)) +>flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 591, 84)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 591, 34)) return record[flags[0]]; ->record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 592, 55)) ->flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 592, 84)) +>record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 591, 55)) +>flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 591, 84)) } type DynamicDBRecord = ({ dynamicField: number } | { dynamicField: string }) & DBBoolTable ->DynamicDBRecord : Symbol(DynamicDBRecord, Decl(keyofAndIndexedAccess.ts, 594, 1)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 596, 21)) ->dynamicField : Symbol(dynamicField, Decl(keyofAndIndexedAccess.ts, 596, 46)) ->dynamicField : Symbol(dynamicField, Decl(keyofAndIndexedAccess.ts, 596, 73)) ->DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 581, 70)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 596, 21)) +>DynamicDBRecord : Symbol(DynamicDBRecord, Decl(keyofAndIndexedAccess.ts, 593, 1)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 595, 21)) +>dynamicField : Symbol(dynamicField, Decl(keyofAndIndexedAccess.ts, 595, 46)) +>dynamicField : Symbol(dynamicField, Decl(keyofAndIndexedAccess.ts, 595, 73)) +>DBBoolTable : Symbol(DBBoolTable, Decl(keyofAndIndexedAccess.ts, 580, 70)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 595, 21)) function getFlagsFromDynamicRecord(record: DynamicDBRecord, flags: Flag[]) { ->getFlagsFromDynamicRecord : Symbol(getFlagsFromDynamicRecord, Decl(keyofAndIndexedAccess.ts, 596, 117)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 597, 35)) ->record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 597, 56)) ->DynamicDBRecord : Symbol(DynamicDBRecord, Decl(keyofAndIndexedAccess.ts, 594, 1)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 597, 35)) ->flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 597, 86)) ->Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 597, 35)) +>getFlagsFromDynamicRecord : Symbol(getFlagsFromDynamicRecord, Decl(keyofAndIndexedAccess.ts, 595, 117)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 596, 35)) +>record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 596, 56)) +>DynamicDBRecord : Symbol(DynamicDBRecord, Decl(keyofAndIndexedAccess.ts, 593, 1)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 596, 35)) +>flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 596, 86)) +>Flag : Symbol(Flag, Decl(keyofAndIndexedAccess.ts, 596, 35)) return record[flags[0]]; ->record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 597, 56)) ->flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 597, 86)) +>record : Symbol(record, Decl(keyofAndIndexedAccess.ts, 596, 56)) +>flags : Symbol(flags, Decl(keyofAndIndexedAccess.ts, 596, 86)) } // Repro from #21368 interface I { ->I : Symbol(I, Decl(keyofAndIndexedAccess.ts, 599, 1)) +>I : Symbol(I, Decl(keyofAndIndexedAccess.ts, 598, 1)) foo: string; ->foo : Symbol(I.foo, Decl(keyofAndIndexedAccess.ts, 603, 13)) +>foo : Symbol(I.foo, Decl(keyofAndIndexedAccess.ts, 602, 13)) } declare function take(p: T): void; ->take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 605, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 607, 22)) ->p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 607, 25)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 607, 22)) +>take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 604, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 606, 22)) +>p : Symbol(p, Decl(keyofAndIndexedAccess.ts, 606, 25)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 606, 22)) function fn(o: T, k: K) { ->fn : Symbol(fn, Decl(keyofAndIndexedAccess.ts, 607, 37)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 609, 12)) ->I : Symbol(I, Decl(keyofAndIndexedAccess.ts, 599, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 609, 24)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 609, 12)) ->o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 609, 44)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 609, 12)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 609, 49)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 609, 24)) +>fn : Symbol(fn, Decl(keyofAndIndexedAccess.ts, 606, 37)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 608, 12)) +>I : Symbol(I, Decl(keyofAndIndexedAccess.ts, 598, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 608, 24)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 608, 12)) +>o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 608, 44)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 608, 12)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 608, 49)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 608, 24)) take<{} | null | undefined>(o[k]); ->take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 605, 1)) ->o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 609, 44)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 609, 49)) +>take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 604, 1)) +>o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 608, 44)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 608, 49)) take(o[k]); ->take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 605, 1)) ->o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 609, 44)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 609, 49)) +>take : Symbol(take, Decl(keyofAndIndexedAccess.ts, 604, 1)) +>o : Symbol(o, Decl(keyofAndIndexedAccess.ts, 608, 44)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 608, 49)) } // Repro from #23133 class Unbounded { ->Unbounded : Symbol(Unbounded, Decl(keyofAndIndexedAccess.ts, 612, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 616, 16)) +>Unbounded : Symbol(Unbounded, Decl(keyofAndIndexedAccess.ts, 611, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 615, 16)) foo(x: T[keyof T]) { ->foo : Symbol(Unbounded.foo, Decl(keyofAndIndexedAccess.ts, 616, 20)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 617, 8)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 616, 16)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 616, 16)) +>foo : Symbol(Unbounded.foo, Decl(keyofAndIndexedAccess.ts, 615, 20)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 616, 8)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 615, 16)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 615, 16)) let y: {} | undefined | null = x; ->y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 618, 11)) ->x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 617, 8)) +>y : Symbol(y, Decl(keyofAndIndexedAccess.ts, 617, 11)) +>x : Symbol(x, Decl(keyofAndIndexedAccess.ts, 616, 8)) } } // Repro from #23940 interface I7 { ->I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 620, 1)) +>I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 619, 1)) x: any; ->x : Symbol(I7.x, Decl(keyofAndIndexedAccess.ts, 624, 14)) +>x : Symbol(I7.x, Decl(keyofAndIndexedAccess.ts, 623, 14)) } type Foo7 = T; ->Foo7 : Symbol(Foo7, Decl(keyofAndIndexedAccess.ts, 626, 1)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 627, 10)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 627, 10)) +>Foo7 : Symbol(Foo7, Decl(keyofAndIndexedAccess.ts, 625, 1)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 626, 10)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 626, 10)) declare function f7(type: K): Foo7; ->f7 : Symbol(f7, Decl(keyofAndIndexedAccess.ts, 627, 32)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 628, 20)) ->I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 620, 1)) ->type : Symbol(type, Decl(keyofAndIndexedAccess.ts, 628, 40)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 628, 20)) ->Foo7 : Symbol(Foo7, Decl(keyofAndIndexedAccess.ts, 626, 1)) ->I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 620, 1)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 628, 20)) +>f7 : Symbol(f7, Decl(keyofAndIndexedAccess.ts, 626, 32)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 627, 20)) +>I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 619, 1)) +>type : Symbol(type, Decl(keyofAndIndexedAccess.ts, 627, 40)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 627, 20)) +>Foo7 : Symbol(Foo7, Decl(keyofAndIndexedAccess.ts, 625, 1)) +>I7 : Symbol(I7, Decl(keyofAndIndexedAccess.ts, 619, 1)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 627, 20)) // Repro from #21770 type Dict = { [key in T]: number }; ->Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 628, 62)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 632, 10)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 632, 33)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 632, 10)) +>Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 627, 62)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 631, 10)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 631, 33)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 631, 10)) type DictDict = { [key in V]: Dict }; ->DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 632, 53)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 633, 14)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 633, 31)) ->key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 633, 55)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 633, 14)) ->Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 628, 62)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 633, 31)) +>DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 631, 53)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 632, 14)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 632, 31)) +>key : Symbol(key, Decl(keyofAndIndexedAccess.ts, 632, 55)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 632, 14)) +>Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 627, 62)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 632, 31)) function ff1(dd: DictDict, k1: V, k2: T): number { ->ff1 : Symbol(ff1, Decl(keyofAndIndexedAccess.ts, 633, 76)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 635, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 635, 30)) ->dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 635, 49)) ->DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 632, 53)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 635, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 635, 30)) ->k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 635, 68)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 635, 13)) ->k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 635, 75)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 635, 30)) +>ff1 : Symbol(ff1, Decl(keyofAndIndexedAccess.ts, 632, 76)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 634, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 634, 30)) +>dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 634, 49)) +>DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 631, 53)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 634, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 634, 30)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 634, 68)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 634, 13)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 634, 75)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 634, 30)) return dd[k1][k2]; ->dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 635, 49)) ->k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 635, 68)) ->k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 635, 75)) +>dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 634, 49)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 634, 68)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 634, 75)) } function ff2(dd: DictDict, k1: V, k2: T): number { ->ff2 : Symbol(ff2, Decl(keyofAndIndexedAccess.ts, 637, 1)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 639, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 639, 30)) ->dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 639, 49)) ->DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 632, 53)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 639, 13)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 639, 30)) ->k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 639, 68)) ->V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 639, 13)) ->k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 639, 75)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 639, 30)) +>ff2 : Symbol(ff2, Decl(keyofAndIndexedAccess.ts, 636, 1)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 638, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 638, 30)) +>dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 638, 49)) +>DictDict : Symbol(DictDict, Decl(keyofAndIndexedAccess.ts, 631, 53)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 638, 13)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 638, 30)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 638, 68)) +>V : Symbol(V, Decl(keyofAndIndexedAccess.ts, 638, 13)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 638, 75)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 638, 30)) const d: Dict = dd[k1]; ->d : Symbol(d, Decl(keyofAndIndexedAccess.ts, 640, 9)) ->Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 628, 62)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 639, 30)) ->dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 639, 49)) ->k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 639, 68)) +>d : Symbol(d, Decl(keyofAndIndexedAccess.ts, 639, 9)) +>Dict : Symbol(Dict, Decl(keyofAndIndexedAccess.ts, 627, 62)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 638, 30)) +>dd : Symbol(dd, Decl(keyofAndIndexedAccess.ts, 638, 49)) +>k1 : Symbol(k1, Decl(keyofAndIndexedAccess.ts, 638, 68)) return d[k2]; ->d : Symbol(d, Decl(keyofAndIndexedAccess.ts, 640, 9)) ->k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 639, 75)) +>d : Symbol(d, Decl(keyofAndIndexedAccess.ts, 639, 9)) +>k2 : Symbol(k2, Decl(keyofAndIndexedAccess.ts, 638, 75)) } // Repro from #26409 const cf1 = (t: T, k: K) => ->cf1 : Symbol(cf1, Decl(keyofAndIndexedAccess.ts, 646, 5)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 646, 13)) ->P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 646, 26)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 646, 65)) ->cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 646, 48)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 646, 65)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 646, 13)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 646, 85)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 646, 13)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 646, 90)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 646, 65)) +>cf1 : Symbol(cf1, Decl(keyofAndIndexedAccess.ts, 645, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 645, 13)) +>P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 645, 26)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 645, 65)) +>cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 645, 48)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 645, 65)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 645, 13)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 645, 85)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 645, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 645, 90)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 645, 65)) { const s: string = t[k]; ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 648, 9)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 646, 85)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 646, 90)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 647, 9)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 645, 85)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 645, 90)) t.cool; ->t.cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 646, 48)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 646, 85)) ->cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 646, 48)) +>t.cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 645, 48)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 645, 85)) +>cool : Symbol(cool, Decl(keyofAndIndexedAccess.ts, 645, 48)) }; const cf2 = (t: T, k: K) => ->cf2 : Symbol(cf2, Decl(keyofAndIndexedAccess.ts, 652, 5)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 652, 13)) ->P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 652, 26)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 652, 54)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 652, 54)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 652, 13)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 652, 74)) ->T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 652, 13)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 652, 79)) ->K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 652, 54)) +>cf2 : Symbol(cf2, Decl(keyofAndIndexedAccess.ts, 651, 5)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 651, 13)) +>P : Symbol(P, Decl(keyofAndIndexedAccess.ts, 651, 26)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 651, 54)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 651, 54)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 651, 13)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 651, 74)) +>T : Symbol(T, Decl(keyofAndIndexedAccess.ts, 651, 13)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 651, 79)) +>K : Symbol(K, Decl(keyofAndIndexedAccess.ts, 651, 54)) { const s: string = t[k]; ->s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 654, 9)) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 652, 74)) ->k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 652, 79)) +>s : Symbol(s, Decl(keyofAndIndexedAccess.ts, 653, 9)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 651, 74)) +>k : Symbol(k, Decl(keyofAndIndexedAccess.ts, 651, 79)) t.cool; >t.cool : Symbol(cool) ->t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 652, 74)) +>t : Symbol(t, Decl(keyofAndIndexedAccess.ts, 651, 74)) >cool : Symbol(cool) }; diff --git a/tests/baselines/reference/keyofAndIndexedAccess.types b/tests/baselines/reference/keyofAndIndexedAccess.types index feeec10b521..9a14549db4f 100644 --- a/tests/baselines/reference/keyofAndIndexedAccess.types +++ b/tests/baselines/reference/keyofAndIndexedAccess.types @@ -145,8 +145,8 @@ type Q30 = [string, number][0]; // string type Q31 = [string, number][1]; // number >Q31 : number -type Q32 = [string, number][2]; // string | number ->Q32 : undefined +type Q32 = [string, number][number]; // string | number +>Q32 : string | number type Q33 = [string, number][E.A]; // string >Q33 : string @@ -156,15 +156,11 @@ type Q34 = [string, number][E.B]; // number >Q34 : number >E : any -type Q35 = [string, number][E.C]; // string | number ->Q35 : undefined ->E : any +type Q35 = [string, number]["0"]; // string +>Q35 : string -type Q36 = [string, number]["0"]; // string ->Q36 : string - -type Q37 = [string, number]["1"]; // string ->Q37 : number +type Q36 = [string, number]["1"]; // string +>Q36 : number type Q40 = (Shape | Options)["visible"]; // boolean | "yes" | "no" >Q40 : boolean | "yes" | "no" diff --git a/tests/baselines/reference/tupleLengthCheck.errors.txt b/tests/baselines/reference/tupleLengthCheck.errors.txt index f90adbf3525..1c6fe909135 100644 --- a/tests/baselines/reference/tupleLengthCheck.errors.txt +++ b/tests/baselines/reference/tupleLengthCheck.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/types/tuple/tupleLengthCheck.ts(5,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2733: Index '1000' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(5,14): error TS2339: Property '2' does not exist on type '[number, string]'. +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2339: Property '1000' does not exist on type '[number, string]'. ==== tests/cases/conformance/types/tuple/tupleLengthCheck.ts (2 errors) ==== @@ -9,10 +9,10 @@ tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2733: Ind const a1 = a[1] const a2 = a[2] ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. const a3 = a[1000] ~~~~ -!!! error TS2733: Index '1000' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '1000' does not exist on type '[number, string]'. const a4 = rest[1] const a5 = rest[2] diff --git a/tests/baselines/reference/tupleTypes.errors.txt b/tests/baselines/reference/tupleTypes.errors.txt index b0b4d06d518..95daf5ce0ef 100644 --- a/tests/baselines/reference/tupleTypes.errors.txt +++ b/tests/baselines/reference/tupleTypes.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/tupleTypes.ts(11,12): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(11,12): error TS2339: Property '2' does not exist on type '[number, string]'. tests/cases/compiler/tupleTypes.ts(12,5): error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(14,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. Property '0' is missing in type '[]'. @@ -9,7 +9,7 @@ tests/cases/compiler/tupleTypes.ts(17,15): error TS2322: Type 'number' is not as tests/cases/compiler/tupleTypes.ts(18,1): error TS2322: Type '[number, string, number]' is not assignable to type '[number, string]'. Types of property 'length' are incompatible. Type '3' is not assignable to type '2'. -tests/cases/compiler/tupleTypes.ts(35,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/compiler/tupleTypes.ts(35,14): error TS2339: Property '2' does not exist on type '[number, string]'. tests/cases/compiler/tupleTypes.ts(36,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. tests/cases/compiler/tupleTypes.ts(41,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. tests/cases/compiler/tupleTypes.ts(47,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. @@ -37,7 +37,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var t1: string; var t2 = t[2]; // number|string ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. var t2: number|string; ~~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 't2' must be of type 'undefined', but here has type 'string | number'. @@ -79,7 +79,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var tt1: string; var tt2 = tt[2]; ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, string]'. var tt2: number | string; ~~~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 'tt2' must be of type 'undefined', but here has type 'string | number'. diff --git a/tests/baselines/reference/unionsOfTupleTypes1.errors.txt b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt index 0f8f8ea786a..d9cad5f1b11 100644 --- a/tests/baselines/reference/unionsOfTupleTypes1.errors.txt +++ b/tests/baselines/reference/unionsOfTupleTypes1.errors.txt @@ -1,11 +1,14 @@ +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(8,15): error TS2339: Property '2' does not exist on type '[string, number]'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(13,15): error TS2339: Property '2' does not exist on type 'T2'. tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(27,20): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(28,20): error TS2460: Type 'T2' has no property '2'. tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(31,16): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'. tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(32,16): error TS2460: Type 'T2' has no property '2'. -tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2339: Property '2' does not exist on type '[string, number]'. +tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(41,18): error TS2339: Property '2' does not exist on type 'T2'. -==== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts (5 errors) ==== +==== tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts (8 errors) ==== type T1 = [string, number]; type T2 = [boolean] | [string, number]; type T3 = [string, ...number[]]; @@ -14,11 +17,15 @@ tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2733: type T10 = T1[0]; // string type T11 = T1[1]; // number type T12 = T1[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type '[string, number]'. type T1N = T1[number]; // string | number type T20 = T2[0]; // string | boolean type T21 = T2[1]; // number | undefined type T22 = T2[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type 'T2'. type T2N = T2[number]; // string | number | boolean type T30 = T3[0]; // string @@ -52,11 +59,13 @@ tests/cases/conformance/types/tuple/unionsOfTupleTypes1.ts(37,18): error TS2733: let t11 = t1[1]; // number let t12 = t1[2]; // undefined ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[string, number]'. let t1x = t1[x]; // string | number let t20 = t2[0]; // string | boolean let t21 = t2[1]; // number | undefined let t22 = t2[2]; // undefined + ~ +!!! error TS2339: Property '2' does not exist on type 'T2'. let t2x = t2[x]; // string | number | boolean let t30 = t3[0]; // string let t31 = t3[1]; // number From f6ca10565d8fb0a9737b687b85e14ee94ad244d7 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 8 Oct 2018 17:09:48 -0700 Subject: [PATCH 029/262] Fix bug: Ensure JSDoc type range is valid (#27343) --- src/compiler/parser.ts | 2 +- tests/cases/fourslash/editJsdocType.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/editJsdocType.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 056edccdbd2..51e56bbdd98 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6308,7 +6308,7 @@ namespace ts { // Parses out a JSDoc type expression. export function parseJSDocTypeExpression(mayOmitBraces?: boolean): JSDocTypeExpression { - const result = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); + const result = createNode(SyntaxKind.JSDocTypeExpression); const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(SyntaxKind.OpenBraceToken); result.type = doInsideOfContext(NodeFlags.JSDoc, parseJSDocType); diff --git a/tests/cases/fourslash/editJsdocType.ts b/tests/cases/fourslash/editJsdocType.ts new file mode 100644 index 00000000000..4e5de6c5daf --- /dev/null +++ b/tests/cases/fourslash/editJsdocType.ts @@ -0,0 +1,13 @@ +/// + +// @allowJs: true +// @noLib: true + +// @Filename: /a.js +/////** @type/**/ */ +////const x = 0; + +goTo.marker(); +verify.quickInfoIs(""); +edit.insert(" "); +verify.quickInfoIs(""); From ca94d8efd908e9e83671bfd252bf219cbbc844a9 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 9 Oct 2018 07:12:09 -0700 Subject: [PATCH 030/262] Infer from usage better import types (#27626) * Use host to improve SymbolTracker implementation * inferFromUsage: Provide a better moduleResolverHost This produces better paths on import types. --- src/services/codefixes/inferFromUsage.ts | 49 +++++++++++-------- ...nferFromUsageSetterWithInaccessibleType.ts | 2 +- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index ed8939079e3..a8ec514c549 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -25,24 +25,24 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions(context) { - const { sourceFile, program, span: { start }, errorCode, cancellationToken } = context; + const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context; if (isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } const token = getTokenAtPosition(sourceFile, start); let declaration!: Declaration | undefined; - const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ returnTrue); }); + const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { - const { sourceFile, program, cancellationToken } = context; + const { sourceFile, program, cancellationToken, host } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes, (changes, err) => { - doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); @@ -58,7 +58,7 @@ namespace ts.codefix { } } - function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker): Declaration | undefined { + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken) { return undefined; } @@ -69,7 +69,7 @@ namespace ts.codefix { case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((isVariableDeclaration(parent) && markSeen(parent)) || isPropertyDeclaration(parent) || isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); return parent; } return undefined; @@ -77,7 +77,7 @@ namespace ts.codefix { case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { const symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -93,14 +93,14 @@ namespace ts.codefix { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; @@ -109,7 +109,7 @@ namespace ts.codefix { case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (isGetAccessor(containingFunction) && isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; @@ -117,7 +117,7 @@ namespace ts.codefix { // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -127,9 +127,9 @@ namespace ts.codefix { } } - function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, cancellationToken: CancellationToken): void { + function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } @@ -145,7 +145,7 @@ namespace ts.codefix { return false; } - function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): void { + function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } @@ -159,26 +159,27 @@ namespace ts.codefix { zipWith(containingFunction.parameters, types, (parameter, type) => { if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + annotate(changes, sourceFile, parameter, type, program, host); } }); } - function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, cancellationToken: CancellationToken): void { + function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + annotate(changes, sourceFile, param, type, program, host); } } - function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program): void { - const typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); + function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program, host: LanguageServiceHost): void { + const typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, checker: TypeChecker): TypeNode | undefined { + function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => { typeIsAccessible = false; }; const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -189,6 +190,14 @@ namespace ts.codefix { reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts index b56c6e05f69..269f67f7cf7 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleType.ts @@ -18,7 +18,7 @@ verify.codeFix({ description: "Infer type of 'x' from usage", newFileContent: `export class C { - set x(val: Promise) { val; } + set x(val: Promise) { val; } method() { this.x = import("./a"); } }`, }); From 585420e9fae2ee381ed64d7b92cd4b773f0d7ca3 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 9 Oct 2018 08:42:27 -0700 Subject: [PATCH 031/262] Updated callback signature --- src/compiler/sys.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 5aaa331f586..0f90748f3c0 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -846,7 +846,7 @@ namespace ts { } } - type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string) => void; + type FsWatchCallback = (eventName: "rename" | "change", relativeFileName: string | undefined) => void; function createFileWatcherCallback(callback: FsWatchCallback): FileWatcherCallback { return (_fileName, eventKind) => callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); From 1a5e66995a978a3cf0bbf8182729b41095005c6f Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 9 Oct 2018 09:42:43 -0700 Subject: [PATCH 032/262] Don't crash if spawnSync result's stderr is null (#27616) --- src/testRunner/externalCompileRunner.ts | 28 +++++++++++++------------ 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index 704b4677447..a8a240a5161 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -1,6 +1,6 @@ -const fs = require("fs"); -const path = require("path"); -const del = require("del"); +const fs: typeof import("fs") = require("fs"); +const path: typeof import("path") = require("path"); +const del: typeof import("del") = require("del"); interface ExecResult { stdout: Buffer; @@ -49,12 +49,9 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { let types: string[] | undefined; if (fs.existsSync(path.join(cwd, "test.json"))) { const submoduleDir = path.join(cwd, directoryName); - const reset = cp.spawnSync("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (reset.status !== 0) throw new Error(`git reset for ${directoryName} failed: ${reset.stderr.toString()}`); - const clean = cp.spawnSync("git", ["clean", "-f"], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (clean.status !== 0) throw new Error(`git clean for ${directoryName} failed: ${clean.stderr.toString()}`); - const update = cp.spawnSync("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir, timeout, shell: true, stdio }); - if (update.status !== 0) throw new Error(`git submodule update for ${directoryName} failed: ${update.stderr.toString()}`); + exec("git", ["reset", "HEAD", "--hard"], { cwd: submoduleDir }); + exec("git", ["clean", "-f"], { cwd: submoduleDir }); + exec("git", ["submodule", "update", "--init", "--remote", "."], { cwd: submoduleDir }); const config = JSON.parse(fs.readFileSync(path.join(cwd, "test.json"), { encoding: "utf8" })) as UserConfig; ts.Debug.assert(!!config.types, "Bad format from test.json: Types field must be present."); @@ -69,18 +66,23 @@ abstract class ExternalCompileRunnerBase extends RunnerBase { if (fs.existsSync(path.join(cwd, "node_modules"))) { del.sync(path.join(cwd, "node_modules"), { force: true }); } - const install = cp.spawnSync(`npm`, ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", "--ignore-scripts"], { cwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } const args = [path.join(Harness.IO.getWorkspaceRoot(), "built/local/tsc.js")]; if (types) { args.push("--types", types.join(",")); // Also actually install those types (for, eg, the js projects which need node) - const install = cp.spawnSync(`npm`, ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2, shell: true, stdio }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure - if (install.status !== 0) throw new Error(`NPM Install types for ${directoryName} failed: ${install.stderr.toString()}`); + exec("npm", ["i", ...types.map(t => `@types/${t}`), "--no-save", "--ignore-scripts"], { cwd: originalCwd, timeout: timeout / 2 }); // NPM shouldn't take the entire timeout - if it takes a long time, it should be terminated and we should log the failure } args.push("--noEmit"); Harness.Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true }), cwd)); + + function exec(command: string, args: string[], options: { cwd: string, timeout?: number }): void { + const res = cp.spawnSync(command, args, { timeout, shell: true, stdio, ...options }); + if (res.status !== 0) { + throw new Error(`${command} ${args.join(" ")} for ${directoryName} failed: ${res.stderr && res.stderr.toString()}`); + } + } }); }); } From 88d3c6fd5f84916332719fe09b65f61d81873a09 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 9 Oct 2018 10:38:46 -0700 Subject: [PATCH 033/262] inferFromUsage codefix now emits JSDoc in JS files (#27610) * Now adding @type to variable declarations, at least Probably everything else, but not as well. * Improve @param output and add test It's still bad, but at least it's not wrong. * Add some js/inferFromUsage tests and fixes Also, remove redundant is(Set|Get)Accessor functions. * Fix @typedef refactor * Emit JSDoc optional parameters By surrounding the parameter name with brackets. It is super, super ugly right now. * Get rest of existing tests working * Correct location of comments * Handle @param blocks 1. Format multiple params nicely in a single-multiline block. 2. Generate only params that haven't already been documented. Existing documentation is not touched. * Re-add isGet/SetAccessor -- it is part of the API * Move isSet/GetAccessor back to the original location * Oh no I missed a newline and a space * Switch to an object type * A lot of cleanup More to come, though. annotate is only called in annotateVariableDeclaration where we don't know whether we're in JS or not. * Move and delegate to annotateJSDocParameters * Address PR comments * Lint: newline problems!!!! * Switch another call to getNonformattedText * Update baseline missed after merge --- .../transformers/declarations/diagnostics.ts | 2 +- src/harness/fourslash.ts | 8 +- src/services/codefixes/inferFromUsage.ts | 94 ++++++++++++++----- src/services/textChanges.ts | 52 +++++++++- .../fourslash/codeFixInferFromUsageCallJS.ts | 20 ++++ .../fourslash/codeFixInferFromUsageJS.ts | 12 +++ .../codeFixInferFromUsageMember2JS.ts | 14 +++ .../codeFixInferFromUsageMemberJS.ts | 30 ++++++ ...deFixInferFromUsageMultipleParametersJS.ts | 23 +++++ ...FixInferFromUsageNumberIndexSignatureJS.ts | 17 ++++ .../codeFixInferFromUsageOptionalParamJS.ts | 21 +++++ ...FixInferFromUsagePartialParameterListJS.ts | 29 ++++++ .../codeFixInferFromUsagePropertyAccessJS.ts | 34 +++++++ .../codeFixInferFromUsageRestParam2JS.ts | 27 ++++++ .../codeFixInferFromUsageRestParam3JS.ts | 21 +++++ .../codeFixInferFromUsageRestParamJS.ts | 27 ++++++ .../fourslash/codeFixInferFromUsageSetter2.ts | 11 --- .../codeFixInferFromUsageSetterJS.ts | 24 +++++ ...erFromUsageSetterWithInaccessibleTypeJS.ts | 36 +++++++ .../codeFixInferFromUsageSingleLineClassJS.ts | 19 ++++ ...FixInferFromUsageStringIndexSignatureJS.ts | 23 +++++ .../codeFixInferFromUsageVariable2JS.ts | 18 ++++ .../codeFixInferFromUsageVariableJS.ts | 14 +++ .../fourslash/codeFixInferFromUsage_allJS.ts | 48 ++++++++++ 24 files changed, 584 insertions(+), 40 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageCallJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts delete mode 100644 tests/cases/fourslash/codeFixInferFromUsageSetter2.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsage_allJS.ts diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 53b5750a1ed..94d6994f8d2 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -466,4 +466,4 @@ namespace ts { }; } } -} \ No newline at end of file +} diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index ccd7aa1d067..dc28871d1c0 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2516,10 +2516,10 @@ Actual: ${stringify(fullActual)}`); * @param expectedContents The contents of the file after the fixes are applied. * @param fileName The file to check. If not supplied, the current open file is used. */ - public verifyFileAfterCodeFix(expectedContents: string, fileName?: string) { + public verifyFileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { fileName = fileName ? fileName : this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixes(fileName)); + this.applyCodeActions(this.getCodeFixes(fileName), index); const actualContents: string = this.getFileContent(fileName); if (this.removeWhitespace(actualContents) !== this.removeWhitespace(expectedContents)) { @@ -4388,6 +4388,10 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } + public fileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { + this.state.verifyFileAfterCodeFix(expectedContents, fileName, index); + } + public codeFixAll(options: VerifyCodeFixAllOptions): void { this.state.verifyCodeFixAll(options); } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index a8ec514c549..62f73df9f80 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -26,9 +26,6 @@ namespace ts.codefix { errorCodes, getCodeActions(context) { const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context; - if (isSourceFileJS(sourceFile)) { - return undefined; // TODO: GH#20113 - } const token = getTokenAtPosition(sourceFile, start); let declaration!: Declaration | undefined; @@ -50,7 +47,7 @@ namespace ts.codefix { function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { switch (errorCode) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return isSetAccessor(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return isSetAccessorDeclaration(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return Diagnostics.Infer_parameter_types_from_usage; default: @@ -59,7 +56,7 @@ namespace ts.codefix { } function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { - if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken) { + if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } @@ -72,6 +69,14 @@ namespace ts.codefix { annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); return parent; } + if (isPropertyAccessExpression(parent)) { + const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + const typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } + return parent; + } return undefined; case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { @@ -92,7 +97,7 @@ namespace ts.codefix { switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (isSetAccessor(containingFunction)) { + if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } @@ -108,7 +113,7 @@ namespace ts.codefix { // Get Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (isGetAccessor(containingFunction) && isIdentifier(containingFunction.name)) { + if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } @@ -116,7 +121,7 @@ namespace ts.codefix { // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (isSetAccessor(containingFunction)) { + if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } @@ -150,18 +155,23 @@ namespace ts.codefix { return; } - const types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(p => isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; - } + const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(p => ({ + declaration: p, + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + })); + Debug.assert(containingFunction.parameters.length === parameterInferences.length); - zipWith(containingFunction.parameters, types, (parameter, type) => { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program, host); + if (isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (const { declaration, type } of parameterInferences) { + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { @@ -169,16 +179,37 @@ namespace ts.codefix { if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program, host); + if (isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program, host: LanguageServiceHost): void { const typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); - if (typeNode) changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + if (typeNode) { + if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ParameterInference[], program: Program, host: LanguageServiceHost): void { + const result = mapDefined(parameterInferences, inference => { + const param = inference.declaration; + const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !getJSDocType(param) ? { ...inference, typeNode } : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + + function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => { typeIsAccessible = false; }; @@ -212,7 +243,7 @@ namespace ts.codefix { return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); } - function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { switch (containingFunction.kind) { case SyntaxKind.Constructor: case SyntaxKind.FunctionExpression: @@ -228,6 +259,13 @@ namespace ts.codefix { } } + interface ParameterInference { + declaration: ParameterDeclaration; + type?: Type; + typeNode?: TypeNode; + isOptional?: boolean; + } + namespace InferFromReference { interface CallContext { argumentTypes: Type[]; @@ -255,7 +293,7 @@ namespace ts.codefix { return getTypeFromUsageContext(usageContext, checker); } - export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): (Type | undefined)[] | undefined { + export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): ParameterInference[] | undefined { if (references.length === 0) { return undefined; } @@ -274,8 +312,10 @@ namespace ts.codefix { return callContexts && declaration.parameters.map((parameter, parameterIndex) => { const types: Type[] = []; const isRest = isRestParameter(parameter); + let isOptional = false; for (const callContext of callContexts) { if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = isInJSFile(declaration); continue; } @@ -289,10 +329,14 @@ namespace ts.codefix { } } if (!types.length) { - return undefined; + return { declaration: parameter }; } const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index abd153f0bac..0d45039f5b1 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -209,6 +209,12 @@ namespace ts.textChanges { export type TypeAnnotatable = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature; + interface JSDocParameter { + declaration: ParameterDeclaration; + typeNode: TypeNode; + isOptional?: boolean; + } + export class ChangeTracker { private readonly changes: Change[] = []; private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; @@ -339,6 +345,12 @@ namespace ts.textChanges { this.insertText(sourceFile, token.getStart(sourceFile), text); } + public insertCommentThenNewline(sourceFile: SourceFile, character: number, position: number, commentText: string): void { + const token = getTouchingToken(sourceFile, position); + const text = "/**" + commentText + "*/" + this.newLineCharacter + repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + } + public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string) { this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text }); } @@ -347,6 +359,23 @@ namespace ts.textChanges { this.replaceRangeWithText(sourceFile, createRange(pos), text); } + public tryInsertJSDocParameters(sourceFile: SourceFile, parameters: JSDocParameter[]) { + if (parameters.length === 0) { + return; + } + const parent = parameters[0].declaration.parent; + const indent = getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + let commentText = "\n"; + for (const { declaration, typeNode, isOptional } of parameters) { + if (isIdentifier(declaration.name)) { + const printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); + } + /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void { let endNode: Node | undefined; @@ -365,6 +394,27 @@ namespace ts.textChanges { this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); } + public tryInsertJSDocType(sourceFile: SourceFile, node: Node, type: TypeNode): void { + const printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + let commentText; + if (isGetAccessorDeclaration(node)) { + commentText = ` @return {${printed}} `; + } + else { + commentText = ` @type {${printed}} `; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + } + + private printJSDocParameter(indent: number, printed: string, name: Identifier, isOptionalParameter: boolean | undefined) { + let printName = unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = `[${printName}]`; + } + return repeatString(" ", indent) + ` * @param {${printed}} ${printName}\n`; + } + public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray): void { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter const start = (findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile) || first(node.parameters)).getStart(sourceFile); @@ -806,7 +856,7 @@ namespace ts.textChanges { } /** Note: output node may be mutated input node. */ - function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { + export function getNonformattedText(node: Node, sourceFile: SourceFile | undefined, newLineCharacter: string): { text: string, node: Node } { const writer = new Writer(newLineCharacter); const newLine = newLineCharacter === "\n" ? NewLineKind.LineFeed : NewLineKind.CarriageReturnLineFeed; createPrinter({ newLine, neverAsciiEscape: true }, writer).writeNode(EmitHint.Unspecified, node, sourceFile, writer); diff --git a/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts b/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts new file mode 100644 index 00000000000..fa7eb5ee671 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageCallJS.ts @@ -0,0 +1,20 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: test.js +////function wat(b) { +//// b(); +////} + +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", + newFileContent: +`/** + * @param {() => void} b + */ +function wat(b) { + b(); +}`}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageJS.ts b/tests/cases/fourslash/codeFixInferFromUsageJS.ts new file mode 100644 index 00000000000..62c9d1bf90b --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageJS.ts @@ -0,0 +1,12 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: test.js +////[|var foo;|] +////function f() { +//// foo += 2; +////} + +verify.rangeAfterCodeFix("/** @type {number} */\nvar foo;",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts new file mode 100644 index 00000000000..dc52286a906 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts @@ -0,0 +1,14 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +/////** @typedef {{ [|p |]}} I */ +/////** @type {I} */ +////var i; +////i.p = 0; + + +verify.rangeAfterCodeFix("p: number", undefined, undefined, 1); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts new file mode 100644 index 00000000000..cb86347cb9f --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts @@ -0,0 +1,30 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js +////class C { +//// constructor() { +//// [|this.p|] = undefined; +//// } +//// method() { +//// this.p.push(1) +//// } +////} + + +// Note: Should be number[] | undefined, but inference currently privileges assignments +// over usage (even when the only result is undefined) and infers only undefined. +verify.fileAfterCodeFix( +`class C { + constructor() { + /** @type {undefined} */ + this.p = undefined; + } + method() { + this.p.push(1) + } +} +`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts new file mode 100644 index 00000000000..8f544df4323 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +//// function f([|a, b, c, d, e = 0, ...d |]) { +//// } +//// f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string"); + + +verify.fileAfterCodeFix( +`/** + * @param {number} a + * @param {string} b + * @param {{ a: number; }} c + * @param {{ shouldNotBeHere: number; }} d + * @param {(string | number)[]} d + */ +function f(a, b, c, d, e = 0, ...d ) { +} +f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");`, undefined, 6); diff --git a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts new file mode 100644 index 00000000000..b6b8fe4c25f --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts @@ -0,0 +1,17 @@ +/// +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +////function f([|a|]) { +//// return a[0] + 1; +////} + +verify.fileAfterCodeFix( +`/** + * @param {number[]} a + */ +function f(a) { + return a[0] + 1; +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts new file mode 100644 index 00000000000..cc00c1ddb5d --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts @@ -0,0 +1,21 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +////function f([|a|]){ +//// a; +////} +////f(); +////f(1); + +verify.fileAfterCodeFix( +`/** + * @param {number} [a] + */ +function f(a) { + a; +} +f(); +f(1);`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts new file mode 100644 index 00000000000..67795b6a178 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts @@ -0,0 +1,29 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js +/////** +//// * @param {*} y +//// */ +////function f(x, y, z) { +//// return x +////} +////f(1, 2, 3) + +verify.fileAfterCodeFix( +` +/** + * @param {*} y + */ +/** + * @param {number} x + * @param {number} z + */ +function f(x, y, z) { + return x +} +f(1, 2, 3) +`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts new file mode 100644 index 00000000000..a52c66312fc --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts @@ -0,0 +1,34 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js + +////function foo([|a, m, x|]) { +//// a.b.c; +//// +//// var numeric = 0; +//// numeric = m.n(); +//// +//// x.y.z +//// x.y.z.push(0); +//// return x.y.z +////} + +verify.fileAfterCodeFix( +`/** + * @param {{ b: { c: any; }; }} a + * @param {{ n: () => number; }} m + * @param {{ y: { z: number[]; }; }} x + */ +function foo(a, m, x) { + a.b.c; + + var numeric = 0; + numeric = m.n(); + + x.y.z + x.y.z.push(0); + return x.y.z +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts new file mode 100644 index 00000000000..0504816c597 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts @@ -0,0 +1,27 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a, [|...rest|]){ +//// a; rest; +////} +////f(1); +////f(2, "s1"); +////f(3, false, "s2"); +////f(4, "s1", "s2", false, "s4"); + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {(string | boolean)[]} rest + */ +function f(a, ...rest){ + a; rest; +} +f(1); +f(2, "s1"); +f(3, false, "s2"); +f(4, "s1", "s2", false, "s4");`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts new file mode 100644 index 00000000000..bda7090ba06 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts @@ -0,0 +1,21 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a, [|...rest |]){ +//// a; +//// rest.push(22); +////} + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {number[]} rest + */ +function f(a, ...rest){ + a; + rest.push(22); +}`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts new file mode 100644 index 00000000000..36582bfa7db --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts @@ -0,0 +1,27 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +/////** @param {number} a */ +////function f(a: number, [|...rest|]){ +//// a; rest; +////} +////f(1); +////f(2, "s1"); +////f(3, "s1", "s2"); +////f(3, "s1", "s2", "s3", "s4"); + +verify.fileAfterCodeFix( +`/** @param {number} a */ +/** + * @param {string[]} rest + */ +function f(a: number, ...rest){ + a; rest; +} +f(1); +f(2, "s1"); +f(3, "s1", "s2"); +f(3, "s1", "s2", "s3", "s4");`, undefined, 4); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts b/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts deleted file mode 100644 index d058bc2787c..00000000000 --- a/tests/cases/fourslash/codeFixInferFromUsageSetter2.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -// @noImplicitAny: true -////class C { -//// set [|x(v)|] { -//// v; -//// } -////} -////(new C).x = 1; - -verify.rangeAfterCodeFix("x(v: number)", undefined, undefined, 1); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts new file mode 100644 index 00000000000..71621f48239 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @Filename: important.js +////class C { +//// set [|x(v)|] { +//// v; +//// } +////} +////(new C).x = 1; + +verify.fileAfterCodeFix( +` +class C { + /** + * @param {number} v + */ + set x(v) { + v; + } +} +(new C).x = 1;`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts new file mode 100644 index 00000000000..7620b969234 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts @@ -0,0 +1,36 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true + +// @Filename: /promise.d.ts +////interface Promise { +////} +////declare var Promise: Promise; + +// @Filename: /a.js +////export class D {} +////export default new D(); + +// @Filename: /b.js +////export class C { +//// set [|x|](val) { val; } +//// method() { this.x = import("./a"); } +////} + +goTo.file("/b.js"); +verify.codeFix({ + index: 2, + description: "Infer type of 'x' from usage", + newFileContent: +`export class C { + /** + * @param {Promise} val + */ + set x(val) { val; } + method() { this.x = import("./a"); } +}`, +}); + diff --git a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts new file mode 100644 index 00000000000..f78a70aa14a --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts @@ -0,0 +1,19 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js +////class C {m(x) {return x;}} +////var c = new C() +////c.m(1) + +verify.fileAfterCodeFix( +` +class C {/** + * @param {number} x + */ + m(x) {return x;}} +var c = new C() +c.m(1)`, undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts new file mode 100644 index 00000000000..5182e80969e --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts @@ -0,0 +1,23 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js + +////function f([|a|]) { +//// return a['hi']; +////} + +verify.codeFix({ + index: 2, + description: "Infer parameter types from usage", + newFileContent: +`/** + * @param {{ [x: string]: any; }} a + */ +function f(a) { + return a['hi']; +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts new file mode 100644 index 00000000000..0e88a30b96b --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts @@ -0,0 +1,18 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js +////[|var x; +////function f() { +//// x++; +////}|] + +verify.rangeAfterCodeFix(`/** @type {number} */ +var x; +function f() { + x++; +} +`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts new file mode 100644 index 00000000000..8e96fd08916 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts @@ -0,0 +1,14 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js + +////[|var x;|] +////function f() { +//// x++; +////} + +verify.rangeAfterCodeFix("/** @type {number } */\nvar x;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); diff --git a/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts b/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts new file mode 100644 index 00000000000..00e44660a98 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsage_allJS.ts @@ -0,0 +1,48 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: true +// @Filename: important.js + +////function f(x, y) { +//// x += 0; +//// y += ""; +////} +//// +////function g(z) { +//// return z * 2; +////} +//// +////let x = null; +////function h() { +//// if (!x) x = 2; +////} + +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", + newFileContent: +`/** + * @param {number} x + * @param {string} y + */ +function f(x, y) { + x += 0; + y += ""; +} + +/** + * @param {number} z + */ +function g(z) { + return z * 2; +} + +/** @type {number | null} */ +let x = null; +function h() { + if (!x) x = 2; +}`, +}); From 74392a0e5159d323ac9da101f9a744a83cb9ee48 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 9 Oct 2018 10:42:21 -0700 Subject: [PATCH 034/262] Update user baselines (#27632) --- .../user/chrome-devtools-frontend.log | 23 +++++++++++++++---- tests/baselines/reference/user/lodash.log | 1 + 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index a52834d0d54..77638fea091 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -149,6 +149,7 @@ node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(274,42): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(298,19): error TS2339: Property 'breadcrumb' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(302,23): error TS2339: Property 'tabIndex' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(314,15): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(323,23): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(330,27): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(391,50): error TS2345: Argument of type '0' is not assignable to parameter of type 'string'. @@ -4399,6 +4400,7 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManag node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(247,24): error TS2694: Namespace 'Coverage' has no exported member 'RawLocation'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(248,24): error TS2694: Namespace 'Coverage' has no exported member 'RawLocation'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(255,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(258,34): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(277,18): error TS2339: Property 'uninstallGutter' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(293,16): error TS2339: Property 'uninstallGutter' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(294,16): error TS2339: Property 'installGutter' does not exist on type 'CodeMirrorTextEditor'. @@ -4452,6 +4454,7 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(57,54): node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(141,5): error TS2322: Type 'Timer' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(187,55): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(187,85): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. +node_modules/chrome-devtools-frontend/front_end/coverage/CoverageView.js(231,59): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(12,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(20,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(28,27): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -6251,6 +6254,7 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(44,24): error TS2339: Property 'token' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(46,20): error TS2345: Argument of type 'void' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(46,69): error TS2339: Property 'length' does not exist on type 'void'. +node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(58,26): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(96,3): error TS2554: Expected 2-3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(103,45): error TS2322: Type 'number' is not assignable to type 'boolean'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/FormatterWorker.js(138,3): error TS2554: Expected 2-3 arguments, but got 1. @@ -6442,6 +6446,8 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(918,34): error TS2345: Argument of type 'Uint32Array' is not assignable to parameter of type 'number[]'. Property 'pop' is missing in type 'Uint32Array'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(920,34): error TS2345: Argument of type 'Uint32Array' is not assignable to parameter of type 'number[]'. +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1020,16): error TS2587: JSDoc type 'JSHeapSnapshotEdge' circularly references itself. +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1028,16): error TS2587: JSDoc type 'JSHeapSnapshotRetainerEdge' circularly references itself. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1045,5): error TS2322: Type 'void' is not assignable to type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1083,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1086,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. @@ -6776,6 +6782,7 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(199,80): error TS2339: Property '_layer' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(222,11): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerTreeOutline.js(223,25): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. +node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(110,15): error TS2587: JSDoc type 'Layer' circularly references itself. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(125,84): error TS2339: Property 'scrollRectIndex' does not exist on type 'Selection'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(135,19): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/LayerViewHost.js(149,34): error TS2339: Property '_snapshot' does not exist on type 'Selection'. @@ -7870,14 +7877,12 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(694,31): e node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(701,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'entryIndex' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(796,43): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(903,60): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'Group'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(915,27): error TS2339: Property 'peekLast' does not exist on type '{ nestingLevel: number; visible: boolean; }[]'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(919,45): error TS2339: Property 'peekLast' does not exist on type '{ nestingLevel: number; visible: boolean; }[]'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(907,17): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(931,33): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'Group'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(940,33): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'Group'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1027,38): error TS2339: Property 'lowerBound' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1167,15): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1169,70): error TS2339: Property 'peekLast' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1176,27): error TS2339: Property 'peekLast' does not exist on type '{ nestingLevel: number; visible: boolean; }[]'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1182,43): error TS2339: Property 'peekLast' does not exist on type '{ nestingLevel: number; visible: boolean; }[]'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1273,25): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1286,19): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1390,34): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'GroupStyle'. @@ -8827,6 +8832,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.j Type 'HeapSnapshotProviderProxy' is not assignable to type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. Property '_worker' does not exist on type '{ dispose(): void; nodePosition(snapshotObjectId: number): Promise; isEmpty(): Promise; serializeItemsRange(startPosition: number, endPosition: number): Promise<...>; sortAndRewind(comparator: ComparatorConfig): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(804,15): error TS2577: Return type annotation circularly references itself. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(804,16): error TS2587: JSDoc type 'HeapSnapshotRetainingObjectNode' circularly references itself. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(871,36): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(874,34): error TS2339: Property 'withThousandsSeparator' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotGridNodes.js(892,3): error TS2416: Property 'createProvider' in type 'HeapSnapshotInstanceNode' is not assignable to the same property in base type 'HeapSnapshotGenericObjectNode'. @@ -9887,6 +9893,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(250,43): er node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(281,43): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'SetBreakpointResult'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(304,43): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'SetBreakpointResult'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(319,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. +node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(332,32): error TS2587: JSDoc type 'BreakLocation' circularly references itself. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(346,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(347,34): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(355,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. @@ -9973,6 +9980,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(23,15): err node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(28,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(33,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(38,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(45,12): error TS2502: 'child' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(48,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(53,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sdk/LayerTreeBase.js(58,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -10610,6 +10618,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(576,43): err node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(576,55): error TS2339: Property 'ordinal' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(647,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(649,15): error TS2577: Return type annotation circularly references itself. +node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(649,16): error TS2587: JSDoc type 'ObjectSnapshot' circularly references itself. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(859,34): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/sdk/TracingModel.js(870,5): error TS2322: Type 'NamedObject[]' is not assignable to type 'Thread[]'. Type 'NamedObject' is not assignable to type 'Thread'. @@ -10871,6 +10880,7 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/JSONView.js(170,23) node_modules/chrome-devtools-frontend/front_end/source_frame/PreviewFactory.js(14,33): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/ResourceSourceFrame.js(51,35): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(15,22): error TS2339: Property 'installGutter' does not exist on type 'CodeMirrorTextEditor'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(18,24): error TS2587: JSDoc type 'TextEditorPositionHandle' circularly references itself. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(89,28): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(110,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(177,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. @@ -11793,6 +11803,7 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1551,68): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'number'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1563,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1569,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1571,9): error TS2502: 'positionHandle' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1614,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1615,48): error TS2339: Property 'line' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1621,9): error TS1345: An expression of type 'void' cannot be tested for truthiness @@ -12613,6 +12624,8 @@ node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js( node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js(1780,33): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js(1811,25): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModel.js(1819,32): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineModelFilter.js(43,22): error TS1110: Type expected. +node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(72,15): error TS2587: JSDoc type 'TopDownNode' circularly references itself. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(74,26): error TS2502: 'parent' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/timeline_model/TimelineProfileTree.js(168,31): error TS2345: Argument of type 'string | symbol' is not assignable to parameter of type 'string'. Type 'symbol' is not assignable to type 'string'. @@ -12674,6 +12687,7 @@ node_modules/chrome-devtools-frontend/front_end/ui/Context.js(73,30): error TS23 node_modules/chrome-devtools-frontend/front_end/ui/Context.js(77,33): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/ui/Context.js(86,45): error TS1110: Type expected. node_modules/chrome-devtools-frontend/front_end/ui/Context.js(101,16): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(36,15): error TS2587: JSDoc type 'ContextMenu' circularly references itself. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(42,15): error TS2502: 'contextMenu' is referenced directly or indirectly in its own type annotation. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(81,41): error TS2694: Namespace 'InspectorFrontendHostAPI' has no exported member 'ContextMenuDescriptor'. node_modules/chrome-devtools-frontend/front_end/ui/ContextMenu.js(87,18): error TS2339: Property '_customElement' does not exist on type 'ContextMenuItem'. @@ -12862,7 +12876,6 @@ node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(97,36): e node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(108,36): error TS2694: Namespace 'UI.KeyboardShortcut' has no exported member 'Descriptor'. node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(135,42): error TS2694: Namespace 'UI.KeyboardShortcut' has no exported member 'Key'. node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(144,42): error TS2694: Namespace 'UI.KeyboardShortcut' has no exported member 'Key'. -node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(197,9): error TS1127: Invalid character. node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(216,21): error TS2551: Property 'Key' does not exist on type 'typeof KeyboardShortcut'. Did you mean 'Keys'? node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(218,50): error TS2694: Namespace 'UI.KeyboardShortcut' has no exported member 'Key'. node_modules/chrome-devtools-frontend/front_end/ui/KeyboardShortcut.js(289,21): error TS2300: Duplicate identifier 'Descriptor'. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index d6a8d458375..0418c19fe2c 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -80,6 +80,7 @@ node_modules/lodash/_baseWrapperValue.js(18,21): error TS2339: Property 'value' node_modules/lodash/_cloneArrayBuffer.js(11,16): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. node_modules/lodash/_cloneBuffer.js(4,69): error TS2339: Property 'nodeType' does not exist on type '(buffer: any, isDeep?: boolean | undefined) => any'. node_modules/lodash/_cloneBuffer.js(7,80): error TS2339: Property 'nodeType' does not exist on type '{ "../../../tests/cases/user/lodash/node_modules/lodash/_cloneBuffer": (buffer: any, isDeep?: boolean | undefined) => any; }'. +node_modules/lodash/_cloneBuffer.js(20,12): error TS2587: JSDoc type 'Buffer' circularly references itself. node_modules/lodash/_cloneBuffer.js(22,14): error TS2577: Return type annotation circularly references itself. node_modules/lodash/_cloneBuffer.js(24,22): error TS2502: 'buffer' is referenced directly or indirectly in its own type annotation. node_modules/lodash/_copySymbols.js(13,29): error TS2554: Expected 0 arguments, but got 1. From 53906f222fe4ae62652b83646d26a72ea0952e1d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 9 Oct 2018 13:17:54 -0700 Subject: [PATCH 035/262] containsTopLevelCommonjs:handle uninitialised vars (#27642) Previously it assumed that all variable declarations had an initialiser, which is not correct. --- src/services/suggestionDiagnostics.ts | 2 +- ...oEs6Module_unexported_uninitialized_var.ts | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 291d607cee8..fcbb02d4023 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -82,7 +82,7 @@ namespace ts { switch (statement.kind) { case SyntaxKind.VariableStatement: return (statement as VariableStatement).declarationList.declarations.some(decl => - isRequireCall(propertyAccessLeftHandSide(decl.initializer!), /*checkArgumentIsStringLiteralLike*/ true)); // TODO: GH#18217 + !!decl.initializer && isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts b/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts new file mode 100644 index 00000000000..e9cbaafee58 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToEs6Module_unexported_uninitialized_var.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @target: esnext + +// @Filename: /a.js +////var privateUnrelated; +////[|exports.f|] = function() {}; +////privateUnrelated = 1; +////console.log(privateUnrelated); + +verify.getSuggestionDiagnostics([{ + message: "File is a CommonJS module; it may be converted to an ES6 module.", + code: 80001, +}]); + +verify.codeFix({ + description: "Convert to ES6 module", + newFileContent: +`var privateUnrelated; +export function f() {} +privateUnrelated = 1; +console.log(privateUnrelated);`, +}); From b4b29ab1e1365673c4db7c5cc96ece3f773ed39f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 9 Oct 2018 13:21:43 -0700 Subject: [PATCH 036/262] Converted legacySafelist to map to avoid using array prototype methods accidently to match with filename Eg. constructor.js was adding constructor function to aquisition.include which resulted in the mismatch between typing installer's typeAquisition (which was passed as JSON string and parsed back to null) and one in project That meant we kept on queuing the new typing installation request. Fixes #27435 --- src/server/editorServices.ts | 10 ++-- .../unittests/tsserverProjectSystem.ts | 57 +++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 1fc71711eab..30a9844eaf8 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -486,7 +486,7 @@ namespace ts.server { private readonly hostConfiguration: HostConfiguration; private safelist: SafeList = defaultTypeSafeList; - private legacySafelist: { [key: string]: string } = {}; + private readonly legacySafelist = createMap(); private pendingProjectUpdates = createMap(); /* @internal */ @@ -638,14 +638,14 @@ namespace ts.server { this.safelist = raw.typesMap; for (const key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info(`Error loading types map: ${e}`); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } } @@ -2721,13 +2721,13 @@ namespace ts.server { if (fileExtensionIs(baseName, "js")) { const inferredTypingName = removeFileExtension(baseName); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); - if (this.legacySafelist[cleanedTypingName]) { + const typeName = this.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - const typeName = this.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 2105ce6ef4b..9c4d776d54d 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -1826,6 +1826,63 @@ namespace ts.projectSystem { } }); + it("file with name constructor.js doesnt cause issue with typeAcquisition when safe type list", () => { + const file1 = { + path: "/a/b/f1.js", + content: `export let x = 5; import { s } from "s"` + }; + const constructorFile = { + path: "/a/b/constructor.js", + content: "const x = 10;" + }; + const bliss = { + path: "/a/b/bliss.js", + content: "export function is() { return true; }" + }; + const host = createServerHost([file1, libFile, constructorFile, bliss, customTypesMap]); + let request: string | undefined; + const cachePath = "/a/data"; + const typingsInstaller: server.ITypingsInstaller = { + isKnownTypesPackageName: returnFalse, + installPackage: notImplemented, + inspectValue: notImplemented, + enqueueInstallTypingsRequest: (proj, typeAcquisition, unresolvedImports) => { + assert.isUndefined(request); + request = JSON.stringify(server.createInstallTypingsRequest(proj, typeAcquisition, unresolvedImports || server.emptyArray, cachePath)); + }, + attach: noop, + onProjectClosed: noop, + globalTypingsCacheLocation: cachePath + }; + + const projectName = "project"; + const projectService = createProjectService(host, { typingsInstaller }); + projectService.openExternalProject({ projectFileName: projectName, options: {}, rootFiles: toExternalFiles([file1.path, constructorFile.path, bliss.path]) }); + assert.equal(request, JSON.stringify({ + projectName, + fileNames: [libFile.path, file1.path, constructorFile.path, bliss.path], + compilerOptions: { allowNonTsExtensions: true, noEmitForJsFiles: true }, + typeAcquisition: { include: ["blissfuljs"], exclude: [], enable: true }, + unresolvedImports: ["s"], + projectRootPath: "/", + cachePath, + kind: "discover" + })); + const response = JSON.parse(request!); + request = undefined; + projectService.updateTypingsForProject({ + kind: "action::set", + projectName: response.projectName, + typeAcquisition: response.typeAcquisition, + compilerOptions: response.compilerOptions, + typings: emptyArray, + unresolvedImports: response.unresolvedImports, + }); + + host.checkTimeoutQueueLengthAndRun(2); + assert.isUndefined(request); + }); + it("ignores files excluded by the default type list", () => { const file1 = { path: "/a/b/f1.js", From 23ec0c44846036005035317f5e5f27421d443cb6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 9 Oct 2018 13:45:17 -0700 Subject: [PATCH 037/262] Accept public api change --- tests/baselines/reference/api/tsserverlibrary.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 0120e49f0a5..d8306559986 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8497,7 +8497,7 @@ declare namespace ts.server { private readonly throttledOperations; private readonly hostConfiguration; private safelist; - private legacySafelist; + private readonly legacySafelist; private pendingProjectUpdates; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; From d0698751ce06814d740b22511c363d2a88a4a1bc Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 9 Oct 2018 18:41:58 -0700 Subject: [PATCH 038/262] Allow discriminant property to contain some non-unit types --- src/compiler/checker.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fe2ce42652a..9578f7a106b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12919,6 +12919,10 @@ namespace ts { isUnitType(type); } + function maybeUnitType(type: Type): boolean { + return type.flags & TypeFlags.Union ? some((type).types, isUnitType) : isUnitType(type); + } + function getBaseTypeOfLiteralType(type: Type): Type { return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral ? stringType : @@ -14217,7 +14221,7 @@ namespace ts { const prop = getUnionOrIntersectionProperty(type, name); if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { if ((prop).isDiscriminantProperty === undefined) { - (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && isLiteralType(getTypeOfSymbol(prop)); + (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && maybeUnitType(getTypeOfSymbol(prop)); } return !!(prop).isDiscriminantProperty; } From ba0f5581f6fd571f7c6b06a9f459e5c477be628e Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 10 Oct 2018 12:51:58 -0700 Subject: [PATCH 039/262] Remove any existing errors in case of successful build in tsbuild watch mode Fixes #27685 --- src/compiler/tsbuild.ts | 3 ++ src/testRunner/unittests/tsbuildWatchMode.ts | 52 ++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 5d27e6a79f6..c2215b22ebf 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -1066,6 +1066,9 @@ namespace ts { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; + if (options.watch) { + diagnostics.removeKey(proj); + } projectStatus.setValue(proj, status); return resultFlags; diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 2ffe51189d8..884042a9c8f 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -356,6 +356,58 @@ function myFunc() { return 100; }`); } }); + it("when referenced project change introduces error in the down stream project and then fixes it", () => { + const subProjectLibrary = `${projectsLocation}/${project}/Library`; + const libraryTs: File = { + path: `${subProjectLibrary}/library.ts`, + content: ` +interface SomeObject +{ + message: string; +} + +export function createSomeObject(): SomeObject +{ + return { + message: "new Object" + }; +}` + }; + const libraryTsconfig: File = { + path: `${subProjectLibrary}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true } }) + }; + const subProjectApp = `${projectsLocation}/${project}/App`; + const appTs: File = { + path: `${subProjectApp}/app.ts`, + content: `import { createSomeObject } from "../Library/library"; +createSomeObject().message;` + }; + const appTsconfig: File = { + path: `${subProjectApp}/tsconfig.json`, + content: JSON.stringify({ references: [{ path: "../Library" }] }) + }; + + const files = [libFile, libraryTs, libraryTsconfig, appTs, appTsconfig]; + const host = createWatchedSystem(files, { currentDirectory: `${projectsLocation}/${project}` }); + createSolutionBuilderWithWatch(host, ["App"]); + checkOutputErrorsInitial(host, emptyArray); + + // Change message in library to message2 + host.writeFile(libraryTs.path, libraryTs.content.replace(/message/g, "message2")); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, [ + "App/app.ts(2,20): error TS2551: Property 'message' does not exist on type 'SomeObject'. Did you mean 'message2'?\n" + ]); + + // Revert library changes + host.writeFile(libraryTs.path, libraryTs.content); + host.checkTimeoutQueueLengthAndRun(1); // Build library + host.checkTimeoutQueueLengthAndRun(1); // Build App + checkOutputErrorsIncremental(host, emptyArray); + }); + describe("reports errors in all projects on incremental compile", () => { function verifyIncrementalErrors(defaultBuildOptions?: BuildOptions, disabledConsoleClear?: boolean) { const host = createSolutionInWatchMode(allFiles, defaultBuildOptions, disabledConsoleClear); From dd764b318f965c7104aa6a02318614069beaf1fc Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 10 Oct 2018 13:45:52 -0700 Subject: [PATCH 040/262] importFixes: Skip alias when testing isTypeOnlySymbol (#27674) --- src/services/codefixes/importFixes.ts | 12 ++++++------ .../importNameCodeFix_defaultExport.ts | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 tests/cases/fourslash/importNameCodeFix_defaultExport.ts diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 578f55f5c68..2f6d68c52f4 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -185,20 +185,20 @@ namespace ts.codefix { const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); if (defaultInfo && defaultInfo.name === symbolName && skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol) }); + result.push({ moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } for (const exported of checker.getExportsOfModule(moduleSymbol)) { if (exported.name === symbolName && skipAlias(exported, checker) === exportedSymbol) { - result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + result.push({ moduleSymbol, importKind: ImportKind.Named, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s: Symbol): boolean { - return !(s.flags & SymbolFlags.Value); + function isTypeOnlySymbol(s: Symbol, checker: TypeChecker): boolean { + return !(skipAlias(s, checker).flags & SymbolFlags.Value); } function getFixForImport( @@ -398,7 +398,7 @@ namespace ts.codefix { // Maps symbol id to info for modules providing that symbol (original export + re-exports). const originalSymbolToExportInfos = createMultiMap(); function addSymbol(moduleSymbol: Symbol, exportedSymbol: Symbol, importKind: ImportKind): void { - originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol, importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), moduleSymbol => { cancellationToken.throwIfCancellationRequested(); @@ -424,7 +424,7 @@ namespace ts.codefix { if (!exported) return undefined; const { symbol, kind } = exported; const info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); - return info && { symbol, symbolForMeaning: info.symbolForMeaning, name: info.name, kind }; + return info && { symbol, kind, ...info }; } function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly kind: ImportKind.Default | ImportKind.Equals } | undefined { diff --git a/tests/cases/fourslash/importNameCodeFix_defaultExport.ts b/tests/cases/fourslash/importNameCodeFix_defaultExport.ts new file mode 100644 index 00000000000..fa8cef71c99 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFix_defaultExport.ts @@ -0,0 +1,18 @@ +/// + +// @allowJs: true +// @checkJs: true + +// @Filename: /a.js +////class C {} +////export default C; + +// @Filename: /b.js +////[|C;|] + +goTo.file("/b.js"); +verify.importFixAtPosition([ +`import C from "./a"; + +C;`, +]); From c110f57deb0c423c4e160ab5bce74c35187cb039 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 10 Oct 2018 15:11:35 -0700 Subject: [PATCH 041/262] Discriminant must include at least one unit type and no instantiable types --- src/compiler/checker.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9578f7a106b..795b893f69e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12919,10 +12919,6 @@ namespace ts { isUnitType(type); } - function maybeUnitType(type: Type): boolean { - return type.flags & TypeFlags.Union ? some((type).types, isUnitType) : isUnitType(type); - } - function getBaseTypeOfLiteralType(type: Type): Type { return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral ? stringType : @@ -14216,12 +14212,26 @@ namespace ts { return undefined; } + function isDiscriminantType(type: Type): boolean { + if (type.flags & TypeFlags.Union) { + if (type.flags & (TypeFlags.Boolean | TypeFlags.EnumLiteral)) { + return true; + } + let combined = 0; + for (const t of (type).types) combined |= t.flags; + if (combined & TypeFlags.Unit && !(combined & TypeFlags.Instantiable)) { + return true; + } + } + return false; + } + function isDiscriminantProperty(type: Type | undefined, name: __String) { if (type && type.flags & TypeFlags.Union) { const prop = getUnionOrIntersectionProperty(type, name); if (prop && getCheckFlags(prop) & CheckFlags.SyntheticProperty) { if ((prop).isDiscriminantProperty === undefined) { - (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && maybeUnitType(getTypeOfSymbol(prop)); + (prop).isDiscriminantProperty = !!((prop).checkFlags & CheckFlags.HasNonUniformType) && isDiscriminantType(getTypeOfSymbol(prop)); } return !!(prop).isDiscriminantProperty; } From 7737cd5f1fe07d47b00b1f5e189a73e060c78c19 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 10 Oct 2018 15:11:57 -0700 Subject: [PATCH 042/262] Accept new baselines --- .../reference/objectLiteralNormalization.errors.txt | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tests/baselines/reference/objectLiteralNormalization.errors.txt b/tests/baselines/reference/objectLiteralNormalization.errors.txt index 3cdda885277..2a09dd3b4df 100644 --- a/tests/baselines/reference/objectLiteralNormalization.errors.txt +++ b/tests/baselines/reference/objectLiteralNormalization.errors.txt @@ -10,9 +10,8 @@ tests/cases/conformance/expressions/objectLiterals/objectLiteralNormalization.ts Types of property 'a' are incompatible. Type 'string' is not assignable to type 'undefined'. tests/cases/conformance/expressions/objectLiterals/objectLiteralNormalization.ts(18,1): error TS2322: Type '{ a: number; }' is not assignable to type '{ a: number; b: number; } | { a: string; b?: undefined; } | { a?: undefined; b?: undefined; }'. - Type '{ a: number; }' is not assignable to type '{ a?: undefined; b?: undefined; }'. - Types of property 'a' are incompatible. - Type 'number' is not assignable to type 'undefined'. + Type '{ a: number; }' is not assignable to type '{ a: number; b: number; }'. + Property 'b' is missing in type '{ a: number; }'. ==== tests/cases/conformance/expressions/objectLiterals/objectLiteralNormalization.ts (5 errors) ==== @@ -52,9 +51,8 @@ tests/cases/conformance/expressions/objectLiterals/objectLiteralNormalization.ts a2 = { a: 1 }; // Error ~~ !!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a: number; b: number; } | { a: string; b?: undefined; } | { a?: undefined; b?: undefined; }'. -!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a?: undefined; b?: undefined; }'. -!!! error TS2322: Types of property 'a' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'undefined'. +!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a: number; b: number; }'. +!!! error TS2322: Property 'b' is missing in type '{ a: number; }'. // Object literals containing spreads are not normalized declare let b1: { a: string, b: string } | { b: string, c: string }; From 22907bfb0701284f83fea13b9050c2c95ec63924 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 10 Oct 2018 15:40:12 -0700 Subject: [PATCH 043/262] Add tests --- .../types/union/discriminatedUnionTypes2.ts | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/cases/conformance/types/union/discriminatedUnionTypes2.ts diff --git a/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts b/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts new file mode 100644 index 00000000000..789bc263c7e --- /dev/null +++ b/tests/cases/conformance/types/union/discriminatedUnionTypes2.ts @@ -0,0 +1,74 @@ +// @strict: true + +function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + if (x.kind === false) { + x.a; + } + else if (x.kind === true) { + x.b; + } + else { + x.c; + } +} + +function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + switch (x.kind) { + case false: + x.a; + break; + case true: + x.b; + break; + default: + x.c; + } +} + +function f13(x: { a: null; b: string } | { a: string, c: number }) { + x = { a: null, b: "foo", c: 4}; // Error +} + +function f14(x: { a: 0; b: string } | { a: T, c: number }) { + if (x.a === 0) { + x.b; // Error + } +} + +type Result = { error?: undefined, value: T } | { error: Error }; + +function f15(x: Result) { + if (!x.error) { + x.value; + } + else { + x.error.message; + } +} + +f15({ value: 10 }); +f15({ error: new Error("boom") }); + +// Repro from #24193 + +interface WithError { + error: Error + data: null +} + +interface WithoutError { + error: null + data: Data +} + +type DataCarrier = WithError | WithoutError + +function f20(carrier: DataCarrier) { + if (carrier.error === null) { + const error: null = carrier.error + const data: Data = carrier.data + } else { + const error: Error = carrier.error + const data: null = carrier.data + } +} From 6cdba6d3516a32e36458ef68e2f785a914ffd91f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 10 Oct 2018 15:40:19 -0700 Subject: [PATCH 044/262] Accept new baselines --- .../discriminatedUnionTypes2.errors.txt | 86 +++++++ .../reference/discriminatedUnionTypes2.js | 128 ++++++++++ .../discriminatedUnionTypes2.symbols | 227 +++++++++++++++++ .../reference/discriminatedUnionTypes2.types | 241 ++++++++++++++++++ 4 files changed, 682 insertions(+) create mode 100644 tests/baselines/reference/discriminatedUnionTypes2.errors.txt create mode 100644 tests/baselines/reference/discriminatedUnionTypes2.js create mode 100644 tests/baselines/reference/discriminatedUnionTypes2.symbols create mode 100644 tests/baselines/reference/discriminatedUnionTypes2.types diff --git a/tests/baselines/reference/discriminatedUnionTypes2.errors.txt b/tests/baselines/reference/discriminatedUnionTypes2.errors.txt new file mode 100644 index 00000000000..c50f7a2767a --- /dev/null +++ b/tests/baselines/reference/discriminatedUnionTypes2.errors.txt @@ -0,0 +1,86 @@ +tests/cases/conformance/types/union/discriminatedUnionTypes2.ts(27,30): error TS2322: Type '{ a: null; b: string; c: number; }' is not assignable to type '{ a: null; b: string; } | { a: string; c: number; }'. + Object literal may only specify known properties, and 'c' does not exist in type '{ a: null; b: string; }'. +tests/cases/conformance/types/union/discriminatedUnionTypes2.ts(32,11): error TS2339: Property 'b' does not exist on type '{ a: 0; b: string; } | { a: T; c: number; }'. + Property 'b' does not exist on type '{ a: T; c: number; }'. + + +==== tests/cases/conformance/types/union/discriminatedUnionTypes2.ts (2 errors) ==== + function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + if (x.kind === false) { + x.a; + } + else if (x.kind === true) { + x.b; + } + else { + x.c; + } + } + + function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + switch (x.kind) { + case false: + x.a; + break; + case true: + x.b; + break; + default: + x.c; + } + } + + function f13(x: { a: null; b: string } | { a: string, c: number }) { + x = { a: null, b: "foo", c: 4}; // Error + ~~~~ +!!! error TS2322: Type '{ a: null; b: string; c: number; }' is not assignable to type '{ a: null; b: string; } | { a: string; c: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: null; b: string; }'. + } + + function f14(x: { a: 0; b: string } | { a: T, c: number }) { + if (x.a === 0) { + x.b; // Error + ~ +!!! error TS2339: Property 'b' does not exist on type '{ a: 0; b: string; } | { a: T; c: number; }'. +!!! error TS2339: Property 'b' does not exist on type '{ a: T; c: number; }'. + } + } + + type Result = { error?: undefined, value: T } | { error: Error }; + + function f15(x: Result) { + if (!x.error) { + x.value; + } + else { + x.error.message; + } + } + + f15({ value: 10 }); + f15({ error: new Error("boom") }); + + // Repro from #24193 + + interface WithError { + error: Error + data: null + } + + interface WithoutError { + error: null + data: Data + } + + type DataCarrier = WithError | WithoutError + + function f20(carrier: DataCarrier) { + if (carrier.error === null) { + const error: null = carrier.error + const data: Data = carrier.data + } else { + const error: Error = carrier.error + const data: null = carrier.data + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/discriminatedUnionTypes2.js b/tests/baselines/reference/discriminatedUnionTypes2.js new file mode 100644 index 00000000000..e2b5d99ddcd --- /dev/null +++ b/tests/baselines/reference/discriminatedUnionTypes2.js @@ -0,0 +1,128 @@ +//// [discriminatedUnionTypes2.ts] +function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + if (x.kind === false) { + x.a; + } + else if (x.kind === true) { + x.b; + } + else { + x.c; + } +} + +function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { + switch (x.kind) { + case false: + x.a; + break; + case true: + x.b; + break; + default: + x.c; + } +} + +function f13(x: { a: null; b: string } | { a: string, c: number }) { + x = { a: null, b: "foo", c: 4}; // Error +} + +function f14(x: { a: 0; b: string } | { a: T, c: number }) { + if (x.a === 0) { + x.b; // Error + } +} + +type Result = { error?: undefined, value: T } | { error: Error }; + +function f15(x: Result) { + if (!x.error) { + x.value; + } + else { + x.error.message; + } +} + +f15({ value: 10 }); +f15({ error: new Error("boom") }); + +// Repro from #24193 + +interface WithError { + error: Error + data: null +} + +interface WithoutError { + error: null + data: Data +} + +type DataCarrier = WithError | WithoutError + +function f20(carrier: DataCarrier) { + if (carrier.error === null) { + const error: null = carrier.error + const data: Data = carrier.data + } else { + const error: Error = carrier.error + const data: null = carrier.data + } +} + + +//// [discriminatedUnionTypes2.js] +"use strict"; +function f10(x) { + if (x.kind === false) { + x.a; + } + else if (x.kind === true) { + x.b; + } + else { + x.c; + } +} +function f11(x) { + switch (x.kind) { + case false: + x.a; + break; + case true: + x.b; + break; + default: + x.c; + } +} +function f13(x) { + x = { a: null, b: "foo", c: 4 }; // Error +} +function f14(x) { + if (x.a === 0) { + x.b; // Error + } +} +function f15(x) { + if (!x.error) { + x.value; + } + else { + x.error.message; + } +} +f15({ value: 10 }); +f15({ error: new Error("boom") }); +function f20(carrier) { + if (carrier.error === null) { + var error = carrier.error; + var data = carrier.data; + } + else { + var error = carrier.error; + var data = carrier.data; + } +} diff --git a/tests/baselines/reference/discriminatedUnionTypes2.symbols b/tests/baselines/reference/discriminatedUnionTypes2.symbols new file mode 100644 index 00000000000..38cfcb0b23a --- /dev/null +++ b/tests/baselines/reference/discriminatedUnionTypes2.symbols @@ -0,0 +1,227 @@ +=== tests/cases/conformance/types/union/discriminatedUnionTypes2.ts === +function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { +>f10 : Symbol(f10, Decl(discriminatedUnionTypes2.ts, 0, 0)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 18)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 0, 31)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 47)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 0, 59)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 75)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 0, 89)) + + if (x.kind === false) { +>x.kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 18), Decl(discriminatedUnionTypes2.ts, 0, 47), Decl(discriminatedUnionTypes2.ts, 0, 75)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 18), Decl(discriminatedUnionTypes2.ts, 0, 47), Decl(discriminatedUnionTypes2.ts, 0, 75)) + + x.a; +>x.a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 0, 31)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 0, 31)) + } + else if (x.kind === true) { +>x.kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 47), Decl(discriminatedUnionTypes2.ts, 0, 75)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 0, 47), Decl(discriminatedUnionTypes2.ts, 0, 75)) + + x.b; +>x.b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 0, 59)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 0, 59)) + } + else { + x.c; +>x.c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 0, 89)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 0, 13)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 0, 89)) + } +} + +function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { +>f11 : Symbol(f11, Decl(discriminatedUnionTypes2.ts, 10, 1)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 12, 13)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 12, 18)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 12, 31)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 12, 47)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 12, 59)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 12, 75)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 12, 89)) + + switch (x.kind) { +>x.kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 12, 18), Decl(discriminatedUnionTypes2.ts, 12, 47), Decl(discriminatedUnionTypes2.ts, 12, 75)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 12, 13)) +>kind : Symbol(kind, Decl(discriminatedUnionTypes2.ts, 12, 18), Decl(discriminatedUnionTypes2.ts, 12, 47), Decl(discriminatedUnionTypes2.ts, 12, 75)) + + case false: + x.a; +>x.a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 12, 31)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 12, 13)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 12, 31)) + + break; + case true: + x.b; +>x.b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 12, 59)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 12, 13)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 12, 59)) + + break; + default: + x.c; +>x.c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 12, 89)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 12, 13)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 12, 89)) + } +} + +function f13(x: { a: null; b: string } | { a: string, c: number }) { +>f13 : Symbol(f13, Decl(discriminatedUnionTypes2.ts, 23, 1)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 25, 13)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 25, 17)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 25, 26)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 25, 42)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 25, 53)) + + x = { a: null, b: "foo", c: 4}; // Error +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 25, 13)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 26, 9)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 26, 18)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 26, 28)) +} + +function f14(x: { a: 0; b: string } | { a: T, c: number }) { +>f14 : Symbol(f14, Decl(discriminatedUnionTypes2.ts, 27, 1)) +>T : Symbol(T, Decl(discriminatedUnionTypes2.ts, 29, 13)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 29, 16)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 29, 20)) +>b : Symbol(b, Decl(discriminatedUnionTypes2.ts, 29, 26)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 29, 42)) +>T : Symbol(T, Decl(discriminatedUnionTypes2.ts, 29, 13)) +>c : Symbol(c, Decl(discriminatedUnionTypes2.ts, 29, 48)) + + if (x.a === 0) { +>x.a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 29, 20), Decl(discriminatedUnionTypes2.ts, 29, 42)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 29, 16)) +>a : Symbol(a, Decl(discriminatedUnionTypes2.ts, 29, 20), Decl(discriminatedUnionTypes2.ts, 29, 42)) + + x.b; // Error +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 29, 16)) + } +} + +type Result = { error?: undefined, value: T } | { error: Error }; +>Result : Symbol(Result, Decl(discriminatedUnionTypes2.ts, 33, 1)) +>T : Symbol(T, Decl(discriminatedUnionTypes2.ts, 35, 12)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 18)) +>value : Symbol(value, Decl(discriminatedUnionTypes2.ts, 35, 37)) +>T : Symbol(T, Decl(discriminatedUnionTypes2.ts, 35, 12)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 52)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +function f15(x: Result) { +>f15 : Symbol(f15, Decl(discriminatedUnionTypes2.ts, 35, 68)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 37, 13)) +>Result : Symbol(Result, Decl(discriminatedUnionTypes2.ts, 33, 1)) + + if (!x.error) { +>x.error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 52), Decl(discriminatedUnionTypes2.ts, 35, 18)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 37, 13)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 52), Decl(discriminatedUnionTypes2.ts, 35, 18)) + + x.value; +>x.value : Symbol(value, Decl(discriminatedUnionTypes2.ts, 35, 37)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 37, 13)) +>value : Symbol(value, Decl(discriminatedUnionTypes2.ts, 35, 37)) + } + else { + x.error.message; +>x.error.message : Symbol(Error.message, Decl(lib.es5.d.ts, --, --)) +>x.error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 52)) +>x : Symbol(x, Decl(discriminatedUnionTypes2.ts, 37, 13)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 35, 52)) +>message : Symbol(Error.message, Decl(lib.es5.d.ts, --, --)) + } +} + +f15({ value: 10 }); +>f15 : Symbol(f15, Decl(discriminatedUnionTypes2.ts, 35, 68)) +>value : Symbol(value, Decl(discriminatedUnionTypes2.ts, 46, 5)) + +f15({ error: new Error("boom") }); +>f15 : Symbol(f15, Decl(discriminatedUnionTypes2.ts, 35, 68)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 47, 5)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +// Repro from #24193 + +interface WithError { +>WithError : Symbol(WithError, Decl(discriminatedUnionTypes2.ts, 47, 34)) + + error: Error +>error : Symbol(WithError.error, Decl(discriminatedUnionTypes2.ts, 51, 21)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + data: null +>data : Symbol(WithError.data, Decl(discriminatedUnionTypes2.ts, 52, 16)) +} + +interface WithoutError { +>WithoutError : Symbol(WithoutError, Decl(discriminatedUnionTypes2.ts, 54, 1)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 56, 23)) + + error: null +>error : Symbol(WithoutError.error, Decl(discriminatedUnionTypes2.ts, 56, 30)) + + data: Data +>data : Symbol(WithoutError.data, Decl(discriminatedUnionTypes2.ts, 57, 15)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 56, 23)) +} + +type DataCarrier = WithError | WithoutError +>DataCarrier : Symbol(DataCarrier, Decl(discriminatedUnionTypes2.ts, 59, 1)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 61, 17)) +>WithError : Symbol(WithError, Decl(discriminatedUnionTypes2.ts, 47, 34)) +>WithoutError : Symbol(WithoutError, Decl(discriminatedUnionTypes2.ts, 54, 1)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 61, 17)) + +function f20(carrier: DataCarrier) { +>f20 : Symbol(f20, Decl(discriminatedUnionTypes2.ts, 61, 55)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 63, 13)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>DataCarrier : Symbol(DataCarrier, Decl(discriminatedUnionTypes2.ts, 59, 1)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 63, 13)) + + if (carrier.error === null) { +>carrier.error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 51, 21), Decl(discriminatedUnionTypes2.ts, 56, 30)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 51, 21), Decl(discriminatedUnionTypes2.ts, 56, 30)) + + const error: null = carrier.error +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 65, 13)) +>carrier.error : Symbol(WithoutError.error, Decl(discriminatedUnionTypes2.ts, 56, 30)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>error : Symbol(WithoutError.error, Decl(discriminatedUnionTypes2.ts, 56, 30)) + + const data: Data = carrier.data +>data : Symbol(data, Decl(discriminatedUnionTypes2.ts, 66, 13)) +>Data : Symbol(Data, Decl(discriminatedUnionTypes2.ts, 63, 13)) +>carrier.data : Symbol(WithoutError.data, Decl(discriminatedUnionTypes2.ts, 57, 15)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>data : Symbol(WithoutError.data, Decl(discriminatedUnionTypes2.ts, 57, 15)) + + } else { + const error: Error = carrier.error +>error : Symbol(error, Decl(discriminatedUnionTypes2.ts, 68, 13)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>carrier.error : Symbol(WithError.error, Decl(discriminatedUnionTypes2.ts, 51, 21)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>error : Symbol(WithError.error, Decl(discriminatedUnionTypes2.ts, 51, 21)) + + const data: null = carrier.data +>data : Symbol(data, Decl(discriminatedUnionTypes2.ts, 69, 13)) +>carrier.data : Symbol(WithError.data, Decl(discriminatedUnionTypes2.ts, 52, 16)) +>carrier : Symbol(carrier, Decl(discriminatedUnionTypes2.ts, 63, 19)) +>data : Symbol(WithError.data, Decl(discriminatedUnionTypes2.ts, 52, 16)) + } +} + diff --git a/tests/baselines/reference/discriminatedUnionTypes2.types b/tests/baselines/reference/discriminatedUnionTypes2.types new file mode 100644 index 00000000000..b654fc1a78d --- /dev/null +++ b/tests/baselines/reference/discriminatedUnionTypes2.types @@ -0,0 +1,241 @@ +=== tests/cases/conformance/types/union/discriminatedUnionTypes2.ts === +function f10(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { +>f10 : (x: { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; }) => void +>x : { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; } +>kind : false +>false : false +>a : string +>kind : true +>true : true +>b : string +>kind : string +>c : string + + if (x.kind === false) { +>x.kind === false : boolean +>x.kind : string | boolean +>x : { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; } +>kind : string | boolean +>false : false + + x.a; +>x.a : string +>x : { kind: false; a: string; } +>a : string + } + else if (x.kind === true) { +>x.kind === true : boolean +>x.kind : string | true +>x : { kind: true; b: string; } | { kind: string; c: string; } +>kind : string | true +>true : true + + x.b; +>x.b : string +>x : { kind: true; b: string; } +>b : string + } + else { + x.c; +>x.c : string +>x : { kind: string; c: string; } +>c : string + } +} + +function f11(x : { kind: false, a: string } | { kind: true, b: string } | { kind: string, c: string }) { +>f11 : (x: { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; }) => void +>x : { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; } +>kind : false +>false : false +>a : string +>kind : true +>true : true +>b : string +>kind : string +>c : string + + switch (x.kind) { +>x.kind : string | boolean +>x : { kind: false; a: string; } | { kind: true; b: string; } | { kind: string; c: string; } +>kind : string | boolean + + case false: +>false : false + + x.a; +>x.a : string +>x : { kind: false; a: string; } +>a : string + + break; + case true: +>true : true + + x.b; +>x.b : string +>x : { kind: true; b: string; } +>b : string + + break; + default: + x.c; +>x.c : string +>x : { kind: string; c: string; } +>c : string + } +} + +function f13(x: { a: null; b: string } | { a: string, c: number }) { +>f13 : (x: { a: null; b: string; } | { a: string; c: number; }) => void +>x : { a: null; b: string; } | { a: string; c: number; } +>a : null +>null : null +>b : string +>a : string +>c : number + + x = { a: null, b: "foo", c: 4}; // Error +>x = { a: null, b: "foo", c: 4} : { a: null; b: string; c: number; } +>x : { a: null; b: string; } | { a: string; c: number; } +>{ a: null, b: "foo", c: 4} : { a: null; b: string; c: number; } +>a : null +>null : null +>b : string +>"foo" : "foo" +>c : number +>4 : 4 +} + +function f14(x: { a: 0; b: string } | { a: T, c: number }) { +>f14 : (x: { a: 0; b: string; } | { a: T; c: number; }) => void +>x : { a: 0; b: string; } | { a: T; c: number; } +>a : 0 +>b : string +>a : T +>c : number + + if (x.a === 0) { +>x.a === 0 : boolean +>x.a : 0 | T +>x : { a: 0; b: string; } | { a: T; c: number; } +>a : 0 | T +>0 : 0 + + x.b; // Error +>x.b : any +>x : { a: 0; b: string; } | { a: T; c: number; } +>b : any + } +} + +type Result = { error?: undefined, value: T } | { error: Error }; +>Result : Result +>error : undefined +>value : T +>error : Error + +function f15(x: Result) { +>f15 : (x: Result) => void +>x : Result + + if (!x.error) { +>!x.error : boolean +>x.error : Error | undefined +>x : Result +>error : Error | undefined + + x.value; +>x.value : number +>x : { error?: undefined; value: number; } +>value : number + } + else { + x.error.message; +>x.error.message : string +>x.error : Error +>x : { error: Error; } +>error : Error +>message : string + } +} + +f15({ value: 10 }); +>f15({ value: 10 }) : void +>f15 : (x: Result) => void +>{ value: 10 } : { value: number; } +>value : number +>10 : 10 + +f15({ error: new Error("boom") }); +>f15({ error: new Error("boom") }) : void +>f15 : (x: Result) => void +>{ error: new Error("boom") } : { error: Error; } +>error : Error +>new Error("boom") : Error +>Error : ErrorConstructor +>"boom" : "boom" + +// Repro from #24193 + +interface WithError { + error: Error +>error : Error + + data: null +>data : null +>null : null +} + +interface WithoutError { + error: null +>error : null +>null : null + + data: Data +>data : Data +} + +type DataCarrier = WithError | WithoutError +>DataCarrier : DataCarrier + +function f20(carrier: DataCarrier) { +>f20 : (carrier: DataCarrier) => void +>carrier : DataCarrier + + if (carrier.error === null) { +>carrier.error === null : boolean +>carrier.error : Error | null +>carrier : DataCarrier +>error : Error | null +>null : null + + const error: null = carrier.error +>error : null +>null : null +>carrier.error : null +>carrier : WithoutError +>error : null + + const data: Data = carrier.data +>data : Data +>carrier.data : Data +>carrier : WithoutError +>data : Data + + } else { + const error: Error = carrier.error +>error : Error +>carrier.error : Error +>carrier : WithError +>error : Error + + const data: null = carrier.data +>data : null +>null : null +>carrier.data : null +>carrier : WithError +>data : null + } +} + From dd6365615dfe65548578d7ac0d8d92d3f78f7414 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 11 Oct 2018 08:45:47 -0700 Subject: [PATCH 045/262] Address CR feedback --- src/compiler/checker.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 33d23bd11ee..c2e8645518d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9312,12 +9312,11 @@ namespace ts { propType; } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { - const restType = mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); - if (restType === undefinedType && accessNode) { + if (accessNode && everyType(objectType, t => !(t).target.hasRestElement)) { const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } - return restType; + return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); } } if (!(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike)) { From d493c47aac96b76e25987e42c7e91bccd46481f9 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Thu, 11 Oct 2018 09:58:25 -0700 Subject: [PATCH 046/262] Update user baselines (#27710) --- tests/baselines/reference/user/enhanced-resolve.log | 6 +++--- tests/baselines/reference/user/npm.log | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/baselines/reference/user/enhanced-resolve.log b/tests/baselines/reference/user/enhanced-resolve.log index 24d0c3b9839..7dd284bf166 100644 --- a/tests/baselines/reference/user/enhanced-resolve.log +++ b/tests/baselines/reference/user/enhanced-resolve.log @@ -1,10 +1,10 @@ Exit Code: 1 Standard output: -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(116,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(116,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(129,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(129,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(147,18): error TS2345: Argument of type 'Timer | null' is not assignable to parameter of type 'number | undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(147,18): error TS2345: Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(176,19): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(179,23): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 1caa051e2de..435d962fa95 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -919,6 +919,8 @@ node_modules/npm/test/broken-under-nyc-and-travis/whoami.js(7,20): error TS2307: node_modules/npm/test/common-tap.js(5,47): error TS2339: Property '_extend' does not exist on type 'typeof import("util")'. node_modules/npm/test/common-tap.js(10,3): error TS2322: Type '(...args: any[]) => void' is not assignable to type 'typeof setImmediate'. Property '__promisify__' is missing in type '(...args: any[]) => void'. +node_modules/npm/test/common-tap.js(10,36): error TS2322: Type '(...args: any[]) => void' is not assignable to type '(callback: (...args: any[]) => void, ...args: any[]) => Immediate'. + Type 'void' is not assignable to type 'Immediate'. node_modules/npm/test/common-tap.js(12,28): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[(...args: any[]) => void, number, ...any[]]'. Property '0' is missing in type 'any[]'. node_modules/npm/test/common-tap.js(175,17): error TS2339: Property '_storage' does not exist on type 'Environment'. From b040ea66d1f7b96029411c21781b094509f98cf6 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 11 Oct 2018 10:13:36 -0700 Subject: [PATCH 047/262] One more CR fix --- src/compiler/checker.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c2e8645518d..229a8bad77d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12882,11 +12882,8 @@ namespace ts { if (propType) { return propType; } - if (everyType(type, isTupleType)) { - const restType = mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); - if (restType !== undefinedType) { - return restType; - } + if (everyType(type, isTupleType) && !everyType(type, t => !(t).target.hasRestElement)) { + return mapType(type, t => getRestTypeOfTupleType(t) || undefinedType); } return undefined; } From 0d91838593e8108e2183ff7dacfdc16c04a8b06b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 Oct 2018 10:09:47 -0700 Subject: [PATCH 048/262] Do not generate jsFile path if its emitOnlyDeclarations is set Fixes #27009 --- src/compiler/emitter.ts | 45 ++++++++++++++--------- src/compiler/transformers/declarations.ts | 2 +- src/compiler/utilities.ts | 2 +- src/testRunner/unittests/tsbuild.ts | 2 + 4 files changed, 31 insertions(+), 20 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index fe54402d434..6b4b3a5c510 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -41,20 +41,23 @@ namespace ts { export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean): EmitFileNames { const options = host.getCompilerOptions(); if (sourceFile.kind === SyntaxKind.Bundle) { - const jsFilePath = options.outFile || options.out!; - const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(jsFilePath) + Extension.Dts : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const outPath = options.outFile || options.out!; + const jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath }; } else { - const jsFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - const sourceMapFilePath = isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + const jsFilePath = options.emitDeclarationOnly ? undefined : ownOutputFilePath; + const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error const isJs = isSourceFileJS(sourceFile); const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined }; } } @@ -135,27 +138,33 @@ namespace ts { if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } - function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string | undefined, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) { + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 5312efb5aac..00e787c421b 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -275,7 +275,7 @@ namespace ts { else { if (isBundledEmit && contains((node as Bundle).sourceFiles, file)) return; // Omit references to files which are being merged const paths = getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index ae75290d56e..564e74fc4d3 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3245,7 +3245,7 @@ namespace ts { } export interface EmitFileNames { - jsFilePath: string; + jsFilePath: string | undefined; sourceMapFilePath: string | undefined; declarationFilePath: string | undefined; declarationMapPath: string | undefined; diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index 36feb68a223..94af1241ab0 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -347,8 +347,10 @@ export class cNew {}`); assert.deepEqual(host.traces, [ "TSFILE: /src/core/anotherModule.js", "TSFILE: /src/core/anotherModule.d.ts", + "TSFILE: /src/core/anotherModule.d.ts.map", "TSFILE: /src/core/index.js", "TSFILE: /src/core/index.d.ts", + "TSFILE: /src/core/index.d.ts.map", "TSFILE: /src/logic/index.js", "TSFILE: /src/logic/index.js.map", "TSFILE: /src/logic/index.d.ts", From 2787a2793ad791c81891768a837fc10c2abed40f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 Oct 2018 09:31:04 -0700 Subject: [PATCH 049/262] Skip writing json file if it is going to overwrite same location Fixes #24715 --- src/compiler/emitter.ts | 4 +++- .../requireOfJsonFileWithoutOutDir.errors.txt | 20 ------------------- 2 files changed, 3 insertions(+), 21 deletions(-) delete mode 100644 tests/baselines/reference/requireOfJsonFileWithoutOutDir.errors.txt diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 6b4b3a5c510..8617c8fccde 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -52,7 +52,9 @@ namespace ts { else { const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it - const jsFilePath = options.emitDeclarationOnly ? undefined : ownOutputFilePath; + const isJsonEmittedToSameLocation = isJsonSourceFile(sourceFile) && + comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error const isJs = isSourceFileJS(sourceFile); diff --git a/tests/baselines/reference/requireOfJsonFileWithoutOutDir.errors.txt b/tests/baselines/reference/requireOfJsonFileWithoutOutDir.errors.txt deleted file mode 100644 index 07f0f1b84d7..00000000000 --- a/tests/baselines/reference/requireOfJsonFileWithoutOutDir.errors.txt +++ /dev/null @@ -1,20 +0,0 @@ -error TS5055: Cannot write file 'tests/cases/compiler/b.json' because it would overwrite input file. - Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig. - - -!!! error TS5055: Cannot write file 'tests/cases/compiler/b.json' because it would overwrite input file. -!!! error TS5055: Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig. -==== tests/cases/compiler/file1.ts (0 errors) ==== - import b1 = require('./b.json'); - let x = b1.a; - import b2 = require('./b.json'); - if (x) { - let b = b2.b; - x = (b1.b === b); - } - -==== tests/cases/compiler/b.json (0 errors) ==== - { - "a": true, - "b": "hello" - } \ No newline at end of file From 578f8db7d903e9a77ccc3ebc392facc5663415f5 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 Oct 2018 12:00:45 -0700 Subject: [PATCH 050/262] Add test cases for transitive reference with different module resolution --- src/testRunner/unittests/tsbuild.ts | 61 +++++++++++--- src/testRunner/unittests/tsbuildWatchMode.ts | 85 ++++++++++++++------ 2 files changed, 110 insertions(+), 36 deletions(-) diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index c96e12618f4..68d46f07c81 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -376,27 +376,64 @@ export class cNew {}`); "/src/b.js", "/src/b.d.ts", "/src/c.js" ]; - it("verify that it builds correctly", () => { + const expectedFileTraces = [ + ...getLibs(), + "/src/a.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.ts", + ...getLibs(), + "/src/a.d.ts", + "/src/b.d.ts", + "/src/refs/a.d.ts", + "/src/c.ts" + ]; + + function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray, expectedDiagnostics: DiagnosticMessage[], expectedFileTraces: ReadonlyArray) { const fs = projFs.shadow(); const host = new fakes.SolutionBuilderHost(fs); + modifyDiskLayout(fs); const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true }); builder.buildAllProjects(); - host.assertDiagnosticMessages(/*empty*/); + host.assertDiagnosticMessages(...expectedDiagnostics); for (const output of allExpectedOutputs) { assert(fs.existsSync(output), `Expect file ${output} to exist`); } - assert.deepEqual(host.traces, [ + assert.deepEqual(host.traces, expectedFileTraces); + } + + function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") { + fs.writeFileSync("/src/b.ts", `import {A} from 'a'; +export const b = new A();`); + fs.writeFileSync("/src/tsconfig.b.json", JSON.stringify({ + compilerOptions: { + composite: true, + moduleResolution + }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }] + })); + } + + it("verify that it builds correctly", () => { + verifyBuild(noop, allExpectedOutputs, emptyArray, expectedFileTraces); + }); + + it("verify that it builds correctly when the referenced project uses different module resolution", () => { + verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "classic"), allExpectedOutputs, emptyArray, expectedFileTraces); + }); + + it("verify that it build reports error about module not found with node resolution with external module name", () => { + // Error in b build only a + const allExpectedOutputs = ["/src/a.js", "/src/a.d.ts"]; + const expectedFileTraces = [ ...getLibs(), "/src/a.ts", - ...getLibs(), - "/src/a.d.ts", - "/src/b.ts", - ...getLibs(), - "/src/a.d.ts", - "/src/b.d.ts", - "/src/refs/a.d.ts", - "/src/c.ts" - ]); + ]; + verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "node"), + allExpectedOutputs, + [Diagnostics.Cannot_find_module_0], + expectedFileTraces); }); }); } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 468c23c2759..7e0405e31e6 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -638,6 +638,29 @@ export function gfoo() { } : fileFromDisk; } + function dtsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.d.ts`); + } + + function jsFile(extensionLessFile: string) { + return getFilePathInProject(project, `${extensionLessFile}.js`); + } + + function verifyWatchState( + host: WatchedSystem, + watch: Watch, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + expectedWatchedDirectories?: ReadonlyArray) { + checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); + verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); + for (const [file, deps] of dependencies) { + verifyDependencies(watch, file, deps); + } + } + function getTsConfigFile(multiFolder: boolean, fileFromDisk: File, folder: string): File { if (!multiFolder) return fileFromDisk; @@ -703,14 +726,6 @@ export function gfoo() { [cTs.path, [cTs.path, refs.path, bDts]] ]; - function jsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.js`); - } - - function dtsFile(extensionLessFile: string) { - return getFilePathInProject(project, `${extensionLessFile}.d.ts`); - } - function createSolutionAndWatchMode() { return createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), configToBuild, configToBuild, getOutputFileStamps); } @@ -724,21 +739,7 @@ export function gfoo() { } function verifyProgram(host: WatchedSystem, watch: Watch) { - verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies); - } - - function verifyWatchState( - host: WatchedSystem, - watch: Watch, - expectedProgramFiles: ReadonlyArray, - expectedWatchedFiles: ReadonlyArray, - expectedWatchedDirectoriesRecursive: ReadonlyArray, - dependencies: ReadonlyArray<[string, ReadonlyArray]>) { - checkProgramActualFiles(watch().getProgram(), expectedProgramFiles); - verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories); - for (const [file, deps] of dependencies) { - verifyDependencies(watch, file, deps); - } + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories); } function verifyProject(host: WatchedSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray) { @@ -782,7 +783,7 @@ export function gfoo() { host.checkTimeoutQueueLengthAndRun(1); checkOutputErrorsIncremental(host, expectedEditErrors); - verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies); + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, expectedWatchedDirectories); if (revert) { revert(host); @@ -961,6 +962,42 @@ export function gfoo() { describe("when config files are side by side", () => { verifyTransitiveReferences(/*multiFolder*/ false); + + it("when referenced project uses different module resolution", () => { + const bTs: File = { + path: bTsFile.path, + content: `import {A} from "a";export const b = new A();` + }; + const bTsconfig: File = { + path: bTsconfigFile.path, + content: JSON.stringify({ + compilerOptions: { composite: true, moduleResolution: "classic" }, + files: ["b.ts"], + references: [{ path: "tsconfig.a.json" }] + }) + }; + const allFiles = [libFile, aTsFile, bTs, cTsFile, aTsconfigFile, bTsconfig, cTsconfigFile, refs]; + const aDts = dtsFile("a"), bDts = dtsFile("b"); + const expectedFiles = [jsFile("a"), aDts, jsFile("b"), bDts, jsFile("c")]; + const expectedProgramFiles = [cTsFile.path, libFile.path, aDts, refs.path, bDts]; + const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfigFile.path, bTsconfigFile.path, aTsconfigFile.path).map(s => s.toLowerCase()); + const expectedWatchedDirectoriesRecursive = [ + getFilePathInProject(project, "refs"), // Failed lookup since refs/a.ts does not exist + ...projectSystem.getTypeRootsFromLocation(getProjectPath(project)) + ].map(s => s.toLowerCase()); + + const defaultDependencies: ReadonlyArray<[string, ReadonlyArray]> = [ + [aDts, [aDts]], + [bDts, [bDts, aDts]], + [refs.path, [refs.path]], + [cTsFile.path, [cTsFile.path, refs.path, bDts]] + ]; + function getOutputFileStamps(host: WatchedSystem) { + return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); + } + const { host, watch } = createSolutionAndWatchModeOfProject(allFiles, getProjectPath(project), "tsconfig.c.json", "tsconfig.c.json", getOutputFileStamps); + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies); + }); }); describe("when config files are in side by side folders", () => { verifyTransitiveReferences(/*multiFolder*/ true); From 4d504f9b3022659b7b62016cab4704e1840f9437 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 11 Oct 2018 12:33:29 -0700 Subject: [PATCH 051/262] assertNever special-cases nodes with SyntaxKind (#27712) * assertNever special-cases nodes with SyntaxKind * Fix single-quote lint * Use stringify when not a node --- src/compiler/core.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index db18d8c9551..7e9813658f5 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1602,8 +1602,9 @@ namespace ts { return value; } - export function assertNever(member: never, message?: string, stackCrawlMark?: AnyFunction): never { - return fail(message || `Illegal value: ${member}`, stackCrawlMark || assertNever); + export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never { + const detail = "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member); + return fail(`${message} ${detail}`, stackCrawlMark || assertNever); } export function getFunctionName(func: AnyFunction) { From 92f3f1cde0984b01dac3c101560df8ab18c2534b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 11 Oct 2018 14:19:32 -0700 Subject: [PATCH 052/262] Allow files to be included by `*.json` pattern in include of tsconfig Fixes #25636 --- src/compiler/commandLineParser.ts | 26 +++++++++++++++++-- src/compiler/program.ts | 4 +-- src/compiler/utilities.ts | 14 ++++++++-- src/testRunner/unittests/tsbuild.ts | 19 ++++++++++++++ .../tests/tsconfig_withIncludeOfJson.json | 16 ++++++++++++ 5 files changed, 73 insertions(+), 6 deletions(-) create mode 100644 tests/projects/resolveJsonModuleAndComposite/tests/tsconfig_withIncludeOfJson.json diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 58f1e8fdaa3..56767b9420b 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -2509,11 +2509,16 @@ namespace ts { // via wildcard, and to handle extension priority. const wildcardFileMap = createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + const wildCardJsonFileMap = createMap(); const { filesSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories } = spec; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. const supportedExtensions = getSupportedExtensions(options, extraFileExtensions); + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. @@ -2524,8 +2529,25 @@ namespace ts { } } + let jsonOnlyIncludeRegexes: ReadonlyArray | undefined; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (const file of host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + for (const file of host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) { + if (fileExtensionIs(file, Extension.Json)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + const includes = validatedIncludeSpecs.filter(s => endsWith(s, Extension.Json)); + const includeFilePatterns = map(getRegularExpressionsForWildcards(includes, basePath, "files"), pattern => `^${pattern}$`); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(pattern => getRegexFromPattern(pattern, host.useCaseSensitiveFileNames)) : emptyArray; + } + const includeIndex = findIndex(jsonOnlyIncludeRegexes, re => re.test(file)); + if (includeIndex !== -1) { + const key = keyMapper(file); + if (!literalFileMap.has(key) && !wildCardJsonFileMap.has(key)) { + wildCardJsonFileMap.set(key, file); + } + } + continue; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -2553,7 +2575,7 @@ namespace ts { const wildcardFiles = arrayFrom(wildcardFileMap.values()); return { - fileNames: literalFiles.concat(wildcardFiles), + fileNames: literalFiles.concat(wildcardFiles, arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories, spec }; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 17a10137d20..cdfcfe6173b 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -610,7 +610,7 @@ namespace ts { const programDiagnostics = createDiagnosticCollection(); const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); - const supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? [...supportedExtensions, Extension.Json] : undefined; + const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input const hasEmitBlockingDiagnostics = createMap(); @@ -1965,7 +1965,7 @@ namespace ts { refFile?: SourceFile): SourceFile | undefined { if (hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { + if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) { if (fail) fail(Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 564e74fc4d3..acaabdab9c7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7738,7 +7738,7 @@ namespace ts { return `^(${pattern})${terminator}`; } - function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { + export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { if (specs === undefined || specs.length === 0) { return undefined; } @@ -8003,11 +8003,13 @@ namespace ts { * List of supported extensions in order of file resolution precedence. */ export const supportedTSExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensionsWithJson: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ export const supportedTSExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; export const supportedJSExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; export const supportedJSAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; + const allSupportedExtensionsWithJson: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; @@ -8024,6 +8026,13 @@ namespace ts { return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } + export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: ReadonlyArray): ReadonlyArray { + if (!options || !options.resolveJsonModule) { return supportedExtensions; } + if (supportedExtensions === allSupportedExtensions) { return allSupportedExtensionsWithJson; } + if (supportedExtensions === supportedTSExtensions) { return supportedTSExtensionsWithJson; } + return [...supportedExtensions, Extension.Json]; + } + function isJSLike(scriptKind: ScriptKind | undefined): boolean { return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX; } @@ -8043,7 +8052,8 @@ namespace ts { export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { if (!fileName) { return false; } - for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) { + const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (const extension of getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)) { if (fileExtensionIs(fileName, extension)) { return true; } diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index 94af1241ab0..dca77505b80 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -276,6 +276,10 @@ export class cNew {}`); function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const fs = projFs.shadow(); + verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages); + } + + function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray, ...expectedDiagnosticMessages: DiagnosticMessage[]) { const host = new fakes.SolutionBuilderHost(fs); const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false }); builder.buildAllProjects(); @@ -292,6 +296,21 @@ export class cNew {}`); verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withInclude.json", Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern); }); + it("with resolveJsonModule and include of *.json along with other include", () => { + verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeOfJson.json"); + }); + + it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => { + const fs = projFs.shadow(); + fs.rimrafSync("/src/tests/src/hello.json"); + fs.writeFileSync("/src/tests/src/index.json", JSON.stringify({ hello: "world" })); + fs.writeFileSync("/src/tests/src/index.ts", `import hello from "./index.json" + +export default hello.hello`); + const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/index.json"]; + verifyProjectWithResolveJsonModuleWithFs(fs, "/src/tests/tsconfig_withIncludeOfJson.json", allExpectedOutputs); + }); + it("with resolveJsonModule and files containing json file", () => { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withFiles.json"); }); diff --git a/tests/projects/resolveJsonModuleAndComposite/tests/tsconfig_withIncludeOfJson.json b/tests/projects/resolveJsonModuleAndComposite/tests/tsconfig_withIncludeOfJson.json new file mode 100644 index 00000000000..72d960b6fba --- /dev/null +++ b/tests/projects/resolveJsonModuleAndComposite/tests/tsconfig_withIncludeOfJson.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "composite": true, + "target": "esnext", + "moduleResolution": "node", + "module": "commonjs", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "dist", + "skipDefaultLibCheck": true + }, + "include": [ + "src/**/*", "src/**/*.json" + ] +} \ No newline at end of file From c0729a22fd364b42f26ef550b56c8132fca079f4 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 10 Oct 2018 14:51:17 -0700 Subject: [PATCH 053/262] Use string/number signature to get contextual type Fixes #26587 --- src/compiler/checker.ts | 2 + ...textualTypeWithUnionTypeIndexSignatures.js | 8 +- ...alTypeWithUnionTypeIndexSignatures.symbols | 4 +- ...tualTypeWithUnionTypeIndexSignatures.types | 24 +++--- ...ntextualTypingOfOptionalMembers.errors.txt | 80 ------------------- .../contextualTypingOfOptionalMembers.types | 8 +- .../reference/narrowingByTypeofInSwitch.types | 2 +- .../reference/tsxAttributeResolution10.types | 2 +- .../unionTypeWithIndexedLiteralType.js | 8 ++ .../unionTypeWithIndexedLiteralType.symbols | 20 +++++ .../unionTypeWithIndexedLiteralType.types | 16 ++++ .../unionTypeWithIndexedLiteralType.ts | 4 + ...textualTypeWithUnionTypeIndexSignatures.ts | 4 +- 13 files changed, 76 insertions(+), 106 deletions(-) delete mode 100644 tests/baselines/reference/contextualTypingOfOptionalMembers.errors.txt create mode 100644 tests/baselines/reference/unionTypeWithIndexedLiteralType.js create mode 100644 tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols create mode 100644 tests/baselines/reference/unionTypeWithIndexedLiteralType.types create mode 100644 tests/cases/compiler/unionTypeWithIndexedLiteralType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index bc93cce86b8..dd8886b2854 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16708,6 +16708,8 @@ namespace ts { return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, IndexKind.Number) || + getIndexTypeOfContextualType(type, IndexKind.String); } return undefined; }, /*noReductions*/ true); diff --git a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.js b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.js index 2c07f461424..0ddadeab96c 100644 --- a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.js +++ b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.js @@ -39,7 +39,7 @@ interface IWithNumberIndexSignature2 { // If S is not empty, U has a string index signature of a union type of // the types of the string index signatures from each type in S. var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { z: a => a }; // a should be number -var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be any +var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be number (because of index signature of IWithStringIndexSignature1) var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: "hello" }; var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a.toString() }; // a should be number var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // a should be number @@ -49,7 +49,7 @@ var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // If S is not empty, U has a numeric index signature of a union type of // the types of the numeric index signatures from each type in S. var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 1: a => a }; // a should be number -var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be any +var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be number (because of index signature of IWithNumberIndexSignature1) var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: "hello" }; var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a.toString() }; // a should be number var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a }; // a should be number @@ -66,7 +66,7 @@ var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a }; // If S is not empty, U has a string index signature of a union type of // the types of the string index signatures from each type in S. var x = { z: function (a) { return a; } }; // a should be number -var x = { foo: function (a) { return a; } }; // a should be any +var x = { foo: function (a) { return a; } }; // a should be number (because of index signature of IWithStringIndexSignature1) var x = { foo: "hello" }; var x2 = { z: function (a) { return a.toString(); } }; // a should be number var x2 = { z: function (a) { return a; } }; // a should be number @@ -74,7 +74,7 @@ var x2 = { z: function (a) { return a; } }; // a should be number // If S is not empty, U has a numeric index signature of a union type of // the types of the numeric index signatures from each type in S. var x3 = { 1: function (a) { return a; } }; // a should be number -var x3 = { 0: function (a) { return a; } }; // a should be any +var x3 = { 0: function (a) { return a; } }; // a should be number (because of index signature of IWithNumberIndexSignature1) var x3 = { 0: "hello" }; var x4 = { 1: function (a) { return a.toString(); } }; // a should be number var x4 = { 1: function (a) { return a; } }; // a should be number diff --git a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.symbols b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.symbols index 69e9e9e52ea..d2959a005e2 100644 --- a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.symbols +++ b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.symbols @@ -74,7 +74,7 @@ var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { z: a => a }; >a : Symbol(a, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 39, 70)) >a : Symbol(a, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 39, 70)) -var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be any +var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be number (because of index signature of IWithStringIndexSignature1) >x : Symbol(x, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 39, 3), Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 40, 3), Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 41, 3)) >IWithNoStringIndexSignature : Symbol(IWithNoStringIndexSignature, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 7, 1)) >IWithStringIndexSignature1 : Symbol(IWithStringIndexSignature1, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 14, 1)) @@ -118,7 +118,7 @@ var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 1: a => a } >a : Symbol(a, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 49, 71)) >a : Symbol(a, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 49, 71)) -var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be any +var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be number (because of index signature of IWithNumberIndexSignature1) >x3 : Symbol(x3, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 49, 3), Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 50, 3), Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 51, 3)) >IWithNoNumberIndexSignature : Symbol(IWithNoNumberIndexSignature, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 11, 1)) >IWithNumberIndexSignature1 : Symbol(IWithNumberIndexSignature1, Decl(contextualTypeWithUnionTypeIndexSignatures.ts, 20, 1)) diff --git a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.types b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.types index 985467ae7ea..6c4638ad75a 100644 --- a/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.types +++ b/tests/baselines/reference/contextualTypeWithUnionTypeIndexSignatures.types @@ -54,13 +54,13 @@ var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { z: a => a }; >a : number >a : number -var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be any +var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be number (because of index signature of IWithStringIndexSignature1) >x : IWithNoStringIndexSignature | IWithStringIndexSignature1 ->{ foo: a => a } : { foo: (a: any) => any; } ->foo : (a: any) => any ->a => a : (a: any) => any ->a : any ->a : any +>{ foo: a => a } : { foo: (a: number) => number; } +>foo : (a: number) => number +>a => a : (a: number) => number +>a : number +>a : number var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: "hello" }; >x : IWithNoStringIndexSignature | IWithStringIndexSignature1 @@ -99,13 +99,13 @@ var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 1: a => a } >a : number >a : number -var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be any +var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be number (because of index signature of IWithNumberIndexSignature1) >x3 : IWithNoNumberIndexSignature | IWithNumberIndexSignature1 ->{ 0: a => a } : { 0: (a: any) => any; } ->0 : (a: any) => any ->a => a : (a: any) => any ->a : any ->a : any +>{ 0: a => a } : { 0: (a: number) => number; } +>0 : (a: number) => number +>a => a : (a: number) => number +>a : number +>a : number var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: "hello" }; >x3 : IWithNoNumberIndexSignature | IWithNumberIndexSignature1 diff --git a/tests/baselines/reference/contextualTypingOfOptionalMembers.errors.txt b/tests/baselines/reference/contextualTypingOfOptionalMembers.errors.txt deleted file mode 100644 index 02c94400e21..00000000000 --- a/tests/baselines/reference/contextualTypingOfOptionalMembers.errors.txt +++ /dev/null @@ -1,80 +0,0 @@ -tests/cases/compiler/index.tsx(73,34): error TS7006: Parameter 's' implicitly has an 'any' type. - - -==== tests/cases/compiler/index.tsx (1 errors) ==== - interface ActionsObject { - [prop: string]: (state: State) => State; - } - - interface Options { - state?: State; - view?: (state: State, actions: Actions) => any; - actions: string | Actions; - } - - declare function app>(obj: Options): void; - - app({ - state: 100, - actions: { - foo: s => s // Should be typed number => number - }, - view: (s, a) => undefined as any, - }); - - - interface Bar { - bar: (a: number) => void; - } - - declare function foo(x: string | T): T; - - const y = foo({ - bar(x) { // Should be typed number => void - } - }); - - interface Options2 { - state?: State; - view?: (state: State, actions: Actions) => any; - actions?: Actions; - } - - declare function app2>(obj: Options2): void; - - app2({ - state: 100, - actions: { - foo: s => s // Should be typed number => number - }, - view: (s, a) => undefined as any, - }); - - - type ActionsArray = ((state: State) => State)[]; - - declare function app3>(obj: Options): void; - - app3({ - state: 100, - actions: [ - s => s // Should be typed number => number - ], - view: (s, a) => undefined as any, - }); - - namespace JSX { - export interface Element {} - export interface IntrinsicElements {} - } - - interface ActionsObjectOr { - [prop: string]: ((state: State) => State) | State; - } - - declare function App4>(props: Options["actions"] & { state: State }): JSX.Element; - - const a = s} />; // TODO: should be number => number, but JSX resolution is missing an inferential pass - ~ -!!! error TS7006: Parameter 's' implicitly has an 'any' type. - \ No newline at end of file diff --git a/tests/baselines/reference/contextualTypingOfOptionalMembers.types b/tests/baselines/reference/contextualTypingOfOptionalMembers.types index 389ad15a579..f4a9e23190d 100644 --- a/tests/baselines/reference/contextualTypingOfOptionalMembers.types +++ b/tests/baselines/reference/contextualTypingOfOptionalMembers.types @@ -183,8 +183,8 @@ const a = s} />; // TODO: should be number => number >App4 : >(props: (string & { state: State; }) | (Actions & { state: State; })) => JSX.Element >state : number >100 : 100 ->foo : (s: any) => any ->s => s : (s: any) => any ->s : any ->s : any +>foo : (s: number) => number +>s => s : (s: number) => number +>s : number +>s : number diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index 000eea75f79..342aeb670ec 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -543,7 +543,7 @@ function multipleGenericFuse(xy: X | case 'function': return [xy, 1]; >'function' : "function" ->[xy, 1] : [X, number] +>[xy, 1] : [X, 1] >xy : X >1 : 1 diff --git a/tests/baselines/reference/tsxAttributeResolution10.types b/tests/baselines/reference/tsxAttributeResolution10.types index 4acabaffa4d..ddc834fe4c7 100644 --- a/tests/baselines/reference/tsxAttributeResolution10.types +++ b/tests/baselines/reference/tsxAttributeResolution10.types @@ -35,7 +35,7 @@ export class MyComponent { ; > : JSX.Element >MyComponent : typeof MyComponent ->bar : boolean +>bar : true >true : true // Should be ok diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.js b/tests/baselines/reference/unionTypeWithIndexedLiteralType.js new file mode 100644 index 00000000000..8ed8d32b3f5 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.js @@ -0,0 +1,8 @@ +//// [unionTypeWithIndexedLiteralType.ts] +interface I { x: number; } +interface Idx { [index: string]: U; } +type U = Idx | I | "lit"; +const u: U = { x: "lit" }; + +//// [unionTypeWithIndexedLiteralType.js] +var u = { x: "lit" }; diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols b/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols new file mode 100644 index 00000000000..bf9502ee5a5 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/unionTypeWithIndexedLiteralType.ts === +interface I { x: number; } +>I : Symbol(I, Decl(unionTypeWithIndexedLiteralType.ts, 0, 0)) +>x : Symbol(I.x, Decl(unionTypeWithIndexedLiteralType.ts, 0, 13)) + +interface Idx { [index: string]: U; } +>Idx : Symbol(Idx, Decl(unionTypeWithIndexedLiteralType.ts, 0, 26)) +>index : Symbol(index, Decl(unionTypeWithIndexedLiteralType.ts, 1, 17)) +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) + +type U = Idx | I | "lit"; +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) +>Idx : Symbol(Idx, Decl(unionTypeWithIndexedLiteralType.ts, 0, 26)) +>I : Symbol(I, Decl(unionTypeWithIndexedLiteralType.ts, 0, 0)) + +const u: U = { x: "lit" }; +>u : Symbol(u, Decl(unionTypeWithIndexedLiteralType.ts, 3, 5)) +>U : Symbol(U, Decl(unionTypeWithIndexedLiteralType.ts, 1, 37)) +>x : Symbol(x, Decl(unionTypeWithIndexedLiteralType.ts, 3, 14)) + diff --git a/tests/baselines/reference/unionTypeWithIndexedLiteralType.types b/tests/baselines/reference/unionTypeWithIndexedLiteralType.types new file mode 100644 index 00000000000..47d1d6832e1 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexedLiteralType.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/unionTypeWithIndexedLiteralType.ts === +interface I { x: number; } +>x : number + +interface Idx { [index: string]: U; } +>index : string + +type U = Idx | I | "lit"; +>U : U + +const u: U = { x: "lit" }; +>u : U +>{ x: "lit" } : { x: "lit"; } +>x : "lit" +>"lit" : "lit" + diff --git a/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts b/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts new file mode 100644 index 00000000000..c594c6d1c9d --- /dev/null +++ b/tests/cases/compiler/unionTypeWithIndexedLiteralType.ts @@ -0,0 +1,4 @@ +interface I { x: number; } +interface Idx { [index: string]: U; } +type U = Idx | I | "lit"; +const u: U = { x: "lit" }; \ No newline at end of file diff --git a/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts b/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts index 9132c61f4fe..a7408672118 100644 --- a/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts +++ b/tests/cases/conformance/types/union/contextualTypeWithUnionTypeIndexSignatures.ts @@ -38,7 +38,7 @@ interface IWithNumberIndexSignature2 { // If S is not empty, U has a string index signature of a union type of // the types of the string index signatures from each type in S. var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { z: a => a }; // a should be number -var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be any +var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: a => a }; // a should be number (because of index signature of IWithStringIndexSignature1) var x: IWithNoStringIndexSignature | IWithStringIndexSignature1 = { foo: "hello" }; var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a.toString() }; // a should be number var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // a should be number @@ -48,7 +48,7 @@ var x2: IWithStringIndexSignature1 | IWithStringIndexSignature2 = { z: a => a }; // If S is not empty, U has a numeric index signature of a union type of // the types of the numeric index signatures from each type in S. var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 1: a => a }; // a should be number -var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be any +var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: a => a }; // a should be number (because of index signature of IWithNumberIndexSignature1) var x3: IWithNoNumberIndexSignature | IWithNumberIndexSignature1 = { 0: "hello" }; var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a.toString() }; // a should be number var x4: IWithNumberIndexSignature1 | IWithNumberIndexSignature2 = { 1: a => a }; // a should be number \ No newline at end of file From d19fb98ec6e1cfe3f6521bd1cc1dbfcb4e6e82a7 Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Thu, 11 Oct 2018 18:45:51 -0400 Subject: [PATCH 054/262] When instantiating a mapped type, clone the type parameter. (#27597) This gives the type parameter returned by getTypeParameterFromMappedType an accurate constraint. Fixes #27596. --- src/compiler/checker.ts | 8 ++++++- .../mappedTypeParameterConstraint.js | 14 +++++++++++ .../mappedTypeParameterConstraint.symbols | 23 +++++++++++++++++++ .../mappedTypeParameterConstraint.types | 14 +++++++++++ .../compiler/mappedTypeParameterConstraint.ts | 6 +++++ 5 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/mappedTypeParameterConstraint.js create mode 100644 tests/baselines/reference/mappedTypeParameterConstraint.symbols create mode 100644 tests/baselines/reference/mappedTypeParameterConstraint.types create mode 100644 tests/cases/compiler/mappedTypeParameterConstraint.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index bc93cce86b8..77d27de786b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6850,7 +6850,7 @@ namespace ts { function getConstraintTypeFromMappedType(type: MappedType) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type: MappedType) { @@ -10413,6 +10413,12 @@ namespace ts { const result = createObjectType(type.objectFlags | ObjectFlags.Instantiated, type.symbol); if (type.objectFlags & ObjectFlags.Mapped) { (result).declaration = (type).declaration; + // C.f. instantiateSignature + const origTypeParameter = getTypeParameterFromMappedType(type); + const freshTypeParameter = cloneTypeParameter(origTypeParameter); + (result).typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; diff --git a/tests/baselines/reference/mappedTypeParameterConstraint.js b/tests/baselines/reference/mappedTypeParameterConstraint.js new file mode 100644 index 00000000000..f7715f17993 --- /dev/null +++ b/tests/baselines/reference/mappedTypeParameterConstraint.js @@ -0,0 +1,14 @@ +//// [mappedTypeParameterConstraint.ts] +// Repro for #27596 + +type MyMap = {[P in keyof T]: T[keyof T]}; +function foo(arg: U): MyMap { + return arg; +} + + +//// [mappedTypeParameterConstraint.js] +// Repro for #27596 +function foo(arg) { + return arg; +} diff --git a/tests/baselines/reference/mappedTypeParameterConstraint.symbols b/tests/baselines/reference/mappedTypeParameterConstraint.symbols new file mode 100644 index 00000000000..1609c465005 --- /dev/null +++ b/tests/baselines/reference/mappedTypeParameterConstraint.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/mappedTypeParameterConstraint.ts === +// Repro for #27596 + +type MyMap = {[P in keyof T]: T[keyof T]}; +>MyMap : Symbol(MyMap, Decl(mappedTypeParameterConstraint.ts, 0, 0)) +>T : Symbol(T, Decl(mappedTypeParameterConstraint.ts, 2, 11)) +>P : Symbol(P, Decl(mappedTypeParameterConstraint.ts, 2, 18)) +>T : Symbol(T, Decl(mappedTypeParameterConstraint.ts, 2, 11)) +>T : Symbol(T, Decl(mappedTypeParameterConstraint.ts, 2, 11)) +>T : Symbol(T, Decl(mappedTypeParameterConstraint.ts, 2, 11)) + +function foo(arg: U): MyMap { +>foo : Symbol(foo, Decl(mappedTypeParameterConstraint.ts, 2, 45)) +>U : Symbol(U, Decl(mappedTypeParameterConstraint.ts, 3, 13)) +>arg : Symbol(arg, Decl(mappedTypeParameterConstraint.ts, 3, 16)) +>U : Symbol(U, Decl(mappedTypeParameterConstraint.ts, 3, 13)) +>MyMap : Symbol(MyMap, Decl(mappedTypeParameterConstraint.ts, 0, 0)) +>U : Symbol(U, Decl(mappedTypeParameterConstraint.ts, 3, 13)) + + return arg; +>arg : Symbol(arg, Decl(mappedTypeParameterConstraint.ts, 3, 16)) +} + diff --git a/tests/baselines/reference/mappedTypeParameterConstraint.types b/tests/baselines/reference/mappedTypeParameterConstraint.types new file mode 100644 index 00000000000..54af46ecfcf --- /dev/null +++ b/tests/baselines/reference/mappedTypeParameterConstraint.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/mappedTypeParameterConstraint.ts === +// Repro for #27596 + +type MyMap = {[P in keyof T]: T[keyof T]}; +>MyMap : MyMap + +function foo(arg: U): MyMap { +>foo : (arg: U) => MyMap +>arg : U + + return arg; +>arg : U +} + diff --git a/tests/cases/compiler/mappedTypeParameterConstraint.ts b/tests/cases/compiler/mappedTypeParameterConstraint.ts new file mode 100644 index 00000000000..16b37999c92 --- /dev/null +++ b/tests/cases/compiler/mappedTypeParameterConstraint.ts @@ -0,0 +1,6 @@ +// Repro for #27596 + +type MyMap = {[P in keyof T]: T[keyof T]}; +function foo(arg: U): MyMap { + return arg; +} From ec0e8cbe2b1a229693576c084a5f797757d327ce Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 11 Oct 2018 16:15:38 -0700 Subject: [PATCH 055/262] noImplicitAny as suggestion (#27693) * noImplicitAny as suggestion Note that not all noImplicitAny errors turn into suggestions. In particular, 1. reportErrorsFromWidening does not, because it doesn't log an error that infer-from-usage fixes, and fixing it would require otherwise-unnecessary code. 2. auto types do not have implicit any suggestions, because that would require running control flow in noImplicitAny mode. * Rename reportImplicitAny+forbid it for non-checkJS In JS, you only get implicit any errors/suggestions with checkJS or ts-check turned on. * Update baselines * Use isCheckJsEnabledForFile * Remove noImplicitAny parameter since it's in scope already --- src/compiler/checker.ts | 62 +++++++++---------- .../unittests/tsserverProjectSystem.ts | 2 +- .../fourslash/annotateWithTypeFromJSDoc1.ts | 7 +-- .../fourslash/annotateWithTypeFromJSDoc3.ts | 13 ++-- .../codeFixUnusedIdentifier_suggestion.ts | 5 ++ .../noSuggestionDiagnosticsOnParseError.ts | 11 +++- ...refactorConvertToEs6Module_export_named.ts | 8 +-- .../fourslash/unusedLocalsInFunction2.ts | 2 +- 8 files changed, 61 insertions(+), 49 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 77d27de786b..8814f85c4ac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4915,9 +4915,7 @@ namespace ts { } const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, t => !!(t.flags & ~TypeFlags.Nullable)) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; @@ -4992,9 +4990,7 @@ namespace ts { return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -5044,8 +5040,8 @@ namespace ts { if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -5145,9 +5141,9 @@ namespace ts { type = isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -5328,14 +5324,12 @@ namespace ts { } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -13282,8 +13276,12 @@ namespace ts { return errorReported; } - function reportImplicitAnyError(declaration: Declaration, type: Type) { + function reportImplicitAny(declaration: Declaration, type: Type) { const typeAsString = typeToString(getWidenedType(type)); + if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } let diagnostic: DiagnosticMessage; switch (declaration.kind) { case SyntaxKind.BinaryExpression: @@ -13306,26 +13304,28 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!(declaration as NamedDeclaration).name) { + if (noImplicitAny && !(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case SyntaxKind.MappedType: - error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { if (produceDiagnostics && noImplicitAny && type.flags & TypeFlags.ContainsWideningType) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } @@ -22319,15 +22319,11 @@ namespace ts { isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); if (isInJSFile(declaration)) { if (widened.flags & TypeFlags.Nullable) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -23318,8 +23314,8 @@ namespace ts { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } const type = getTypeFromMappedTypeNode(node); @@ -24343,8 +24339,8 @@ namespace ts { if (produceDiagnostics && !getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & FunctionFlags.Generator && nodeIsPresent(body)) { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9c4d776d54d..77c486f3f67 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -4981,7 +4981,7 @@ namespace ts.projectSystem { checkErrorMessage(session, "suggestionDiag", { file: file.path, diagnostics: [ - createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecssary*/ true) + createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecessary*/ true), ], }); checkCompleteEvent(session, 2, expectedSequenceId); diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts index ef626fd358d..5e18925fdfe 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts @@ -4,10 +4,9 @@ /////** @type {number} */ ////var [|x|]; -verify.getSuggestionDiagnostics([{ - message: "JSDoc types may be moved to TypeScript types.", - code: 80004, -}]); +verify.getSuggestionDiagnostics([ + { message: "JSDoc types may be moved to TypeScript types.", code: 80004 }, + { message: "Variable 'x' implicitly has an 'any' type.", code: 7005 }]); verify.codeFix({ description: "Annotate with type from JSDoc", diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts index c5013b80cf1..7e064f8dae4 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts @@ -6,14 +6,17 @@ //// * @param alpha - the other best parameter //// * @param {*} beta - I have no idea how this got here //// */ -////function [|f|](x, y, z: string, alpha, beta) { +////function [|f|]([|x|], [|y|], z: string, [|alpha|], [|beta|]) { //// x; y; z; alpha; beta; ////} -verify.getSuggestionDiagnostics([{ - message: "JSDoc types may be moved to TypeScript types.", - code: 80004, -}]); +const [r0, r1, r2, r3, r4] = test.ranges(); +verify.getSuggestionDiagnostics([ + {message: "JSDoc types may be moved to TypeScript types.", code: 80004, range: r0}, + {message: "Parameter 'x' implicitly has an 'any' type.", code: 7006, range: r1 }, + {message: "Parameter 'y' implicitly has an 'any' type.", code: 7006, range: r2 }, + {message: "Parameter 'alpha' implicitly has an 'any' type.", code: 7006, range: r3 }, + {message: "Parameter 'beta' implicitly has an 'any' type.", code: 7006, range: r4 }]); verify.codeFix({ description: "Annotate with type from JSDoc", diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts index b830ccad746..a456299c68a 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts @@ -6,6 +6,11 @@ const [r0, r1] = test.ranges(); verify.getSuggestionDiagnostics([ + { + message: "Parameter 'p' implicitly has an 'any' type.", + range: r0, + code: 7006, + }, { message: "'p' is declared but its value is never read.", range: r0, diff --git a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts index b92a920c3b2..f992f4c8e8e 100644 --- a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts +++ b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts @@ -4,4 +4,13 @@ ////export {}; ////const a = 1 d; -verify.getSuggestionDiagnostics([]); +// Only give suggestions for nodes that do NOT have parse errors +verify.getSuggestionDiagnostics([{ + message: "Variable 'd' implicitly has an 'any' type.", + code: 7005, + range: { + fileName: "/a.ts", + pos: 23, + end: 24, + } +}]); diff --git a/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts b/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts index e7ee2908580..481281a47a4 100644 --- a/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts +++ b/tests/cases/fourslash/refactorConvertToEs6Module_export_named.ts @@ -12,10 +12,10 @@ ////exports.a3 = x => { x; }; ////exports.a4 = x => x; -verify.getSuggestionDiagnostics([{ - message: "File is a CommonJS module; it may be converted to an ES6 module.", - code: 80001, -}]); +const [r0, r1, r2] = test.ranges(); +verify.getSuggestionDiagnostics([ + { message: "File is a CommonJS module; it may be converted to an ES6 module.", code: 80001, range: r0 }, +]); verify.codeFix({ description: "Convert to ES6 module", diff --git a/tests/cases/fourslash/unusedLocalsInFunction2.ts b/tests/cases/fourslash/unusedLocalsInFunction2.ts index 83816e68038..b0b0b69a2fa 100644 --- a/tests/cases/fourslash/unusedLocalsInFunction2.ts +++ b/tests/cases/fourslash/unusedLocalsInFunction2.ts @@ -6,4 +6,4 @@ //// x+1; ////} -verify.rangeAfterCodeFix("var x;"); +verify.rangeAfterCodeFix("var x;", undefined, undefined, 0); From 54a5be1860c7f0de4e6196926d329fbbbf9c6081 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 12 Oct 2018 08:49:04 -0700 Subject: [PATCH 056/262] At '.' in object literal, don't close the object (#27850) * At '.' in object literal, don't close the object * Include diagnostics test --- src/compiler/parser.ts | 10 +++++++++- .../unittests/convertCompilerOptionsFromJson.ts | 3 +-- tests/cases/fourslash/completionsDotInObjectLiteral.ts | 10 ++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 tests/cases/fourslash/completionsDotInObjectLiteral.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 51e56bbdd98..c88aebe799f 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1482,7 +1482,15 @@ namespace ts { // which would be a candidate for improved error reporting. return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); case ParsingContext.ObjectLiteralMembers: - return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); + switch (token()) { + case SyntaxKind.OpenBracketToken: + case SyntaxKind.AsteriskToken: + case SyntaxKind.DotDotDotToken: + case SyntaxKind.DotToken: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case ParsingContext.RestProperties: return isLiteralPropertyName(); case ParsingContext.ObjectBindingElements: diff --git a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts index 6140ab72eee..327bf523160 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts @@ -596,8 +596,7 @@ namespace ts { { compilerOptions: { target: undefined, - module: ModuleKind.ESNext, - types: [] + module: ModuleKind.ESNext }, hasParseErrors: true } diff --git a/tests/cases/fourslash/completionsDotInObjectLiteral.ts b/tests/cases/fourslash/completionsDotInObjectLiteral.ts new file mode 100644 index 00000000000..171e8d2886b --- /dev/null +++ b/tests/cases/fourslash/completionsDotInObjectLiteral.ts @@ -0,0 +1,10 @@ +/// + +////const o = { +//// a: 1, +//// [|.|]/**/ +////[|}|]; + +verify.getSyntacticDiagnostics(test.ranges().map((range): FourSlashInterface.Diagnostic => + ({ code: 1003, message: "Identifier expected.", range }))); +verify.completions({ marker: "", exact: undefined }); From e3bfec5217bf8375e9b16ad117977308d27d240c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 12 Oct 2018 15:58:31 -0700 Subject: [PATCH 057/262] Handle when advancing past , of call expression moves past endPos of formatting Fixes #26513 --- src/services/formatting/formatting.ts | 6 +++--- tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index c1de1574e88..0ed6e84e2c3 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -753,17 +753,17 @@ namespace ts.formatting { const listEndToken = getCloseTokenForOpenToken(listStartToken); if (listEndToken !== SyntaxKind.Unknown && formattingScanner.isOnToken()) { - let tokenInfo = formattingScanner.readTokenInfo(parent); + let tokenInfo: TokenInfo | undefined = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === SyntaxKind.CommaToken && isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } diff --git a/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts new file mode 100644 index 00000000000..30f4d3faf75 --- /dev/null +++ b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts @@ -0,0 +1,7 @@ +/// +////export const strong: StrongParser = verify(fmap(build(() => +//// /*start*/surround('**', compress(some(union([inline]), '**')), '**')),/*end*/ +//// ns => [html('strong', ns)] +////), ([el]) => hasTightStartText(el)); + +format.selection("start", "end"); \ No newline at end of file From b94dfd9cea905b3e9d24feba8ccc2bb9dff6e991 Mon Sep 17 00:00:00 2001 From: Daiki Nishikawa Date: Mon, 15 Oct 2018 10:03:01 +0900 Subject: [PATCH 058/262] delete link --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 27d2b9f323c..c937316603f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -194,6 +194,6 @@ to establish the new baselines as the desired behavior. This will change the fil ## Localization All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json). -If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in [`diagnosticInformationMap.generated.ts`](./src/compiler/diagnosticInformationMap.generated.ts). +If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`. See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages). From bb275b999c6de3a019c57ea6838727c0c9713eee Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Mon, 15 Oct 2018 08:08:33 -0700 Subject: [PATCH 059/262] Update user baselines (#27905) --- tests/baselines/reference/user/jimp.log | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 tests/baselines/reference/user/jimp.log diff --git a/tests/baselines/reference/user/jimp.log b/tests/baselines/reference/user/jimp.log deleted file mode 100644 index 0498af334c2..00000000000 --- a/tests/baselines/reference/user/jimp.log +++ /dev/null @@ -1,10 +0,0 @@ -Exit Code: 1 -Standard output: -node_modules/jimp/jimp.d.ts(248,5): error TS7010: 'parseBitmap', which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/jimp/jimp.d.ts(505,12): error TS7010: 'appendConstructorOption', which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/jimp/jimp.d.ts(555,12): error TS7010: 'measureText', which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/jimp/jimp.d.ts(556,12): error TS7010: 'measureTextHeight', which lacks return-type annotation, implicitly has an 'any' return type. - - - -Standard error: From 709f5f2fc47eb9d28798f5933864d05711720dee Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 15 Oct 2018 10:18:54 -0700 Subject: [PATCH 060/262] Handle circular mapped type instantiations for arrays and tuples --- src/compiler/checker.ts | 12 +++++++++++- src/compiler/types.ts | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 795b893f69e..4d397bcc71c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10365,7 +10365,15 @@ namespace ts { if (typeVariable) { const mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, t => { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; + } + type.instantiating = true; + const result = mapType(mappedTypeVariable, t => { if (t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.InstantiableNonPrimitive | TypeFlags.Object | TypeFlags.Intersection) && t !== wildcardType) { const replacementMapper = createReplacementMapper(typeVariable, t, mapper); return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : @@ -10375,6 +10383,8 @@ namespace ts { } return t; }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 3bd103579f1..5763ab3eff0 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4074,6 +4074,7 @@ namespace ts { templateType?: Type; modifiersType?: Type; resolvedApparentType?: Type; + instantiating?: boolean; } export interface EvolvingArrayType extends ObjectType { From 0c3221c2205f50ec3f0c069ec919f35b7aebfb5a Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 15 Oct 2018 10:24:00 -0700 Subject: [PATCH 061/262] Add regression test --- .../conformance/types/mapped/recursiveMappedTypes.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts index 7a78ad9dc4a..188efa2f51a 100644 --- a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts +++ b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts @@ -12,4 +12,13 @@ type Recurse1 = { type Recurse2 = { [K in keyof Recurse1]: Recurse1[K] -} \ No newline at end of file +} + +// Repro from #27881 + +export type Circular = {[P in keyof T]: Circular}; +type tup = [number, number, number, number]; + +function foo(arg: Circular): tup { + return arg; +} From 3930525678e921d3e2cad96e6424b129c7ada089 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 15 Oct 2018 10:24:10 -0700 Subject: [PATCH 062/262] Accept new baselines --- .../reference/recursiveMappedTypes.errors.txt | 12 ++++++++- .../reference/recursiveMappedTypes.js | 27 ++++++++++++------- .../reference/recursiveMappedTypes.symbols | 25 +++++++++++++++++ .../reference/recursiveMappedTypes.types | 17 ++++++++++++ 4 files changed, 71 insertions(+), 10 deletions(-) diff --git a/tests/baselines/reference/recursiveMappedTypes.errors.txt b/tests/baselines/reference/recursiveMappedTypes.errors.txt index 8279f4f60a6..b702cf7e316 100644 --- a/tests/baselines/reference/recursiveMappedTypes.errors.txt +++ b/tests/baselines/reference/recursiveMappedTypes.errors.txt @@ -31,4 +31,14 @@ tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(12,11): error TS231 [K in keyof Recurse1]: Recurse1[K] ~~~~~~~~~~~~~~ !!! error TS2313: Type parameter 'K' has a circular constraint. - } \ No newline at end of file + } + + // Repro from #27881 + + export type Circular = {[P in keyof T]: Circular}; + type tup = [number, number, number, number]; + + function foo(arg: Circular): tup { + return arg; + } + \ No newline at end of file diff --git a/tests/baselines/reference/recursiveMappedTypes.js b/tests/baselines/reference/recursiveMappedTypes.js index 50610708664..612c9d3fca4 100644 --- a/tests/baselines/reference/recursiveMappedTypes.js +++ b/tests/baselines/reference/recursiveMappedTypes.js @@ -11,19 +11,28 @@ type Recurse1 = { type Recurse2 = { [K in keyof Recurse1]: Recurse1[K] -} +} + +// Repro from #27881 + +export type Circular = {[P in keyof T]: Circular}; +type tup = [number, number, number, number]; + +function foo(arg: Circular): tup { + return arg; +} + //// [recursiveMappedTypes.js] +"use strict"; // Recursive mapped types simply appear empty +exports.__esModule = true; +function foo(arg) { + return arg; +} //// [recursiveMappedTypes.d.ts] -declare type Recurse = { - [K in keyof Recurse]: Recurse[K]; -}; -declare type Recurse1 = { - [K in keyof Recurse2]: Recurse2[K]; -}; -declare type Recurse2 = { - [K in keyof Recurse1]: Recurse1[K]; +export declare type Circular = { + [P in keyof T]: Circular; }; diff --git a/tests/baselines/reference/recursiveMappedTypes.symbols b/tests/baselines/reference/recursiveMappedTypes.symbols index 20ebbedc00a..7c0e2ffaa23 100644 --- a/tests/baselines/reference/recursiveMappedTypes.symbols +++ b/tests/baselines/reference/recursiveMappedTypes.symbols @@ -30,3 +30,28 @@ type Recurse2 = { >Recurse1 : Symbol(Recurse1, Decl(recursiveMappedTypes.ts, 4, 1)) >K : Symbol(K, Decl(recursiveMappedTypes.ts, 11, 5)) } + +// Repro from #27881 + +export type Circular = {[P in keyof T]: Circular}; +>Circular : Symbol(Circular, Decl(recursiveMappedTypes.ts, 12, 1)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 16, 21)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 16, 28)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 16, 21)) +>Circular : Symbol(Circular, Decl(recursiveMappedTypes.ts, 12, 1)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 16, 21)) + +type tup = [number, number, number, number]; +>tup : Symbol(tup, Decl(recursiveMappedTypes.ts, 16, 56)) + +function foo(arg: Circular): tup { +>foo : Symbol(foo, Decl(recursiveMappedTypes.ts, 17, 44)) +>arg : Symbol(arg, Decl(recursiveMappedTypes.ts, 19, 13)) +>Circular : Symbol(Circular, Decl(recursiveMappedTypes.ts, 12, 1)) +>tup : Symbol(tup, Decl(recursiveMappedTypes.ts, 16, 56)) +>tup : Symbol(tup, Decl(recursiveMappedTypes.ts, 16, 56)) + + return arg; +>arg : Symbol(arg, Decl(recursiveMappedTypes.ts, 19, 13)) +} + diff --git a/tests/baselines/reference/recursiveMappedTypes.types b/tests/baselines/reference/recursiveMappedTypes.types index aae3280b605..5741f711e9d 100644 --- a/tests/baselines/reference/recursiveMappedTypes.types +++ b/tests/baselines/reference/recursiveMappedTypes.types @@ -18,3 +18,20 @@ type Recurse2 = { [K in keyof Recurse1]: Recurse1[K] } + +// Repro from #27881 + +export type Circular = {[P in keyof T]: Circular}; +>Circular : Circular + +type tup = [number, number, number, number]; +>tup : [number, number, number, number] + +function foo(arg: Circular): tup { +>foo : (arg: [any, any, any, any]) => [number, number, number, number] +>arg : [any, any, any, any] + + return arg; +>arg : [any, any, any, any] +} + From c184184713d613a5a1dd6023a0429e3fba2d79cc Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 15 Oct 2018 12:47:57 -0700 Subject: [PATCH 063/262] Add getEffectiveConstructSignatures (#27561) * Add helpers that understand constructor functions * getEffectiveConstructSignatures gets construct signatures from type, and call signatures from constructor functions if there are no construct signatures. * getEffectiveConstructSignatureReturnType gets the "JS Class type" for constructor functions, and the return type of signatures for all other declarations. This is a first step toward making constructor functions have construct signatures instead of call signatures, which will also contribute to fixing instantiation of generic constructor functions, which is basically broken right now. Note that the baselines *improve* but, because of the previously mentioned generic problem, are still not correct. Construct signatures for constructor functions and generic constructor functions turns out to be an intertwined problem. * Correct correct originalBaseType And, for now, return anyType for generic constructor functions used as base types. Don't give an incorrect error based on the function's return type, which is usually void. * Add error examples to tests * Add construct signatures instead of getEffective* functions * Fix typo in baseline * Remove pesky newline I thought I got rid of it! * Test of constructor tag on object literal method It doesn't work, and shouldn't in the future, because it's a runtime error. --- src/compiler/checker.ts | 34 +++++++++---------- ...assCanExtendConstructorFunction.errors.txt | 22 ++++++------ .../classCanExtendConstructorFunction.symbols | 11 +++++- .../classCanExtendConstructorFunction.types | 22 +++++++++--- .../reference/constructorFunctions.errors.txt | 4 +-- .../reference/constructorFunctions.symbols | 4 +-- .../reference/constructorFunctions.types | 12 +++---- ...tructorTagOnObjectLiteralMethod.errors.txt | 15 ++++++++ ...onstructorTagOnObjectLiteralMethod.symbols | 16 +++++++++ .../constructorTagOnObjectLiteralMethod.types | 24 +++++++++++++ .../typeFromPropertyAssignment12.types | 10 +++--- .../constructorTagOnObjectLiteralMethod.ts | 10 ++++++ .../classCanExtendConstructorFunction.ts | 4 ++- .../conformance/salsa/constructorFunctions.ts | 4 +-- .../fourslash/jsDocFunctionSignatures8.ts | 2 +- 15 files changed, 141 insertions(+), 53 deletions(-) create mode 100644 tests/baselines/reference/constructorTagOnObjectLiteralMethod.errors.txt create mode 100644 tests/baselines/reference/constructorTagOnObjectLiteralMethod.symbols create mode 100644 tests/baselines/reference/constructorTagOnObjectLiteralMethod.types create mode 100644 tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cb538a36897..1a4f3bb6a0b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5622,9 +5622,6 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - if (isJSConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, SignatureKind.Call); - } return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } @@ -5706,7 +5703,9 @@ namespace ts { const baseTypeNode = getBaseTypeNodeOfClass(type)!; const typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); let baseType: Type; - const originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + const originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & SymbolFlags.Class && areAllOuterTypeParametersApplied(originalBaseType!)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -5717,8 +5716,8 @@ namespace ts { else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; } - else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJSClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -6730,6 +6729,7 @@ namespace ts { // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = filter(type.callSignatures, sig => isJSConstructor(sig.declaration)); } // And likewise for construct signatures for classes if (symbol.flags & SymbolFlags.Class) { @@ -7866,6 +7866,7 @@ namespace ts { let type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper!) : signature.unionSignatures ? getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype) : getReturnTypeFromAnnotation(signature.declaration!) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration!)) || (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -15451,12 +15452,9 @@ namespace ts { } if (!targetType) { - let constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); - if (constructSignatures.length === 0) { - constructSignatures = filter(getSignaturesOfType(rightType, SignatureKind.Call), sig => isJSConstructor(sig.declaration)); - } + const constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); targetType = constructSignatures.length ? - getUnionType(map(constructSignatures, signature => isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration!)) || getReturnTypeOfSignature(getErasedSignature(signature)))) : + getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))) : emptyObjectType; } @@ -20039,12 +20037,12 @@ namespace ts { // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -20056,7 +20054,7 @@ namespace ts { // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { @@ -20272,9 +20270,9 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } @@ -20322,8 +20320,8 @@ namespace ts { } const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + const numConstructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } diff --git a/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt b/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt index b3e2f836283..12dacb9efde 100644 --- a/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt +++ b/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt @@ -2,9 +2,8 @@ tests/cases/conformance/salsa/first.js(23,9): error TS2554: Expected 1 arguments tests/cases/conformance/salsa/first.js(31,5): error TS2416: Property 'load' in type 'Sql' is not assignable to the same property in base type 'Wagon'. Type '(files: string[], format: "csv" | "json" | "xmlolololol") => void' is not assignable to type '(supplies?: any[]) => void'. tests/cases/conformance/salsa/first.js(47,24): error TS2507: Type '(numberEaten: number) => void' is not a constructor function type. -tests/cases/conformance/salsa/generic.js(8,15): error TS2508: No base constructor has the specified number of type arguments. -tests/cases/conformance/salsa/generic.js(11,21): error TS2339: Property 'flavour' does not exist on type 'Chowder'. -tests/cases/conformance/salsa/generic.js(18,9): error TS2339: Property 'flavour' does not exist on type 'Chowder'. +tests/cases/conformance/salsa/generic.js(19,19): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/salsa/generic.js(20,32): error TS2345: Argument of type '0' is not assignable to parameter of type '{ claim: "ignorant" | "malicious"; }'. tests/cases/conformance/salsa/second.ts(8,25): error TS2507: Type '(numberEaten: number) => void' is not a constructor function type. tests/cases/conformance/salsa/second.ts(14,7): error TS2417: Class static side 'typeof Conestoga' incorrectly extends base class static side 'typeof Wagon'. Types of property 'circle' are incompatible. @@ -115,7 +114,7 @@ tests/cases/conformance/salsa/second.ts(17,15): error TS2345: Argument of type ' c.drunkOO c.numberOxen -==== tests/cases/conformance/salsa/generic.js (3 errors) ==== +==== tests/cases/conformance/salsa/generic.js (2 errors) ==== /** * @template T * @param {T} flavour @@ -124,21 +123,22 @@ tests/cases/conformance/salsa/second.ts(17,15): error TS2345: Argument of type ' this.flavour = flavour } /** @extends {Soup<{ claim: "ignorant" | "malicious" }>} */ - ~~~~ -!!! error TS2508: No base constructor has the specified number of type arguments. class Chowder extends Soup { log() { return this.flavour - ~~~~~~~ -!!! error TS2339: Property 'flavour' does not exist on type 'Chowder'. } } var soup = new Soup(1); soup.flavour - var chowder = new Chowder(); + var chowder = new Chowder({ claim: "ignorant" }); chowder.flavour.claim - ~~~~~~~ -!!! error TS2339: Property 'flavour' does not exist on type 'Chowder'. + var errorNoArgs = new Chowder(); + ~~~~~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/salsa/generic.js:5:15: An argument for 'flavour' was not provided. + var errorArgType = new Chowder(0); + ~ +!!! error TS2345: Argument of type '0' is not assignable to parameter of type '{ claim: "ignorant" | "malicious"; }'. \ No newline at end of file diff --git a/tests/baselines/reference/classCanExtendConstructorFunction.symbols b/tests/baselines/reference/classCanExtendConstructorFunction.symbols index 2a794718f4c..bd935a8a5b8 100644 --- a/tests/baselines/reference/classCanExtendConstructorFunction.symbols +++ b/tests/baselines/reference/classCanExtendConstructorFunction.symbols @@ -218,11 +218,20 @@ soup.flavour >soup : Symbol(soup, Decl(generic.js, 14, 3)) >flavour : Symbol(Soup.flavour, Decl(generic.js, 4, 24)) -var chowder = new Chowder(); +var chowder = new Chowder({ claim: "ignorant" }); >chowder : Symbol(chowder, Decl(generic.js, 16, 3)) >Chowder : Symbol(Chowder, Decl(generic.js, 6, 1)) +>claim : Symbol(claim, Decl(generic.js, 16, 27)) chowder.flavour.claim >chowder : Symbol(chowder, Decl(generic.js, 16, 3)) +var errorNoArgs = new Chowder(); +>errorNoArgs : Symbol(errorNoArgs, Decl(generic.js, 18, 3)) +>Chowder : Symbol(Chowder, Decl(generic.js, 6, 1)) + +var errorArgType = new Chowder(0); +>errorArgType : Symbol(errorArgType, Decl(generic.js, 19, 3)) +>Chowder : Symbol(Chowder, Decl(generic.js, 6, 1)) + diff --git a/tests/baselines/reference/classCanExtendConstructorFunction.types b/tests/baselines/reference/classCanExtendConstructorFunction.types index e1d4498ff7f..f42366976fc 100644 --- a/tests/baselines/reference/classCanExtendConstructorFunction.types +++ b/tests/baselines/reference/classCanExtendConstructorFunction.types @@ -268,16 +268,30 @@ soup.flavour >soup : typeof Soup >flavour : number -var chowder = new Chowder(); ->chowder : Chowder ->new Chowder() : Chowder +var chowder = new Chowder({ claim: "ignorant" }); +>chowder : any +>new Chowder({ claim: "ignorant" }) : any >Chowder : typeof Chowder +>{ claim: "ignorant" } : { claim: "ignorant"; } +>claim : "ignorant" +>"ignorant" : "ignorant" chowder.flavour.claim >chowder.flavour.claim : any >chowder.flavour : any ->chowder : Chowder +>chowder : any >flavour : any >claim : any +var errorNoArgs = new Chowder(); +>errorNoArgs : any +>new Chowder() : any +>Chowder : typeof Chowder + +var errorArgType = new Chowder(0); +>errorArgType : any +>new Chowder(0) : any +>Chowder : typeof Chowder +>0 : 0 + diff --git a/tests/baselines/reference/constructorFunctions.errors.txt b/tests/baselines/reference/constructorFunctions.errors.txt index 1464b1a874c..3957bb952fd 100644 --- a/tests/baselines/reference/constructorFunctions.errors.txt +++ b/tests/baselines/reference/constructorFunctions.errors.txt @@ -25,7 +25,7 @@ tests/cases/conformance/salsa/index.js(55,13): error TS2554: Expected 1 argument if (!(this instanceof C3)) return new C3(); }; - const c3_v1 = C3(); + const c3_v1 = C3(); // error: @class tag requires 'new' ~~~~ !!! error TS2348: Value of type 'typeof C3' is not callable. Did you mean to include 'new'? const c3_v2 = new C3(); @@ -35,7 +35,7 @@ tests/cases/conformance/salsa/index.js(55,13): error TS2554: Expected 1 argument if (!(this instanceof C4)) return new C4(); }; - const c4_v1 = C4(); + const c4_v1 = C4(); // error: @class tag requires 'new' ~~~~ !!! error TS2348: Value of type 'typeof C4' is not callable. Did you mean to include 'new'? const c4_v2 = new C4(); diff --git a/tests/baselines/reference/constructorFunctions.symbols b/tests/baselines/reference/constructorFunctions.symbols index 83e514b0b8d..590d4b9b8db 100644 --- a/tests/baselines/reference/constructorFunctions.symbols +++ b/tests/baselines/reference/constructorFunctions.symbols @@ -49,7 +49,7 @@ function C3() { }; -const c3_v1 = C3(); +const c3_v1 = C3(); // error: @class tag requires 'new' >c3_v1 : Symbol(c3_v1, Decl(index.js, 21, 5)) >C3 : Symbol(C3, Decl(index.js, 14, 23)) @@ -68,7 +68,7 @@ var C4 = function () { }; -const c4_v1 = C4(); +const c4_v1 = C4(); // error: @class tag requires 'new' >c4_v1 : Symbol(c4_v1, Decl(index.js, 29, 5)) >C4 : Symbol(C4, Decl(index.js, 25, 3)) diff --git a/tests/baselines/reference/constructorFunctions.types b/tests/baselines/reference/constructorFunctions.types index 4ae813076ef..d5bd4425435 100644 --- a/tests/baselines/reference/constructorFunctions.types +++ b/tests/baselines/reference/constructorFunctions.types @@ -76,9 +76,9 @@ function C3() { }; -const c3_v1 = C3(); ->c3_v1 : C3 ->C3() : C3 +const c3_v1 = C3(); // error: @class tag requires 'new' +>c3_v1 : any +>C3() : any >C3 : typeof C3 const c3_v2 = new C3(); @@ -102,9 +102,9 @@ var C4 = function () { }; -const c4_v1 = C4(); ->c4_v1 : C4 ->C4() : C4 +const c4_v1 = C4(); // error: @class tag requires 'new' +>c4_v1 : any +>C4() : any >C4 : typeof C4 const c4_v2 = new C4(); diff --git a/tests/baselines/reference/constructorTagOnObjectLiteralMethod.errors.txt b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.errors.txt new file mode 100644 index 00000000000..2ebd6b53260 --- /dev/null +++ b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/jsdoc/example.js(3,16): error TS2339: Property 'bar' does not exist on type '{ Foo(): void; }'. +tests/cases/conformance/jsdoc/example.js(5,2): error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. + + +==== tests/cases/conformance/jsdoc/example.js (2 errors) ==== + const obj = { + /** @constructor */ + Foo() { this.bar = "bar" } + ~~~ +!!! error TS2339: Property 'bar' does not exist on type '{ Foo(): void; }'. + }; + (new obj.Foo()).bar + ~~~~~~~~~~~~~ +!!! error TS7009: 'new' expression, whose target lacks a construct signature, implicitly has an 'any' type. + \ No newline at end of file diff --git a/tests/baselines/reference/constructorTagOnObjectLiteralMethod.symbols b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.symbols new file mode 100644 index 00000000000..bd76f0c33bc --- /dev/null +++ b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.symbols @@ -0,0 +1,16 @@ +=== tests/cases/conformance/jsdoc/example.js === +const obj = { +>obj : Symbol(obj, Decl(example.js, 0, 5)) + + /** @constructor */ + Foo() { this.bar = "bar" } +>Foo : Symbol(Foo, Decl(example.js, 0, 13)) +>this : Symbol(obj, Decl(example.js, 0, 11)) +>bar : Symbol(bar, Decl(example.js, 2, 9)) + +}; +(new obj.Foo()).bar +>obj.Foo : Symbol(Foo, Decl(example.js, 0, 13)) +>obj : Symbol(obj, Decl(example.js, 0, 5)) +>Foo : Symbol(Foo, Decl(example.js, 0, 13)) + diff --git a/tests/baselines/reference/constructorTagOnObjectLiteralMethod.types b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.types new file mode 100644 index 00000000000..c731f3bc632 --- /dev/null +++ b/tests/baselines/reference/constructorTagOnObjectLiteralMethod.types @@ -0,0 +1,24 @@ +=== tests/cases/conformance/jsdoc/example.js === +const obj = { +>obj : { Foo(): void; } +>{ /** @constructor */ Foo() { this.bar = "bar" }} : { Foo(): void; } + + /** @constructor */ + Foo() { this.bar = "bar" } +>Foo : () => void +>this.bar = "bar" : "bar" +>this.bar : any +>this : { Foo(): void; } +>bar : any +>"bar" : "bar" + +}; +(new obj.Foo()).bar +>(new obj.Foo()).bar : any +>(new obj.Foo()) : any +>new obj.Foo() : any +>obj.Foo : () => void +>obj : { Foo(): void; } +>Foo : () => void +>bar : any + diff --git a/tests/baselines/reference/typeFromPropertyAssignment12.types b/tests/baselines/reference/typeFromPropertyAssignment12.types index 21b8dd7e32c..c2bee51375b 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment12.types +++ b/tests/baselines/reference/typeFromPropertyAssignment12.types @@ -1,7 +1,7 @@ === tests/cases/conformance/salsa/module.js === var Outer = function(element, config) {}; ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } ->function(element, config) {} : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } +>function(element, config) {} : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >element : any >config : any @@ -10,7 +10,7 @@ var Outer = function(element, config) {}; Outer.Pos = function (line, ch) {}; >Outer.Pos = function (line, ch) {} : typeof Pos >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >function (line, ch) {} : typeof Pos >line : any @@ -21,7 +21,7 @@ Outer.Pos.prototype.line; >Outer.Pos.prototype.line : any >Outer.Pos.prototype : any >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >prototype : any >line : any @@ -30,7 +30,7 @@ var pos = new Outer.Pos(1, 'x'); >pos : Pos >new Outer.Pos(1, 'x') : Pos >Outer.Pos : typeof Pos ->Outer : { (element: any, config: any): void; Pos(line: any, ch: any): void; } +>Outer : { (element: any, config: any): void; Pos(line: any, ch: any): Pos; } >Pos : typeof Pos >1 : 1 >'x' : "x" diff --git a/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts b/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts new file mode 100644 index 00000000000..d73ba6766c5 --- /dev/null +++ b/tests/cases/conformance/jsdoc/constructorTagOnObjectLiteralMethod.ts @@ -0,0 +1,10 @@ +// @noEmit: true +// @Filename: example.js +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +const obj = { + /** @constructor */ + Foo() { this.bar = "bar" } +}; +(new obj.Foo()).bar diff --git a/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts b/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts index 6946507c80e..89536584643 100644 --- a/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts +++ b/tests/cases/conformance/salsa/classCanExtendConstructorFunction.ts @@ -99,6 +99,8 @@ class Chowder extends Soup { var soup = new Soup(1); soup.flavour -var chowder = new Chowder(); +var chowder = new Chowder({ claim: "ignorant" }); chowder.flavour.claim +var errorNoArgs = new Chowder(); +var errorArgType = new Chowder(0); diff --git a/tests/cases/conformance/salsa/constructorFunctions.ts b/tests/cases/conformance/salsa/constructorFunctions.ts index 97486bb988c..35eae4b0e28 100644 --- a/tests/cases/conformance/salsa/constructorFunctions.ts +++ b/tests/cases/conformance/salsa/constructorFunctions.ts @@ -24,7 +24,7 @@ function C3() { if (!(this instanceof C3)) return new C3(); }; -const c3_v1 = C3(); +const c3_v1 = C3(); // error: @class tag requires 'new' const c3_v2 = new C3(); /** @class */ @@ -32,7 +32,7 @@ var C4 = function () { if (!(this instanceof C4)) return new C4(); }; -const c4_v1 = C4(); +const c4_v1 = C4(); // error: @class tag requires 'new' const c4_v2 = new C4(); var c5_v1; diff --git a/tests/cases/fourslash/jsDocFunctionSignatures8.ts b/tests/cases/fourslash/jsDocFunctionSignatures8.ts index 6853c70daf2..f7f2f4dca5e 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures8.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures8.ts @@ -14,4 +14,4 @@ ////} ////var p = new Pers/**/on(); goTo.marker(); -verify.quickInfoIs("function Person(name: string, age: number): void", "Represents a person\na b multiline test"); +verify.quickInfoIs("function Person(name: string, age: number): Person", "Represents a person\na b multiline test"); From 3aa33aa4ed9067dbc1addc8a64e6e42da2ed5d61 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 15 Oct 2018 15:55:45 -0700 Subject: [PATCH 064/262] Simplify the test --- .../cases/fourslash/formatRangeEndingAfterCommaOfCall.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts index 30f4d3faf75..824839ff4af 100644 --- a/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts +++ b/tests/cases/fourslash/formatRangeEndingAfterCommaOfCall.ts @@ -1,7 +1,7 @@ /// -////export const strong: StrongParser = verify(fmap(build(() => -//// /*start*/surround('**', compress(some(union([inline]), '**')), '**')),/*end*/ -//// ns => [html('strong', ns)] -////), ([el]) => hasTightStartText(el)); +////someCall( +//// /*start*/"firstParameter",/*end*/ +//// "something else" +////); format.selection("start", "end"); \ No newline at end of file From 1dadee88be1fd2e894cd871ff9cf1731cc8ac05a Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 16 Oct 2018 08:38:54 -0700 Subject: [PATCH 065/262] Update user baselines (#27922) --- tests/baselines/reference/user/bluebird.log | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/baselines/reference/user/bluebird.log b/tests/baselines/reference/user/bluebird.log index beb7553049b..4d7acc487ae 100644 --- a/tests/baselines/reference/user/bluebird.log +++ b/tests/baselines/reference/user/bluebird.log @@ -20,7 +20,7 @@ node_modules/bluebird/js/release/debuggability.js(168,17): error TS2403: Subsequ node_modules/bluebird/js/release/debuggability.js(174,26): error TS2339: Property 'detail' does not exist on type 'Event'. node_modules/bluebird/js/release/debuggability.js(175,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. node_modules/bluebird/js/release/debuggability.js(176,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/debuggability.js(199,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["removeListener", string, (...args: any[]) => void]'. +node_modules/bluebird/js/release/debuggability.js(199,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["multipleResolves", MultipleResolveListener]'. Property '0' is missing in type 'IArguments'. node_modules/bluebird/js/release/debuggability.js(242,56): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. Property 'pop' is missing in type 'IArguments'. From 0f4a615bcbdf1e26d91593fa295c819a54678573 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 16 Oct 2018 09:01:25 -0700 Subject: [PATCH 066/262] Fix isSourceFileFromExternalLibrary for file with redirect (#27917) * Fix isSourceFileFromExternalLibrary for file with redirect * Alternate fix * Use currentNodeModulesDepth > 0 --- src/compiler/program.ts | 1 + .../unittests/programMissingFiles.ts | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index cdfcfe6173b..ccec076ce7e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2031,6 +2031,7 @@ namespace ts { redirect.resolvedPath = resolvedPath; redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget, unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get(this: SourceFile) { return this.redirectInfo!.redirectTarget.id; }, diff --git a/src/testRunner/unittests/programMissingFiles.ts b/src/testRunner/unittests/programMissingFiles.ts index 37d4c791196..eb68e3bd665 100644 --- a/src/testRunner/unittests/programMissingFiles.ts +++ b/src/testRunner/unittests/programMissingFiles.ts @@ -98,4 +98,27 @@ namespace ts { ]); }); }); + + describe("Program.isSourceFileFromExternalLibrary", () => { + it("works on redirect files", () => { + // In this example '/node_modules/foo/index.d.ts' will redirect to '/node_modules/bar/node_modules/foo/index.d.ts'. + const a = new documents.TextDocument("/a.ts", 'import * as bar from "bar"; import * as foo from "foo";'); + const bar = new documents.TextDocument("/node_modules/bar/index.d.ts", 'import * as foo from "foo";'); + const fooPackageJsonText = '{ "name": "foo", "version": "1.2.3" }'; + const fooIndexText = "export const x: number;"; + const barFooPackage = new documents.TextDocument("/node_modules/bar/node_modules/foo/package.json", fooPackageJsonText); + const barFooIndex = new documents.TextDocument("/node_modules/bar/node_modules/foo/index.d.ts", fooIndexText); + const fooPackage = new documents.TextDocument("/node_modules/foo/package.json", fooPackageJsonText); + const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", fooIndexText); + + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, bar, barFooPackage, barFooIndex, fooPackage, fooIndex], cwd: "/" }); + const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); + + for (const file of [a, bar, barFooIndex, fooIndex]) { + const isExternalExpected = file !== a; + const isExternalActual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); + assert.equal(isExternalActual, isExternalExpected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${isExternalExpected}, got ${isExternalActual}`); + } + }); + }); } From eb2297df022f6b1f284aff96e93c06097bb01ea5 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 16 Oct 2018 12:28:14 -0700 Subject: [PATCH 067/262] Fix compile errors in tsbuildWatchMode.ts (#27870) * Fix compile errors in tsbuildWatchMode.ts * Remove TODO comments * new LKG * Add tslint disables --- lib/de/diagnosticMessages.generated.json | 2 +- lib/enu/diagnosticMessages.generated.json.lcg | 192 +- lib/es/diagnosticMessages.generated.json | 8 +- lib/ko/diagnosticMessages.generated.json | 16 +- lib/lib.es2015.promise.d.ts | 4 +- lib/lib.es5.d.ts | 72 +- lib/lib.esnext.array.d.ts | 4 +- lib/protocol.d.ts | 57 +- lib/pt-br/diagnosticMessages.generated.json | 24 +- lib/tr/diagnosticMessages.generated.json | 20 +- lib/tsc.js | 8489 ++++++----- lib/tsserver.js | 12080 +++++++++------ lib/tsserverlibrary.d.ts | 477 +- lib/tsserverlibrary.js | 12277 ++++++++++------ lib/typescript.d.ts | 340 +- lib/typescript.js | 11667 +++++++++------ lib/typescriptServices.d.ts | 340 +- lib/typescriptServices.js | 11667 +++++++++------ lib/typingsInstaller.js | 9667 +++++++----- lib/zh-cn/diagnosticMessages.generated.json | 6 +- src/testRunner/unittests/tsbuildWatchMode.ts | 4 +- 21 files changed, 41317 insertions(+), 26096 deletions(-) diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 795136609dc..f7bf53b6755 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -938,7 +938,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", - "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" weist einen zirkulären Standard auf.", + "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006": "Der Typparameter \"{0}\" der Konstruktorsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002": "Der Typparameter \"{0}\" der exportierten Klasse besitzt oder verwendet den privaten Namen \"{1}\".", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 2c93bcf114d..58166339abe 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -135,9 +135,9 @@ - + - + @@ -861,6 +861,18 @@ + + + + + + + + + + + + @@ -1233,6 +1245,12 @@ + + + + + + @@ -1401,6 +1419,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2001,6 +2049,18 @@ + + + + + + + + + + + + @@ -2259,6 +2319,12 @@ + + + + + + @@ -2349,6 +2415,12 @@ + + + + + + @@ -2421,9 +2493,9 @@ - + - + @@ -2781,6 +2853,18 @@ + + + + + + + + + + + + @@ -2829,12 +2913,6 @@ - - - - - - @@ -3225,6 +3303,12 @@ + + + + + + @@ -3255,6 +3339,12 @@ + + + + + + @@ -3705,6 +3795,12 @@ + + + + + + @@ -3909,9 +4005,9 @@ - + - + @@ -5025,12 +5121,6 @@ - - - - - - @@ -5313,6 +5403,12 @@ + + + + + + @@ -5589,6 +5685,12 @@ + + + + + + @@ -6051,6 +6153,12 @@ + + + + + + @@ -6207,6 +6315,12 @@ + + + + + + @@ -6393,6 +6507,12 @@ + + + + + + @@ -6657,12 +6777,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -6831,6 +6975,18 @@ + + + + + + + + + + + + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 0e0e31a2b11..52840b1208e 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -328,7 +328,7 @@ "Do_not_emit_outputs_if_any_errors_were_reported_6008": "No emitir salidas si se informa de algún error.", "Do_not_emit_use_strict_directives_in_module_output_6112": "No emitir directivas 'use strict' en la salida del módulo.", "Do_not_erase_const_enum_declarations_in_generated_code_6007": "No borrar las declaraciones de enumeración const en el código generado.", - "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones auxiliares personalizadas como \"__extends\" en la salida compilada.", + "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157": "No generar funciones del asistente personalizadas como \"__extends\" en la salida compilada.", "Do_not_include_the_default_library_file_lib_d_ts_6158": "No incluir el archivo de biblioteca predeterminado (lib.d.ts).", "Do_not_report_errors_on_unreachable_code_6077": "No notificar los errores del código inaccesible.", "Do_not_report_errors_on_unused_labels_6074": "No notificar los errores de las etiquetas no usadas.", @@ -477,7 +477,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "La declaración de importación '{0}' usa el nombre privado '{1}'.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "La declaración de importación está en conflicto con la declaración local de \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Las declaraciones de importación de un espacio de nombres no pueden hacer referencia a un módulo.", - "Import_emit_helpers_from_tslib_6139": "Importe elementos auxiliares de emisión de \"tslib\".", + "Import_emit_helpers_from_tslib_6139": "Importe asistentes de emisión de \"tslib\".", "Import_may_be_converted_to_a_default_import_80003": "La importación puede convertirse a una importación predeterminada.", "Import_name_cannot_be_0_2438": "El nombre de importación no puede ser \"{0}\".", "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439": "La declaración de importación o exportación de una declaración de módulo de ambiente no puede hacer referencia al módulo a través de su nombre relativo.", @@ -892,8 +892,8 @@ "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190": "La declaración de variable de una instrucción \"for...of\" no puede tener un inicializador.", "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410": "No se admite la instrucción 'with'. Todos los símbolos de un bloque 'with' tendrán el tipo 'any'.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "Esta función de constructor puede convertirse en una declaración de clase.", - "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere una aplicación auxiliar importada, pero no se puede encontrar el módulo \"{0}\".", - "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere una aplicación auxiliar importada denominada \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", + "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354": "Esta sintaxis requiere un asistente importado, pero no se puede encontrar el módulo \"{0}\".", + "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343": "Esta sintaxis requiere un asistente importado denominado \"{1}\", pero el módulo \"{0}\" no tiene el miembro exportado \"{1}\".", "Trailing_comma_not_allowed_1009": "No se permite la coma final.", "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153": "Transpilar cada archivo como un módulo aparte (parecido a \"ts.transpileModule\").", "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035": "Pruebe \"npm install @types/{0}\" si existe o agregue un nuevo archivo de declaración (.d.ts) que incluya \"declare module '{0}';\"", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index c5d6cf984db..1003d62329c 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 매개 변수는 매개 변수 목록 마지막에 있어야 합니다.", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 매개 변수는 배열 형식이어야 합니다.", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표를 사용할 수 없습니다.", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "rest 매개 변수 또는 바인딩 패턴에 후행 쉼표가 없을 수 있습니다.", "A_return_statement_can_only_be_used_within_a_function_body_1108": "'return' 문은 함수 본문 내에서만 사용할 수 있습니다.", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "가져오기를 'baseUrl'에 상대적인 조회 위치로 다시 매핑하는 일련의 항목입니다.", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "'set' 접근자에는 반환 형식 주석을 사용할 수 없습니다.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "'null'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "'null'이거나 '정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "'정의되지 않음'일 수 있는 개체를 호출할 수 없습니다.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' 집합이 없기 때문에 '{0}' 프로젝트를 추가할 수 없습니다.", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' 프로젝트는 'outFile'이 설정되어 있지 않기 때문에 앞에 추가할 수 없습니다.", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' 플래그가 제공된 경우 형식을 다시 내보낼 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -274,7 +274,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "구성 파일에 대한 경로 또는 'tsconfig.json'이 포함된 폴더에 대한 경로를 고려하여 프로젝트를 컴파일합니다.", "Compiler_option_0_expects_an_argument_6044": "컴파일러 옵션 '{0}'에는 인수가 필요합니다.", "Compiler_option_0_requires_a_value_of_type_1_5024": "컴파일러 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", - "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 사용하지 않도록 설정할 수 없습니다.", + "Composite_projects_may_not_disable_declaration_emit_6304": "복합 프로젝트는 선언 내보내기를 비활성화할 수 없습니다.", "Computed_property_names_are_not_allowed_in_enums_1164": "컴퓨팅된 속성 이름은 열거형에 사용할 수 없습니다.", "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "계산된 값은 문자열 값 멤버가 포함된 열거형에서 허용되지 않습니다.", "Concatenate_and_emit_output_to_single_file_6001": "출력을 연결하고 단일 파일로 내보냅니다.", @@ -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' 파일에 sourcemap을 생성합니다.", "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}' 형식입니다. 반환 형식을 제공하세요.", @@ -677,13 +677,13 @@ "Print_names_of_generated_files_part_of_the_compilation_6154": "컴파일의 일부인 생성된 파일의 이름을 인쇄합니다.", "Print_the_compiler_s_version_6019": "컴파일러 버전을 인쇄합니다.", "Print_this_message_6017": "이 메시지를 출력합니다.", - "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.", + "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363": "'{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.", "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353": "'{1}' 종속성이 최신 상태가 아니기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350": "가장 오래된 출력 '{1}'이(가) 최신 입력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352": "'{1}' 출력 파일이 존재하지 않기 때문에 '{0}' 프로젝트가 최신 상태가 아닙니다.", "Project_0_is_up_to_date_6361": "'{0}' 프로젝트가 최신 상태입니다.", "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351": "최신 입력 '{1}'이(가) 가장 오래된 출력 '{2}'보다 오래되었기 때문에 '{0}' 프로젝트가 최신 상태입니다.", - "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "종속성의 .d.ts 파일이 있기 때문에 '{0}' 프로젝트가 최신 상태입니다.", + "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "'{0}' 프로젝트는 종속성에 .d.ts 파일이 있는 최신 상태입니다.", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "프로젝트 참조는 순환 그래프를 형성할 수 없습니다. 순환이 발견되었습니다. {0}", "Projects_in_this_build_Colon_0_6355": "이 빌드의 프로젝트: {0}", "Projects_to_reference_6300": "참조할 프로젝트", @@ -803,7 +803,7 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "빌드될 항목 표시(또는 '--clean'으로 지정된 경우 삭제될 항목 표시)", "Signature_0_must_be_a_type_predicate_1224": "'{0}' 시그니처는 형식 조건자여야 합니다.", "Skip_type_checking_of_declaration_files_6012": "선언 파일 형식 검사를 건너뜁니다.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{1}' 종속성에 오류가 있기 때문에 '{0}' 프로젝트 빌드를 건너뜁니다.", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "'{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.", "Skipping_clean_because_not_all_projects_could_be_located_6371": "일부 프로젝트를 찾을 수 없으므로 정리를 건너뛰는 중입니다.", "Source_Map_Options_6175": "소스 맵 옵션", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "특수화된 오버로드 시그니처는 특수화되지 않은 서명에 할당할 수 없습니다.", @@ -1039,7 +1039,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성이나 인덱스 액세스 식, 또는 내보내기 할당이나 가져오기 선언의 오른쪽, 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum 선언'은 .ts 파일에서만 사용할 수 있습니다.", diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 9f27b7b59ab..002d69165fd 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -27,7 +27,7 @@ interface PromiseConstructor { /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * a resolve callback used to resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; @@ -213,4 +213,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 840fd682789..d1a9d6f0d2a 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -315,6 +315,66 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +interface CallableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: (this: T) => R, thisArg: T): R; + apply(this: (this: T, ...args: A) => R, thisArg: T, args: A): R; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: (this: T, ...args: A) => R, thisArg: T, ...args: A): R; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; + bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R; + bind(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R; +} + +interface NewableFunction extends Function { + /** + * Calls the function with the specified object as the this value and the elements of specified array as the arguments. + * @param thisArg The object to be used as the this object. + * @param args An array of argument values to be passed to the function. + */ + apply(this: new () => T, thisArg: T): void; + apply(this: new (...args: A) => T, thisArg: T, args: A): void; + + /** + * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. + * @param thisArg The object to be used as the this object. + * @param args Argument values to be passed to the function. + */ + call(this: new (...args: A) => T, thisArg: T, ...args: A): void; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg The object to be used as the this object. + * @param args Arguments to bind to the parameters of the function. + */ + bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; + bind(this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2, arg3: A3): new (...args: A) => R; + bind(this: new (...args: AX[]) => R, thisArg: any, ...args: AX[]): new (...args: AX[]) => R; +} + interface IArguments { [index: number]: any; length: number; @@ -1370,7 +1430,7 @@ type Readonly = { }; /** - * From T pick a set of properties K + * From T, pick a set of properties whose keys are in the union K */ type Pick = { [P in K]: T[P]; @@ -1398,6 +1458,16 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; +/** + * Obtain the parameters of a function type in a tuple + */ +type Parameters any> = T extends (...args: infer P) => any ? P : never; + +/** + * Obtain the parameters of a constructor function type in a tuple + */ +type ConstructorParameters any> = T extends new (...args: infer P) => any ? P : never; + /** * Obtain the return type of a function type */ diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts index 3da8562d2ea..6c751223209 100644 --- a/lib/lib.esnext.array.d.ts +++ b/lib/lib.esnext.array.d.ts @@ -31,7 +31,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] @@ -145,7 +145,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index e7fcfc6ff5d..5823233a25b 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -827,15 +827,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -852,6 +854,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -860,7 +871,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -1373,7 +1388,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -1885,6 +1900,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -2220,6 +2264,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 509172c0ead..de74fa7bdcd 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -61,7 +61,7 @@ "A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330": "Uma propriedade de uma interface ou tipo literal cujo tipo é um tipo de 'unique symbol' deve ser 'readonly'.", "A_required_parameter_cannot_follow_an_optional_parameter_1016": "Um parâmetro obrigatório não pode seguir um parâmetro opcional.", "A_rest_element_cannot_contain_a_binding_pattern_2501": "Um elemento rest não pode conter um padrão de associação.", - "A_rest_element_cannot_have_a_property_name_2566": "Um elemento restante não pode ter um nome de propriedade.", + "A_rest_element_cannot_have_a_property_name_2566": "Um elemento rest não pode ter um nome de propriedade.", "A_rest_element_cannot_have_an_initializer_1186": "Um elemento rest não pode ter um inicializador.", "A_rest_element_must_be_last_in_a_destructuring_pattern_2462": "Um elemento rest deve ser o último em um padrão de desestruturação.", "A_rest_parameter_cannot_be_optional_1047": "Um parâmetro rest não pode ser opcional.", @@ -174,7 +174,7 @@ "An_object_member_cannot_be_declared_optional_1162": "Um membro de objeto não pode ser declarado como opcional.", "An_overload_signature_cannot_be_declared_as_a_generator_1222": "A assinatura de sobrecarga não pode ser declarada como geradora.", "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006": "Uma expressão unária com o operador '{0}' não é permitida no lado esquerdo de uma expressão de exponenciação. Considere delimitar a expressão em parênteses.", - "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos de JSDoc", + "Annotate_everything_with_types_from_JSDoc_95043": "Anotar tudo com tipos do JSDoc", "Annotate_with_type_from_JSDoc_95009": "Anotar com o tipo do JSDoc", "Annotate_with_types_from_JSDoc_95010": "Anotar com os tipos do JSDoc", "Argument_expression_expected_1135": "Expressão de argumento esperada.", @@ -368,7 +368,7 @@ "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", "Enum_0_used_before_its_declaration_2450": "A enumeração '{0}' usada antes de sua declaração.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações de enum apenas podem se mescladas com namespaces ou com outras declarações de enum.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "As declarações enum só podem ser mescladas com namespaces ou com outras declarações enum.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Declarações de enumeração devem ser const ou não const.", "Enum_member_expected_1132": "Membro de enumeração esperado.", "Enum_member_must_have_initializer_1061": "O membro de enumeração deve ter um inicializador.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "O módulo {0} já exportou um membro denominado '{1}'. Considere reexportar explicitamente para resolver a ambiguidade.", "Module_0_has_no_default_export_1192": "O módulo '{0}' não tem padrão de exportação.", "Module_0_has_no_exported_member_1_2305": "O módulo '{0}' não tem nenhum membro exportado '{1}'.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro exportado '{1}'. Você quis dizer '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "O módulo '{0}' não tem nenhum membro '{1}' exportado. Você quis dizer '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "O módulo '{0}' está oculto por uma declaração de local com o mesmo nome.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "O módulo '{0}' resolve para uma entidade sem módulo e não pode ser importado usando este constructo.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "O módulo '{0}' usa 'export =' e não pode ser usado com 'export *'.", @@ -622,7 +622,7 @@ "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051": "A opção '{0} só pode ser usada quando qualquer uma das opções '--inlineSourceMap' ou '--sourceMap' é fornecida.", "Option_0_cannot_be_specified_with_option_1_5053": "A opção '{0}' não pode ser especificada com a opção '{1}'.", "Option_0_cannot_be_specified_without_specifying_option_1_5052": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}'.", - "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem especificar a opção '{1}' ou a opção '{2}'.", + "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069": "A opção '{0}' não pode ser especificada sem a especificação da opção '{1}' ou '{2}'.", "Option_0_should_have_array_of_strings_as_a_value_6103": "A opção '{0}' deve ter matriz de cadeias de um valor.", "Option_build_must_be_the_first_command_line_argument_6369": "A opção '--build' precisa ser o primeiro argumento da linha de comando.", "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "A opção 'isolatedModules' só pode ser usada quando nenhuma opção de '--module' for fornecida ou a opção 'target' for 'ES2015' ou superior.", @@ -686,7 +686,7 @@ "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354": "O projeto '{0}' está atualizado com os arquivos .d.ts de suas dependências", "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "Referências de projeto não podem formar um gráfico circular. Ciclo detectado: {0}", "Projects_in_this_build_Colon_0_6355": "Projetos neste build: {0}", - "Projects_to_reference_6300": "Projetos para referência", + "Projects_to_reference_6300": "Projetos a serem referenciados", "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "A propriedade '{0}' não existe no tipo '{1}'. Você esqueceu de usar 'await'?", @@ -740,7 +740,7 @@ "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", "Remove_destructuring_90009": "Remover desestruturação", - "Remove_import_from_0_90005": "Remover importação do '{0}'", + "Remove_import_from_0_90005": "Remover importação de '{0}'", "Remove_unreachable_code_95050": "Remover código inacessível", "Remove_unused_label_95053": "Remover rótulo não utilizado", "Remove_variable_statement_90010": "Remover instrução de variável", @@ -752,7 +752,7 @@ "Report_errors_on_unused_parameters_6135": "Relatar erros nos parâmetros não utilizados.", "Required_type_parameters_may_not_follow_optional_type_parameters_2706": "Os parâmetros de tipo necessários podem não seguir os parâmetros de tipo opcionais.", "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", - "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' para nomes de propriedades com valores de cadeia de caracteres somente (sem números ou símbolos).", + "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", "Resolving_from_node_modules_folder_6118": "Resolvendo na pasta node_modules...", "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", @@ -803,8 +803,8 @@ "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367": "Mostrar o que seria compilado (ou excluído, se especificado com '--clean')", "Signature_0_must_be_a_type_predicate_1224": "A assinatura '{0}' deve ser um predicado de tipo.", "Skip_type_checking_of_declaration_files_6012": "Ignorar a verificação de tipo dos arquivos de declaração.", - "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando build do projeto '{0}' porque sua dependência '{1}' tem erros", - "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque nem todos os projetos foram localizados", + "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362": "Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros", + "Skipping_clean_because_not_all_projects_could_be_located_6371": "Ignorando a limpeza porque não foram localizados todos os projetos", "Source_Map_Options_6175": "Opções do Sourcemap", "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382": "A assinatura de sobrecarga especializada não pode ser atribuída a qualquer assinatura não especializada.", "Specifier_of_dynamic_import_cannot_be_spread_element_1325": "O especificador de importação dinâmica não pode ser o elemento de difusão.", @@ -966,7 +966,7 @@ "Unexpected_end_of_text_1126": "Fim inesperado do texto.", "Unexpected_token_1012": "Token inesperado.", "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068": "Token inesperado. Um construtor, método, acessador ou propriedade era esperado.", - "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Um nome de parâmetro de tipo era esperado sem chaves.", + "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069": "Token inesperado. Era esperado um nome de parâmetro de tipo sem chaves.", "Unexpected_token_expected_1179": "Token inesperado. '{' esperado.", "Unknown_compiler_option_0_5023": "Opção do compilador '{0}' desconhecida.", "Unknown_option_excludes_Did_you_mean_exclude_6114": "Opção desconhecida 'excludes'. Você quis dizer 'exclude'?", @@ -993,7 +993,7 @@ "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", "Version_0_6029": "Versão {0}", "Watch_input_files_6005": "Observe os arquivos de entrada.", - "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se se deve manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", + "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 611ccb3a4ad..284c223d0cd 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -49,8 +49,8 @@ "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", - "A_non_dry_build_would_build_project_0_6357": "non-dry bir derleme '{0}' projesini derler", - "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "non-dry bir derleme şu dosyaları siler: {0}", + "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", + "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -110,7 +110,7 @@ "Add_initializers_to_all_uninitialized_properties_95027": "Tüm başlatılmamış özelliklere başlatıcılar ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_missing_typeof_95052": "Eksik 'typeof' öğesini ekle", - "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekleyin veya kaldırın", + "Add_or_remove_braces_in_an_arrow_function_95058": "Ok işlevine küme ayracı ekle veya kaldır", "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Bir üye adıyla eşleşen tüm çözülmemiş değişkenlere niteleyici ekle", "Add_to_all_uncalled_decorators_95044": "Çağrılmayan tüm dekoratörlere '()' ekle", "Add_ts_ignore_to_all_error_messages_95042": "Tüm hata iletilerine '@ts-ignore' ekle", @@ -122,7 +122,7 @@ "All_declarations_of_0_must_have_identical_modifiers_2687": "Tüm '{0}' bildirimleri aynı değiştiricilere sahip olmalıdır.", "All_declarations_of_0_must_have_identical_type_parameters_2428": "Tüm '{0}' bildirimleri özdeş tür parametrelerine sahip olmalıdır.", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "Soyut metoda ait tüm bildirimler ardışık olmalıdır.", - "All_destructured_elements_are_unused_6198": "Yok edilen öğelerin hiçbiri kullanılmamış.", + "All_destructured_elements_are_unused_6198": "Yapısı bozulan öğelerin hiçbiri kullanılmıyor.", "All_imports_in_import_declaration_are_unused_6192": "İçeri aktarma bildirimindeki hiçbir içeri aktarma kullanılmadı.", "All_variables_are_unused_6199": "Hiçbir değişken kullanılmıyor.", "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "Varsayılan dışarı aktarmaya sahip olmayan modüllerde varsayılan içeri aktarmalara izin verin. Bu işlem kod üretimini etkilemez, yalnızca tür denetimini etkiler.", @@ -232,7 +232,7 @@ "Cannot_invoke_an_object_which_is_possibly_null_2721": "Muhtemelen 'null' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "Muhtemelen 'null' veya 'undefined' olan bir nesne çağrılamıyor.", "Cannot_invoke_an_object_which_is_possibly_undefined_2722": "Muhtemelen 'undefined' olan bir nesne çağrılamıyor.", - "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' projesi, 'outFile' kümesi içermediğinden başa eklenemiyor", + "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "'--isolatedModules' bayrağı sağlandığında bir tür yeniden dışarı aktarılamaz.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", @@ -311,7 +311,7 @@ "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207": "Dekoratörler aynı ada sahip birden fazla get/set erişimcisine uygulanamaz.", "Default_export_of_the_module_has_or_is_using_private_name_0_4082": "Modülün varsayılan dışarı aktarımı '{0}' özel adına sahip veya bu adı kullanıyor.", "Delete_all_unused_declarations_95024": "Kullanılmayan tüm bildirimleri sil", - "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını silin", + "Delete_the_outputs_of_all_projects_6365": "Tüm projelerin çıkışlarını sil", "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084": "[Kullanım Dışı] Bunun yerine '--jsxFactory' kullanın. 'react' JSX gösterimi hedefleniyorsa, createElement için çağrılan nesneyi belirtin", "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170": "[Kullanım Dışı] Bunun yerine '--outFile' kullanın. Çıkışı tek bir dosya olarak birleştirin ve gösterin", "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160": "[Kullanım Dışı] Bunun yerine '--skipLibCheck' kullanın. Varsayılan kitaplık bildirim dosyalarının tür denetimini atlayın.", @@ -362,13 +362,13 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Sınıflarda sıkı özellik başlatma denetimini etkinleştirin.", "Enable_strict_null_checks_6113": "Katı null denetimlerini etkinleştir.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", - "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştirin", + "Enable_verbose_logging_6366": "Ayrıntılı günlüğe yazmayı etkinleştir", "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", "Enum_0_used_before_its_declaration_2450": "'{0}' sabit listesi, bildiriminden önce kullanıldı.", - "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Enum bildirimleri yalnızca ad alanı veya diğer enum bildirimleri ile birleştirilebilir.", + "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567": "Sabit listesi bildirimleri yalnızca ad alanı veya diğer sabit listesi bildirimleri ile birleştirilebilir.", "Enum_declarations_must_all_be_const_or_non_const_2473": "Sabit listesi bildirimlerinin tümü const veya const olmayan değerler olmalıdır.", "Enum_member_expected_1132": "Sabit listesi üyesi bekleniyor.", "Enum_member_must_have_initializer_1061": "Sabit listesi üyesi bir başlatıcıya sahip olmalıdır.", @@ -571,7 +571,7 @@ "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "{0} modülü, '{1}' adlı bir üyeyi zaten dışarı aktardı. Belirsizliği çözmek için açık olarak yeniden dışarı aktarmayı göz önünde bulundurun.", "Module_0_has_no_default_export_1192": "'{0}' modülü için varsayılan dışarı aktarma yok.", "Module_0_has_no_exported_member_1_2305": "'{0}' modülü, dışarı aktarılan '{1}' üyesine sahip değil.", - "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "'{0}' modülünün dışa aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", + "Module_0_has_no_exported_member_1_Did_you_mean_2_2724": "{0}' modülünün dışarı aktarılan '{1}' adlı bir üyesi yok. Şunu mu demek istediniz: '{2}'?", "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437": "'{0}' modülü, aynı ada sahip bir yerel bildirim tarafından gizleniyor.", "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497": "'{0}' modülü, modül olmayan bir varlığa çözümleniyor ve bu oluşturma ile içeri aktarılamaz.", "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498": "'{0}' modülü 'export =' kullanıyor ve 'export *' ile birlikte kullanılamaz.", @@ -737,7 +737,7 @@ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", - "Remove_braces_from_arrow_function_95060": "Ok işlevinden köşeli ayraçları kaldırın", + "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", diff --git a/lib/tsc.js b/lib/tsc.js index 1e550d3ba52..6309a02f3fe 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -59,10 +59,11 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -661,16 +662,13 @@ var ts; return result; } function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -712,7 +710,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1011,7 +1009,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1125,6 +1123,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1276,7 +1278,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1673,6 +1677,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); var ts; (function (ts) { @@ -1732,6 +1740,287 @@ var ts; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + var Version = (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + if (this === other) + return 0; + if (other === undefined) + return 1; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + if (left === right) + return 0; + if (left.length === 0) + return right.length === 0 ? 0 : 1; + if (right.length === 0) + return -1; + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 : 1; + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + return ts.compareValues(left.length, right.length); + } + var VersionRange = (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); +var ts; (function (ts) { var OperationCanceledException = (function () { function OperationCanceledException() { @@ -1840,19 +2129,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; ts.missingFileModifiedTime = new Date(0); function createPollingIntervalBasedLevels(levels) { var _a; @@ -2048,17 +2324,20 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; function createRecursiveDirectoryWatcher(host) { var cache = ts.createMap(); var callbackCache = ts.createMultiMap(); @@ -2331,10 +2610,11 @@ var ts; } function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { - var fileName = !ts.isString(relativeFileName) - ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -2885,7 +3165,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -2924,6 +3204,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3167,7 +3451,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -3195,6 +3478,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3286,6 +3577,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3399,7 +3691,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -3493,7 +3787,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -3591,6 +3885,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -3621,9 +3924,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -3688,6 +3991,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -3816,10 +4120,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; function tokenIsIdentifierOrKeyword(token) { return token >= 71; } @@ -3828,136 +4135,85 @@ var ts; return token === 29 || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117, - "any": 119, - "as": 118, - "boolean": 122, - "break": 72, - "case": 73, - "catch": 74, - "class": 75, - "continue": 77, - "const": 76, - "constructor": 123, - "debugger": 78, - "declare": 124, - "default": 79, - "delete": 80, - "do": 81, - "else": 82, - "enum": 83, - "export": 84, - "extends": 85, - "false": 86, - "finally": 87, - "for": 88, - "from": 143, - "function": 89, - "get": 125, - "if": 90, - "implements": 108, - "import": 91, - "in": 92, - "infer": 126, - "instanceof": 93, - "interface": 109, - "is": 127, - "keyof": 128, - "let": 110, - "module": 129, - "namespace": 130, - "never": 131, - "new": 94, - "null": 95, - "number": 134, - "object": 135, - "package": 111, - "private": 112, - "protected": 113, - "public": 114, - "readonly": 132, - "require": 133, - "global": 144, - "return": 96, - "set": 136, - "static": 115, - "string": 137, - "super": 97, - "switch": 98, - "symbol": 138, - "this": 99, - "throw": 100, - "true": 101, - "try": 102, - "type": 139, - "typeof": 103, - "undefined": 140, - "unique": 141, - "unknown": 142, - "var": 104, - "void": 105, - "while": 106, - "with": 107, - "yield": 116, - "async": 120, - "await": 121, - "of": 145, - "{": 17, - "}": 18, - "(": 19, - ")": 20, - "[": 21, - "]": 22, - ".": 23, - "...": 24, - ";": 25, - ",": 26, - "<": 27, - ">": 29, - "<=": 30, - ">=": 31, - "==": 32, - "!=": 33, - "===": 34, - "!==": 35, - "=>": 36, - "+": 37, - "-": 38, - "**": 40, - "*": 39, - "/": 41, - "%": 42, - "++": 43, - "--": 44, - "<<": 45, - ">": 46, - ">>>": 47, - "&": 48, - "|": 49, - "^": 50, - "!": 51, - "~": 52, - "&&": 53, - "||": 54, - "?": 55, - ":": 56, - "=": 58, - "+=": 59, - "-=": 60, - "*=": 61, - "**=": 62, - "/=": 63, - "%=": 64, - "<<=": 65, - ">>=": 66, - ">>>=": 67, - "&=": 68, - "|=": 69, - "^=": 70, - "@": 57, - }); + var textToKeywordObj = (_a = { + abstract: 117, + any: 119, + as: 118, + boolean: 122, + break: 72, + case: 73, + catch: 74, + class: 75, + continue: 77, + const: 76 + }, + _a["" + "constructor"] = 123, + _a.debugger = 78, + _a.declare = 124, + _a.default = 79, + _a.delete = 80, + _a.do = 81, + _a.else = 82, + _a.enum = 83, + _a.export = 84, + _a.extends = 85, + _a.false = 86, + _a.finally = 87, + _a.for = 88, + _a.from = 143, + _a.function = 89, + _a.get = 125, + _a.if = 90, + _a.implements = 108, + _a.import = 91, + _a.in = 92, + _a.infer = 126, + _a.instanceof = 93, + _a.interface = 109, + _a.is = 127, + _a.keyof = 128, + _a.let = 110, + _a.module = 129, + _a.namespace = 130, + _a.never = 131, + _a.new = 94, + _a.null = 95, + _a.number = 134, + _a.object = 135, + _a.package = 111, + _a.private = 112, + _a.protected = 113, + _a.public = 114, + _a.readonly = 132, + _a.require = 133, + _a.global = 144, + _a.return = 96, + _a.set = 136, + _a.static = 115, + _a.string = 137, + _a.super = 97, + _a.switch = 98, + _a.symbol = 138, + _a.this = 99, + _a.throw = 100, + _a.true = 101, + _a.try = 102, + _a.type = 139, + _a.typeof = 103, + _a.undefined = 140, + _a.unique = 141, + _a.unknown = 142, + _a.var = 104, + _a.void = 105, + _a.while = 106, + _a.with = 107, + _a.yield = 116, + _a.async = 120, + _a.await = 121, + _a.of = 145, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17, "}": 18, "(": 19, ")": 20, "[": 21, "]": 22, ".": 23, "...": 24, ";": 25, ",": 26, "<": 27, ">": 29, "<=": 30, ">=": 31, "==": 32, "!=": 33, "===": 34, "!==": 35, "=>": 36, "+": 37, "-": 38, "**": 40, "*": 39, "/": 41, "%": 42, "++": 43, "--": 44, "<<": 45, ">": 46, ">>>": 47, "&": 48, "|": 49, "^": 50, "!": 51, "~": 52, "&&": 53, "||": 54, "?": 55, ":": 56, "=": 58, "+=": 59, "-=": 60, "*=": 61, "**=": 62, "/=": 63, "%=": 64, "<<=": 65, ">>=": 66, ">>>=": 67, "&=": 68, "|=": 69, "^=": 70, "@": 57 })); var unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; @@ -4418,6 +4674,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -4447,6 +4704,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -4814,9 +5072,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 && ch <= 122) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -4867,6 +5125,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -4903,6 +5162,24 @@ var ts; case 11: case 12: case 32: + case 160: + case 5760: + case 8192: + case 8193: + case 8194: + case 8195: + case 8196: + case 8197: + case 8198: + case 8199: + case 8200: + case 8201: + case 8202: + case 8203: + case 8239: + case 8287: + case 12288: + case 65279: if (skipTrivia) { pos++; continue; @@ -4960,6 +5237,10 @@ var ts; return pos += 2, token = 40; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1)) { + asteriskSeen = true; + continue; + } return token = 39; case 43: if (text.charCodeAt(pos + 1) === 43) { @@ -5437,7 +5718,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71; + return token = getIdentifierToken(); } else { return token = 0; @@ -5512,6 +5793,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -5527,7 +5811,6 @@ var ts; ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5606,22 +5889,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -5726,6 +5996,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -5901,12 +6177,19 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -5926,11 +6209,11 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216) ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: if (node.singleQuote) { @@ -6267,6 +6550,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2); } @@ -6326,6 +6613,7 @@ var ts; case 137: case 122: case 138: + case 135: case 140: case 131: return true; @@ -6926,18 +7214,18 @@ var ts; return node.kind === 246 && node.moduleReference.kind !== 257; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216); } @@ -6977,14 +7265,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -7007,14 +7295,18 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -7022,20 +7314,20 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - function getDeclaredJavascriptInitializer(node) { + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; - function getAssignedJavascriptInitializer(node) { + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 || e.kind === 195 ? initializer : undefined; @@ -7049,21 +7341,21 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + ts.getExpandoInitializer = getExpandoInitializer; + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 && ts.isIdentifier(parent.left)) { @@ -7074,7 +7366,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; function isSameEntityName(name, initializer) { if (ts.isIdentifier(name) && ts.isIdentifier(initializer)) { return name.escapedText === initializer.escapedText; @@ -7107,12 +7399,12 @@ var ts; return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 || isInJavaScriptFile(expr) ? special : 0; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 || isInJSFile(expr) ? special : 0; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 || !ts.isPropertyAccessExpression(expr.left)) { return 0; @@ -7121,9 +7413,9 @@ var ts; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { return 6; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99) { return 4; } @@ -7148,7 +7440,7 @@ var ts; } return 0; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -7157,11 +7449,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 && !!ts.getJSDocTypeTag(expr.parent); } @@ -7267,7 +7559,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 && + getAssignmentDeclarationKind(node.expression) !== 0 && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 ? node.expression.right.right @@ -7308,6 +7600,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -7477,6 +7773,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193) { + node = node.parent; + } + return node; + } function isDeleteTarget(node) { if (node.kind !== 187 && node.kind !== 188) { return false; @@ -7498,32 +7800,35 @@ var ts; return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } ts.isDeclarationName = isDeclarationName; - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71: case 9: - case 8: { - var parent = name.parent; + case 8: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + case 71: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 && + getAssignmentDeclarationKind(binExp) !== 0 && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 147 && @@ -7569,7 +7874,7 @@ var ts; node.kind === 251 || node.kind === 255 || node.kind === 252 && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -7578,7 +7883,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { var tag = ts.getJSDocAugmentsTag(node); if (tag) { return tag.class; @@ -8251,7 +8556,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); @@ -8263,7 +8568,7 @@ var ts; } ts.getSourceFilesToEmit = getSourceFilesToEmit; function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -8377,7 +8682,7 @@ var ts; ts.getAllAccessorDeclarations = getAllAccessorDeclarations; function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -8389,7 +8694,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -8623,13 +8928,18 @@ var ts; } ts.isAssignmentOperator = isAssignmentOperator; function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -8651,15 +8961,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 || isPropertyAccessEntityNameExpression(node); } @@ -8694,10 +8995,10 @@ var ts; function isExportDefaultSymbol(symbol) { return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -8818,6 +9119,26 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -8899,6 +9220,8 @@ var ts; } ts.formatObjectFlags = formatObjectFlags; function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -9030,6 +9353,8 @@ var ts; if (!parent) return 0; switch (parent.kind) { + case 193: + return accessKind(parent); case 201: case 200: var operator = parent.operator; @@ -9041,11 +9366,31 @@ var ts; : 0; case 187: return parent.name !== node ? 0 : accessKind(parent); + case 273: { + var parentAccess = accessKind(parent.parent); + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274: + return node === parent.objectAssignmentInitializer ? 0 : accessKind(parent.parent); + case 185: + return accessKind(parent); default: return 0; } function writeOrReadWrite() { - return parent.parent && parent.parent.kind === 219 ? 1 : 2; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 ? 1 : 2; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0: + return 1; + case 1: + return 0; + case 2: + return 2; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -9254,12 +9599,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -9469,7 +9808,7 @@ var ts; if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219: var expr = hostNode.expression; switch (expr.kind) { @@ -9481,9 +9820,7 @@ var ts; return arg; } } - return undefined; - case 1: - return undefined; + break; case 193: { return getDeclarationIdentifier(hostNode.expression); } @@ -9491,10 +9828,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -9523,7 +9858,7 @@ var ts; } case 202: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1: case 4: case 5: @@ -9584,6 +9919,13 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; function hasJSDocParameterTags(node) { return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } @@ -9671,7 +10013,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -10917,7 +11272,7 @@ var ts; } function isDeclaration(node) { if (node.kind === 148) { - return node.parent.kind !== 301 || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -11269,6 +11624,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -11285,9 +11652,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -11299,13 +11665,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -11498,8 +11865,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -11694,6 +12059,13 @@ var ts; } ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42, 63]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -11739,6 +12111,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } @@ -11925,35 +12298,56 @@ var ts; } } ts.getScriptKindFromFileName = getScriptKindFromFileName; - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTSExtensionsWithJson = [".ts", ".tsx", ".d.ts", ".json"]; + ts.supportedTSExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; + ts.supportedJSExtensions = [".js", ".jsx"]; + ts.supportedJSAndJsonExtensions = [".js", ".jsx", ".json"]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json"]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json"]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 || scriptKind === 2; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -12057,14 +12451,14 @@ var ts; return !(pos >= 0); } ts.positionIsSynthesized = positionIsSynthesized; - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json"; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json"; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); @@ -12219,6 +12613,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -12282,6 +12692,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275: @@ -12352,6 +12763,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -12710,7 +13122,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, 6); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); @@ -12776,8 +13188,12 @@ var ts; if (scriptKind === 6) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -13338,7 +13754,15 @@ var ts; case 6: return token() === 21 || isLiteralPropertyName(); case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + switch (token()) { + case 21: + case 39: + case 24: + case 23: + return true; + default: + return isLiteralPropertyName(); + } case 18: return isLiteralPropertyName(); case 9: @@ -13940,8 +14364,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288, dotdotdot.pos); variadic.type = type; @@ -15554,6 +15980,7 @@ var ts; var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); node.questionToken = parseOptionalToken(55); + node.exclamationToken = parseOptionalToken(51); if (asteriskToken || token() === 19 || token() === 27) { return parseMethodDeclaration(node, asteriskToken); } @@ -16749,7 +17176,7 @@ var ts; } JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281, scanner.getTokenPos()); + var result = createNode(281); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17); result.type = doInsideOfContext(2097152, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -16852,10 +17279,6 @@ var ts; indent += asterisk.length; } break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; case 5: var whitespace = scanner.getTokenText(); if (state === 2) { @@ -16938,7 +17361,7 @@ var ts; var atToken = createNode(57, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -17109,10 +17532,8 @@ var ts; var result = target === 1 ? createNode(303, atToken.pos) : createNode(297, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -17126,14 +17547,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 || child.kind === 303) { children = ts.append(children, child); } @@ -17221,7 +17642,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -17236,7 +17657,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290, start_3); } @@ -17296,7 +17717,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -17336,17 +17757,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 || child.kind === 303) && target !== 4 && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -17374,7 +17795,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57); var atToken = createNode(57); atToken.end = scanner.getTextPos(); @@ -17400,9 +17821,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { var constraint; @@ -18014,7 +18433,7 @@ var ts; ]; ts.libs = libEntries.map(function (entry) { return entry[0]; }); ts.libMap = ts.createMapFromEntries(libEntries); - ts.optionDeclarations = [ + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -18028,6 +18447,41 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -18075,21 +18529,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, { name: "target", shortName: "t", @@ -18103,6 +18542,8 @@ var ts; es2018: 5, esnext: 6, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18121,6 +18562,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18133,6 +18575,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -18140,6 +18583,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -18157,6 +18601,7 @@ var ts; "react-native": 3, "react": 2 }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18265,6 +18710,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18273,6 +18719,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18281,14 +18728,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18297,6 +18754,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18305,6 +18763,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18337,6 +18796,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -18348,6 +18808,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -18355,6 +18816,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -18362,6 +18824,7 @@ var ts; { name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -18375,6 +18838,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -18386,6 +18850,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -18396,6 +18861,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -18477,30 +18943,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -18558,12 +19006,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -18576,6 +19026,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -18621,6 +19072,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -18628,6 +19080,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -18681,7 +19134,41 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); ts.typeAcquisitionDeclarations = [ { name: "enableAutoDiscovery", @@ -18727,20 +19214,20 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } @@ -18773,16 +19260,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -18794,14 +19280,14 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); } else { if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -18834,7 +19320,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -18877,8 +19363,18 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -18890,7 +19386,32 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + projects.push("."); + } + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -19162,7 +19683,10 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -19414,7 +19938,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -19431,8 +19956,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -19468,19 +20007,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -19488,7 +20026,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -19505,12 +20042,28 @@ var ts; function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -19588,11 +20141,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -19638,7 +20186,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -19646,7 +20194,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -19792,7 +20340,7 @@ var ts; validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { @@ -19801,8 +20349,10 @@ var ts; var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); if (filesSpecs) { for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { var fileName = filesSpecs_1[_i]; @@ -19810,27 +20360,42 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json")) { + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json"); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); var key = keyMapper(file); if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -19981,6 +20546,12 @@ var ts; function noPackageId(r) { return withPackageId(undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } var Extensions; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; @@ -19992,7 +20563,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -20001,45 +20572,92 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; + } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return path; } } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; - } - return result.config; - } - catch (e) { - return {}; - } - } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -20073,7 +20691,8 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -20093,7 +20712,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -20119,11 +20737,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -20138,7 +20756,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, false, moduleResolutionState, true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -20167,10 +20792,13 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + if (baseFileName.charCodeAt(0) !== 46) { + result.push(baseFileName); + } } } } @@ -20312,15 +20940,15 @@ var ts; return result; } ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -20354,7 +20982,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -20371,7 +20999,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -20382,66 +21010,53 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -20453,8 +21068,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -20462,7 +21077,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -20475,7 +21090,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } } @@ -20491,29 +21106,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -20521,7 +21137,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } ts.nodeModulesPathPart = "/node_modules/"; function parseNodeModuleFromPath(resolved) { @@ -20550,41 +21166,37 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); - } - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json"); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -20598,11 +21210,11 @@ var ts; return tryExtension(".json"); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -20616,40 +21228,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { - var path = tryReadPackageJsonFields(true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts"; } @@ -20661,6 +21266,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts")) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -20672,46 +21278,51 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - file = tryReadPackageJsonFields(false, jsonContent, candidate, state); - if (!file) { - return undefined; + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); - if (result) { - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } function resolvedIfExtensionMatches(extensions, path) { var ext = ts.tryGetExtensionFromPath(path); @@ -20729,90 +21340,132 @@ var ts; return extension === ".d.ts"; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, true, undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } var mangledScopedPackageSeparator = "__"; - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } return mangled; } function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -20821,63 +21474,64 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; - function getPackageNameFromAtTypesDirectory(mangledName) { + ts.mangleScopedPackageName = mangleScopedPackageName; + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; - function getUnmangledNameForScopedPackage(typesPackageName) { + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } if (!ts.isExternalModuleNameRelative(moduleName)) { var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, false, state)); } } } @@ -20887,9 +21541,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, false); return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -21046,12 +21700,16 @@ var ts; if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; } } function getDeclarationName(node) { @@ -21091,7 +21749,7 @@ var ts; case 277: return "export="; case 202: - if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + if (ts.getAssignmentDeclarationKind(node) === 2) { return "export="; } ts.Debug.fail("Unknown binary declaration kind"); @@ -21133,7 +21791,7 @@ var ts; if (symbol.isReplaceableByMethod) { symbolTable.set(name, symbol = createSymbol(0, name)); } - else { + else if (!(includes & 3 && symbol.flags & 67108864)) { if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -21188,12 +21846,12 @@ var ts; } else { if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); } - var exportKind = symbolFlags & 67216319 ? 1048576 : 0; + var exportKind = symbolFlags & 67220415 ? 1048576 : 0; var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -21328,6 +21986,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -21425,6 +22084,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200: return expr.operator === 51 && isNarrowingExpression(expr.operand); + case 197: + return isNarrowingExpression(expr.expression); } return false; } @@ -21789,7 +22450,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -22147,7 +22807,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 67215503); + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 110735); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -22164,7 +22824,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 67215503 : 0); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 110735 : 0); return state; } function bindFunctionOrConstructorType(node) { @@ -22232,9 +22892,6 @@ var ts; declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 67216319); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -22254,7 +22911,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288, 67901928); + bindBlockScopedDeclaration(typeAlias, 524288, 67897832); } else { bind(typeAlias.fullName); @@ -22426,7 +23083,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -22466,7 +23123,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288, 67901928); + bindBlockScopedDeclaration(parentNode, 524288, 67897832); break; } case 99: @@ -22482,15 +23139,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, undefined, node.expression, 1 | 134217728, 67216318); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, undefined, node.expression, 1 | 134217728, 67220414); } break; case 202: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1: bindExportsPropertyAssignment(node); @@ -22558,15 +23215,15 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 154: case 153: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67208127); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 67212223); case 237: return bindFunctionDeclaration(node); case 155: return declareSymbolAndAddToSymbolTable(node, 16384, 0); case 156: - return bindPropertyOrMethodOrAccessor(node, 32768, 67150783); + return bindPropertyOrMethodOrAccessor(node, 32768, 67154879); case 157: - return bindPropertyOrMethodOrAccessor(node, 65536, 67183551); + return bindPropertyOrMethodOrAccessor(node, 65536, 67187647); case 163: case 287: case 291: @@ -22582,7 +23239,7 @@ var ts; case 195: return bindFunctionExpression(node); case 189: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -22591,9 +23248,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239: - return bindBlockScopedDeclaration(node, 64, 67901832); + return bindBlockScopedDeclaration(node, 64, 67897736); case 240: - return bindBlockScopedDeclaration(node, 524288, 67901928); + return bindBlockScopedDeclaration(node, 524288, 67897832); case 241: return bindEnumDeclaration(node); case 242: @@ -22668,33 +23325,30 @@ var ts; bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); } else { - var flags = node.kind === 252 && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); + if (node.isExportEquals) { + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -22751,7 +23405,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, false); switch (thisContainer.kind) { case 237: @@ -22800,7 +23454,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, false); + bindPropertyAssignment(lhs.expression, lhs, false); } function bindPrototypePropertyAssignment(lhs, parent) { var classPrototype = lhs.expression; @@ -22813,7 +23467,7 @@ var ts; function bindSpecialPropertyAssignment(node) { var lhs = node.left; var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } node.left.parent = node; @@ -22831,36 +23485,36 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 : propertyAccess.parent.parent.kind === 277; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920))) { var flags_1 = 1536 | 67108864; - var excludeFlags_1 = 67215503 & ~67108864; + var excludeFlags_1 = 110735 & ~67108864; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 : 4) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 : 0) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 : 4; + var excludes = isMethod ? 67212223 : 0; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864, excludes & ~67108864); } - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 | 32 | 1024)) { return true; } @@ -22873,7 +23527,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 ? init.right : init, isPrototypeAssignment); } return false; } @@ -22945,14 +23599,17 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 : 0); + var enumExcludes = (isEnum ? 68008191 : 0); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 | enumFlags, 67220415 | enumExcludes); } else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216318); + declareSymbolAndAddToSymbolTable(node, 1 | enumFlags, 67220414 | enumExcludes); } } } @@ -22967,7 +23624,7 @@ var ts; bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1, 67216319); + declareSymbolAndAddToSymbolTable(node, 1, 67220415); } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; @@ -22983,10 +23640,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 67215791); + bindBlockScopedDeclaration(node, 16, 67219887); } else { - declareSymbolAndAddToSymbolTable(node, 16, 67215791); + declareSymbolAndAddToSymbolTable(node, 16, 67219887); } } function bindFunctionExpression(node) { @@ -23024,10 +23681,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, undefined, node, 262144, 67639784); + declareSymbol(container_1.locals, undefined, node, 262144, 67635688); } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } else if (node.parent.kind === 174) { @@ -23036,14 +23693,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, undefined, node, 262144, 67639784); + declareSymbol(container_2.locals, undefined, node, 262144, 67635688); } else { bindAnonymousDeclaration(node, 262144, getDeclarationName(node)); } } else { - declareSymbolAndAddToSymbolTable(node, 262144, 67639784); + declareSymbolAndAddToSymbolTable(node, 262144, 67635688); } } function shouldReportErrorOnModuleDeclaration(node) { @@ -23057,8 +23714,7 @@ var ts; if (currentFlow === unreachableFlow) { var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 218) || node.kind === 238 || - (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)) || - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -23085,7 +23741,7 @@ var ts; } } function isExecutableStatement(s) { - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 | 2)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } function isPurelyTypeDeclaration(s) { @@ -23121,6 +23777,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } function computeTransformFlagsForNode(node, subtreeFlags) { @@ -23190,32 +23849,32 @@ var ts; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288 - || (expression.transformFlags & (134217728 | 268435456))) { + if (subtreeFlags & 131072 + || (expression.transformFlags & (33554432 | 67108864))) { transformFlags |= 192; - if (expression.transformFlags & 268435456) { - transformFlags |= 16384; + if (expression.transformFlags & 67108864) { + transformFlags |= 8192; } } if (expression.kind === 91) { - transformFlags |= 67108864; - if (subtreeFlags & 16384) { - transformFlags |= 32768; + transformFlags |= 16777216; + if (subtreeFlags & 8192) { + transformFlags |= 16384; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3; } - if (subtreeFlags & 524288) { + if (subtreeFlags & 131072) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940049729; + return transformFlags & ~637666625; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23232,7 +23891,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23241,21 +23900,21 @@ var ts; var dotDotDotToken = node.dotDotDotToken; if (node.questionToken || node.type - || subtreeFlags & 4096 + || (subtreeFlags & 4096 && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (ts.hasModifier(node, 92)) { - transformFlags |= 3 | 262144; + transformFlags |= 3 | 4096; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; + if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { + transformFlags |= 192 | 65536; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23279,28 +23938,28 @@ var ts; } else { transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) + if ((subtreeFlags & 4096) || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 + if (subtreeFlags & 4096 || node.typeParameters) { transformFlags |= 3; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~942011713; + return transformFlags & ~638121281; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23316,7 +23975,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23327,7 +23986,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~940574017; + return transformFlags & ~637797697; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23335,7 +23994,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23343,11 +24002,11 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23359,7 +24018,7 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } if (ts.hasModifier(node, 256)) { @@ -23369,7 +24028,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23380,19 +24039,19 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192; + transformFlags |= 4096; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -23402,7 +24061,7 @@ var ts; transformFlags = 3; } else { - transformFlags = subtreeFlags | 33554432; + transformFlags = subtreeFlags | 8388608; if (modifierFlags & 2270 || node.typeParameters || node.type) { @@ -23411,10 +24070,10 @@ var ts; if (modifierFlags & 256) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { @@ -23422,7 +24081,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23434,17 +24093,17 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= node.asteriskToken ? 8 : 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 163840) { + if (subtreeFlags & 81920) { transformFlags |= 192; } if (node.asteriskToken) { transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -23456,46 +24115,46 @@ var ts; if (ts.hasModifier(node, 256)) { transformFlags |= 16; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } - if (subtreeFlags & 16384) { - transformFlags |= 32768; + if (subtreeFlags & 8192) { + transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003902273; + return transformFlags & ~653604161; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (transformFlags & 134217728) { - transformFlags ^= 134217728; - transformFlags |= 268435456; + if (transformFlags & 33554432) { + transformFlags ^= 33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionFlags = expression.transformFlags; - if (expressionFlags & 134217728) { - transformFlags &= ~134217728; - transformFlags |= 268435456; + if (expressionFlags & 33554432) { + transformFlags &= ~33554432; + transformFlags |= 67108864 | 16 | 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~671089985; + return transformFlags & ~570426689; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { + transformFlags |= 192 | 2097152; + if (subtreeFlags & 262144) { transformFlags |= 8; } if (node.type) { transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -23505,21 +24164,21 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { + if (declarationListTransformFlags & 2097152) { transformFlags |= 192; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 + if (subtreeFlags & 1048576 && ts.isIterationStatement(node, true)) { transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23527,7 +24186,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23535,7 +24194,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -23544,22 +24203,22 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~977327425; + return transformFlags & ~647001409; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { + var transformFlags = subtreeFlags | 8388608; + if (subtreeFlags & 2097152) { transformFlags |= 192; } if (node.flags & 3) { - transformFlags |= 192 | 4194304; + transformFlags |= 192 | 1048576; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~948962625; + return transformFlags & ~639894849; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 939525441; + var excludeFlags = 637535553; switch (kind) { case 120: case 199: @@ -23625,7 +24284,7 @@ var ts; transformFlags |= 192; break; case 205: - transformFlags |= 8 | 192 | 16777216; + transformFlags |= 8 | 192 | 4194304; break; case 119: case 134: @@ -23668,60 +24327,60 @@ var ts; excludeFlags = -3; break; case 147: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; + transformFlags |= 524288; + if (subtreeFlags & 8192) { + transformFlags |= 32768; } break; case 206: - transformFlags |= 192 | 524288; + transformFlags |= 192 | 131072; break; case 275: - transformFlags |= 8 | 1048576; + transformFlags |= 8 | 262144; break; case 97: - transformFlags |= 192 | 134217728; + transformFlags |= 192 | 33554432; excludeFlags = 536872257; break; case 99: - transformFlags |= 16384; + transformFlags |= 8192; break; case 182: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; + transformFlags |= 192 | 2097152; + if (subtreeFlags & 131072) { + transformFlags |= 8 | 262144; } - excludeFlags = 940049729; + excludeFlags = 637666625; break; case 183: - transformFlags |= 192 | 8388608; - excludeFlags = 940049729; + transformFlags |= 192 | 2097152; + excludeFlags = 637666625; break; case 184: transformFlags |= 192; if (node.dotDotDotToken) { - transformFlags |= 524288; + transformFlags |= 131072; } break; case 150: transformFlags |= 3 | 4096; break; case 186: - excludeFlags = 942740801; - if (subtreeFlags & 2097152) { + excludeFlags = 638358849; + if (subtreeFlags & 524288) { transformFlags |= 192; } - if (subtreeFlags & 65536) { - transformFlags |= 16384; + if (subtreeFlags & 32768) { + transformFlags |= 8192; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } break; case 185: case 190: - excludeFlags = 940049729; - if (subtreeFlags & 524288) { + excludeFlags = 637666625; + if (subtreeFlags & 131072) { transformFlags |= 192; } break; @@ -23729,21 +24388,21 @@ var ts; case 222: case 223: case 224: - if (subtreeFlags & 4194304) { + if (subtreeFlags & 1048576) { transformFlags |= 192; } break; case 277: - if (subtreeFlags & 32768) { + if (subtreeFlags & 16384) { transformFlags |= 192; } break; case 228: - transformFlags |= 33554432 | 8; + transformFlags |= 8388608 | 8; break; case 226: case 227: - transformFlags |= 33554432; + transformFlags |= 8388608; break; } node.transformFlags = transformFlags | 536870912; @@ -23757,27 +24416,27 @@ var ts; case 189: case 190: case 185: - return 940049729; + return 637666625; case 242: - return 977327425; + return 647001409; case 149: - return 939525441; + return 637535553; case 195: - return 1003902273; + return 653604161; case 194: case 237: - return 1003935041; + return 653620545; case 236: - return 948962625; + return 639894849; case 238: case 207: - return 942011713; + return 638121281; case 155: - return 1003668801; + return 653616449; case 154: case 156: case 157: - return 1003668801; + return 653616449; case 119: case 134: case 131: @@ -23796,12 +24455,12 @@ var ts; case 240: return -3; case 186: - return 942740801; + return 638358849; case 272: - return 940574017; + return 637797697; case 182: case 183: - return 940049729; + return 637666625; case 192: case 210: case 306: @@ -23810,9 +24469,9 @@ var ts; return 536872257; case 187: case 188: - return 671089985; + return 570426689; default: - return 939525441; + return 637535553; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -24013,6 +24672,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); var cancellationToken; var requestedExternalEmitHelpers; var externalHelpersModule; @@ -24022,7 +24693,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -24031,6 +24703,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -24230,8 +24903,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -24295,7 +24968,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -24325,8 +24999,19 @@ var ts; var stringType = createIntrinsicType(4, "string"); var numberType = createIntrinsicType(8, "number"); var falseType = createIntrinsicType(256, "false"); + var regularFalseType = createIntrinsicType(256, "false"); var trueType = createIntrinsicType(256, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256, "true"); + falseType.flags |= 33554432; + trueType.flags |= 33554432; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024, "symbol"); var voidType = createIntrinsicType(4096, "void"); var neverType = createIntrinsicType(32768, "never"); @@ -24364,6 +25049,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -24379,6 +25066,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -24390,7 +25078,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); var flowLoopStart = 0; var flowLoopCount = 0; @@ -24546,35 +25233,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2) - result |= 67216319; + result |= 67220415; if (flags & 1) - result |= 67216318; + result |= 67220414; if (flags & 4) result |= 0; if (flags & 8) result |= 68008959; if (flags & 16) - result |= 67215791; + result |= 67219887; if (flags & 32) result |= 68008383; if (flags & 64) - result |= 67901832; + result |= 67897736; if (flags & 256) result |= 68008191; if (flags & 128) result |= 68008831; if (flags & 512) - result |= 67215503; + result |= 110735; if (flags & 8192) - result |= 67208127; + result |= 67212223; if (flags & 32768) - result |= 67150783; + result |= 67154879; if (flags & 65536) - result |= 67183551; + result |= 67187647; if (flags & 262144) - result |= 67639784; + result |= 67635688; if (flags & 524288) - result |= 67901928; + result |= 67897832; if (flags & 2097152) result |= 2097152; return result; @@ -24614,6 +25301,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { target.valueDeclaration = source.valueDeclaration; } @@ -24635,52 +25323,53 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 || source.flags & 384); - var isEitherBlockScoped = !!(target.flags & 2 || source.flags & 2); + var isEitherBlockScoped_1 = !!(target.flags & 2 || source.flags & 2); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -24772,8 +25461,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -24880,18 +25569,25 @@ var ts; if (result = lookup(location.locals, name, meaning)) { var useResult = true; if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - if (meaning & result.flags & 67901928 && lastLocation.kind !== 289) { + if (meaning & result.flags & 67897832 && lastLocation.kind !== 289) { useResult = result.flags & 262144 ? lastLocation === location.type || lastLocation.kind === 149 || lastLocation.kind === 148 : false; } - if (meaning & 67216319 && result.flags & 1) { - useResult = - lastLocation.kind === 149 || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3) { + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1) { + useResult = + lastLocation.kind === 149 || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173) { @@ -24946,7 +25642,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319)) { + if (lookup(ctor.locals, name, meaning & 67220415)) { propertyWithInvalidInitializer = location; } } @@ -24955,7 +25651,7 @@ var ts; case 238: case 207: case 239: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { result = undefined; break; @@ -24977,7 +25673,7 @@ var ts; case 209: if (lastLocation === location.expression && location.parent.token === 85) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -24988,7 +25684,7 @@ var ts; case 147: grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239) { - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -25044,7 +25740,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -25053,7 +25749,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, false)) { return requireSymbol; } @@ -25094,13 +25790,13 @@ var ts; } if (errorLocation && (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 67216319) === 67216319))) { + ((meaning & 32 || meaning & 384) && (meaning & 67220415) === 67220415))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } - if (result && isInExternalModule && (meaning & 67216319) === 67216319 && !(originalLocation.flags & 2097152)) { + if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); @@ -25188,9 +25884,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(errorLocation) ? 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(errorLocation) ? 67220415 : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~namespaceMeaning, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~namespaceMeaning, undefined, undefined, false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -25209,29 +25905,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024)) { + if (meaning & (67220415 & ~1024)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 & ~67216319, undefined, undefined, false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 & ~67220415, undefined, undefined, false)); if (symbol && !(symbol.flags & 1024)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 & ~1024 & ~67901928)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67216319, undefined, undefined, false)); + if (meaning & (67220415 & ~1024 & ~67897832)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~67220415, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 & ~1024 & ~67216319)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67901928, undefined, undefined, false)); + else if (meaning & (67897832 & ~1024 & ~67220415)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~67897832, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -25241,7 +25940,7 @@ var ts; } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -25258,6 +25957,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -25313,7 +26015,7 @@ var ts; } return true; } - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); @@ -25347,7 +26049,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 | 1920)) { + if (valueSymbol.flags & (67897832 | 1920)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -25400,7 +26102,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -25434,7 +26136,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 | 67901928 | 1920, true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 | 67897832 | 1920, true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -25453,7 +26155,7 @@ var ts; case 251: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255: - return getTargetOfExportSpecifier(node, 67216319 | 67901928 | 1920, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 | 67897832 | 1920, dontRecursivelyResolve); case 252: case 202: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -25464,7 +26166,7 @@ var ts; } } function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 | 67901928 | 1920; } + if (excludes === void 0) { excludes = 67220415 | 67897832 | 1920; } if (!symbol) return false; return (symbol.flags & (2097152 | excludes)) === 2097152 || !!(symbol.flags & 2097152 && symbol.flags & 67108864); @@ -25498,7 +26200,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -25531,21 +26233,21 @@ var ts; } else { ts.Debug.assert(entityName.parent.kind === 246); - return resolveEntityName(entityName, 67216319 | 67901928 | 1920, false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 | 67897832 | 1920, false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, undefined, 16 | 4); } function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 | (ts.isInJavaScriptFile(name) ? meaning & 67216319 : 0); + var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 67220415 : 0); var symbol; if (name.kind === 71) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { return symbolFromJSPrototype; @@ -25561,7 +26263,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -25590,15 +26292,15 @@ var ts; ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, undefined, name, true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -25606,9 +26308,19 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3) { + ts.getAssignmentDeclarationKind(host.expression) === 3) { var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6) { + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -25616,6 +26328,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -25645,7 +26364,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); } return getMergedSymbol(sourceFile.symbol); @@ -25661,7 +26380,7 @@ var ts; return getMergedSymbol(pattern.symbol); } } - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -25691,7 +26410,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -25699,7 +26418,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json") && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -25711,23 +26430,21 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages(undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages(undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -25937,7 +26654,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67216319); + return !!(symbol.flags & 67220415 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 67220415); } function findConstructorDeclaration(node) { var members = node.members; @@ -26030,7 +26747,7 @@ var ts; return callback(globals); } function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 67216319 ? 67216319 : 1920; + return rightMeaning === 67220415 ? 67220415 : 1920; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -26069,7 +26786,8 @@ var ts; && symbolFromSymbolTable.escapedName !== "export=" && symbolFromSymbolTable.escapedName !== "default" && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -26126,11 +26844,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832, false); return access.accessibility === 0; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319, false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415, false); return access.accessibility === 0; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -26154,7 +26872,14 @@ var ts; }; } } - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -26242,14 +26967,14 @@ var ts; if (entityName.parent.kind === 165 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } else if (entityName.kind === 146 || entityName.kind === 187 || entityName.parent.kind === 246) { meaning = 1920; } else { - meaning = 67901928; + meaning = 67897832; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); @@ -26271,6 +26996,9 @@ var ts; if (flags & 8) { nodeFlags |= 16384; } + if (flags & 16) { + nodeFlags |= 67108864; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26353,7 +27081,11 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -26398,13 +27130,13 @@ var ts; } if (type.flags & 512 && !(type.flags & 262144)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928, false); + var parentName = symbolToName(parentSymbol, context, 67897832, false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, undefined); } if (type.flags & 544) { - var name = symbolToName(type.symbol, context, 67901928, false); + var name = symbolToName(type.symbol, context, 67897832, false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, undefined); } @@ -26424,7 +27156,7 @@ var ts; if (!(context.flags & 1048576)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319); + return symbolToTypeNode(type.symbol, context, 67220415); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -26490,17 +27222,20 @@ var ts; return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 | 8), undefined); } return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928) + ? symbolToTypeNode(type.symbol, context, 67897832) : ts.createTypeReferenceNode(ts.createIdentifier("?"), undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832, typeArgumentNodes); } if (type.flags & (262144 | 524288)) { var types = type.flags & 262144 ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 ? 171 : 172, typeNodes); @@ -26567,19 +27302,19 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 && type.symbol && type.symbol.flags & 32; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 : 67216319; + if (isJSConstructor(symbol.valueDeclaration)) { + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 : 67220415; return symbolToTypeNode(symbol, context, isInstanceType); } else if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319); + return symbolToTypeNode(symbol, context, 67220415); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - return symbolToTypeNode(typeAlias, context, 67901928); + return symbolToTypeNode(typeAlias, context, 67897832); } else { context.approximateLength += 3; @@ -26657,8 +27392,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -26694,7 +27429,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16; - var ref = symbolToTypeNode(parent, context, 67901928, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -26707,7 +27442,7 @@ var ts; } var flags = context.flags; context.flags |= 16; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -26801,17 +27536,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 | 1048576, undefined, undefined, true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319, true); + var propertyName = symbolToName(propertySymbol, context, 67220415, true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -26930,7 +27661,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928, undefined, type.symbol.escapedName, false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832, undefined, type.symbol.escapedName, false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -26941,7 +27672,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 | 8) - : symbolToName(type.symbol, context, 67901928, true); + : symbolToName(type.symbol, context, 67897832, true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -26980,6 +27711,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184) { @@ -26989,11 +27723,20 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 | 1048576, undefined, undefined, true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64) && !(context.flags & 67108864)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } @@ -27089,7 +27832,10 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -27097,7 +27843,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384)); - var isTypeOf = meaning === 67216319; + var isTypeOf = meaning === 67220415; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); @@ -27194,6 +27940,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216; } @@ -27252,7 +28001,7 @@ var ts; var baseType = t.flags & 256 ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -27411,10 +28160,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252) { - exportSymbol = resolveName(node, node.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, node, false); + exportSymbol = resolveName(node, node.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, node, false); } else if (node.parent.kind === 255) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 | 67901928 | 1920 | 2097152); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 | 67897832 | 1920 | 2097152); } var result; if (exportSymbol) { @@ -27434,7 +28183,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 | 67901928 | 1920, undefined, undefined, false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 | 67897832 | 1920, undefined, undefined, false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -27471,6 +28220,8 @@ var ts; switch (propertyName) { case 0: return !!getSymbolLinks(target).type; + case 5: + return !!(getNodeLinks(target).resolvedEnumType); case 2: return !!getSymbolLinks(target).declaredType; case 1: @@ -27479,6 +28230,8 @@ var ts; return !!target.resolvedReturnType; case 4: return !!target.immediateBaseConstraint; + case 6: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -27622,33 +28375,33 @@ var ts; } else { var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } } } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192)) { type = getTypeWithFacts(type, 131072); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -27688,7 +28441,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1) && !(declaration.flags & 4194304)) { if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { @@ -27712,15 +28465,21 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } if (declaration.initializer) { @@ -27735,15 +28494,15 @@ var ts; } return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -27757,8 +28516,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -27766,16 +28525,16 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; if (!type) { var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -27786,15 +28545,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -27813,7 +28570,7 @@ var ts; type.objectFlags |= 16384; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -27826,10 +28583,10 @@ var ts; } return declaredType; } - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 && - special === 2 && + kind === 2 && symbol.escapedName === "export=") { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -27853,9 +28610,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -27875,8 +28630,8 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, false).parent; return ts.isClassLike(parent) && parent; }); @@ -27884,7 +28639,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -27895,8 +28650,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -27966,9 +28721,9 @@ var ts; return getWidenedType(type); } type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -28007,18 +28762,25 @@ var ts; } if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } if (!pushTypeResolution(symbol, 0)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -28031,7 +28793,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -28092,7 +28854,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156); var setter = ts.getDeclarationOfKind(symbol, 157); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -28116,14 +28878,12 @@ var ts; type = getReturnTypeFromBody(getter); } else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -28146,7 +28906,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -28173,7 +28933,7 @@ var ts; } else if (declaration.kind === 202 || declaration.kind === 187 && declaration.parent.kind === 202) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -28182,11 +28942,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=")); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16, symbol); @@ -28206,7 +28966,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 67216319 + links.type = targetSymbol.flags & 67220415 ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -28215,22 +28975,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -28375,23 +29127,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -28452,7 +29201,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 && areAllOuterTypeParametersApplied(originalBaseType)) { baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol, typeArgs); @@ -28460,8 +29211,8 @@ var ts; else if (baseConstructorType.flags & 1) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); @@ -28542,7 +29293,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928, true); + var baseSymbol = resolveEntityName(node.expression, 67897832, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -28671,9 +29422,9 @@ var ts; if (declaration.kind === 241) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -28851,7 +29602,7 @@ var ts; if (type.flags & 2048) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192) { + if (type.flags & (64 | 128)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -28866,7 +29617,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319) { + if (symbolFlags & 67220415) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -29067,7 +29818,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -29190,7 +29941,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { var signatures = getSignaturesOfType(t, 1); @@ -29208,7 +29959,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -29254,6 +30005,7 @@ var ts; setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); if (symbol.flags & (16 | 8192)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } if (symbol.flags & 32) { var classType = getDeclaredTypeOfClassOrInterface(symbol); @@ -29348,7 +30100,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -29505,10 +30257,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -29520,7 +30277,8 @@ var ts; } function getConstraintOfDistributiveConditionalType(type) { if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -29582,6 +30340,7 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -29589,8 +30348,14 @@ var ts; if (!pushTypeResolution(t, 4)) { return circularConstraintType; } + if (constraintDepth === 50) { + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -29612,8 +30377,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -29628,7 +30393,7 @@ var ts; if (t.flags & 2097152) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304) { @@ -29638,9 +30403,6 @@ var ts; if (t.flags & 8388608) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -29677,16 +30439,31 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } function getApparentType(type) { var t = type.flags & 15794176 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 ? globalStringType : - t.flags & 168 ? globalNumberType : - t.flags & 272 ? globalBooleanType : - t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t.flags & 1048576 ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 ? getApparentTypeOfMappedType(t) : + t.flags & 524288 ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 ? globalStringType : + t.flags & 168 ? globalNumberType : + t.flags & 272 ? globalBooleanType : + t.flags & 3072 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t.flags & 1048576 ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -29715,10 +30492,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1)) || getIndexInfoOfType(type, 0)); - if (index) { - checkFlags |= index.isReadonly ? 8 : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1) || getIndexInfoOfType(type, 0)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16; @@ -29795,8 +30572,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -29867,7 +30648,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && (node.type && node.type.kind === 286 + return ts.isInJSFile(node) && (node.type && node.type.kind === 286 || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; return isBracketed || !!typeExpression && typeExpression.type.kind === 286; @@ -29957,7 +30738,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -29966,7 +30747,7 @@ var ts; var paramSymbol = param.symbol; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319, undefined, undefined, false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415, undefined, undefined, false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this") { @@ -30001,7 +30782,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } return links.resolvedSignature; @@ -30024,7 +30805,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -30108,7 +30889,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -30149,6 +30930,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -30185,7 +30967,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -30204,8 +30986,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -30239,7 +31025,7 @@ var ts; signature; } function createCanonicalSignature(signature) { - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -30409,10 +31195,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -30438,7 +31224,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -30485,32 +31271,50 @@ var ts; if (type) { return type; } + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); if (jsdocType) { return jsdocType; } - resolveTypeReferenceName(getTypeReferenceName(node), 67901928); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832); return getTypeOfSymbol(symbol); } function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + if (referenceType || assignedType) { + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -30626,10 +31430,10 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928; + var meaning = 67897832; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319; + meaning |= 67220415; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); @@ -30678,10 +31482,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { return resolveName(undefined, name, meaning, diagnostic, name, false); @@ -30708,6 +31512,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -30734,7 +31541,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928, undefined); + var symbol = getGlobalSymbol(name, 67897832, undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -30845,6 +31652,13 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -30901,10 +31715,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -30917,15 +31728,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -30971,7 +31773,7 @@ var ts; var remove = t.flags & 64 && includes & 4 || t.flags & 128 && includes & 8 || t.flags & 2048 && includes & 1024 || - t.flags & 192 && t.flags & 33554432 && containsType(types, t.regularType); + t.flags & 448 && t.flags & 33554432 && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -30992,7 +31794,7 @@ var ts; } switch (unionReduction) { case 1: - if (includes & 2240) { + if (includes & 2240 | 256) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -31080,18 +31882,15 @@ var ts; if (type === wildcardType) includes |= 268435456; } - else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type) && - !(flags & 131072 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } return includes; } function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -31308,7 +32107,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? @@ -31321,20 +32120,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576) && isTypeAssignableToKind(indexType, 68 | 168 | 3072)) { @@ -31380,7 +32182,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -31398,7 +32200,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 | 134217728); @@ -31406,18 +32211,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 | 1048576); } - function isStringIndexOnlyType(type) { - if (type.flags & 131072 && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 ? getSimplifiedIndexedAccessType(type) : type; } @@ -31427,27 +32220,16 @@ var ts; } type.simplified = circularConstraintType; var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 && isGenericObjectType(objectType)) { - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + if (indexType.flags & 262144) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + if (!(indexType.flags & 15794176)) { + if (objectType.flags & 262144) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + if (objectType.flags & 524288) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } if (isGenericMappedType(objectType)) { @@ -31466,7 +32248,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -31484,17 +32267,26 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 && !(indexType.flags & 16)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false, missingType); + if (propType === missingType) { + if (!accessNode) { + return missingType; + } + else { + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -31653,7 +32445,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 : node.flags & 2097152 ? 67216319 | 67901928 : 67901928; + var targetMeaning = node.isTypeOf ? 67220415 : node.flags & 2097152 ? 67220415 | 67897832 : 67897832; var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { links.resolvedSymbol = unknownSymbol; @@ -31682,7 +32474,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 + var errorMessage = targetMeaning === 67220415 ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -31696,7 +32488,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319) { + if (meaning === 67220415) { return links.resolvedType = getTypeOfSymbol(symbol); } else { @@ -31830,7 +32622,7 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 && !(type.flags & 33554432)) { + if (type.flags & 448 && !(type.flags & 33554432)) { if (!type.freshType) { var freshType = createLiteralType(type.flags | 33554432, type.value, type.symbol); freshType.regularType = type; @@ -31841,7 +32633,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 && type.flags & 33554432 ? type.regularType : + return type.flags & 448 && type.flags & 33554432 ? type.regularType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -32037,7 +32829,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -32119,7 +32911,7 @@ var ts; var typeParameters = links.outerTypeParameters; if (!typeParameters) { var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -32129,7 +32921,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -32182,31 +32974,41 @@ var ts; return !!ts.forEachChild(node, containsReference); } } - function instantiateMappedType(type, mapper) { + function getHomomorphicTypeVariable(type) { var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 1048576) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536) { + return typeVariable; + } + } + return undefined; + } + function instantiateMappedType(type, mapper) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 | 14745600 | 131072 | 524288) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 | 14745600 | 131072 | 524288); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -32230,6 +33032,11 @@ var ts; var result = createObjectType(type.objectFlags | 64, type.symbol); if (type.objectFlags & 32) { result.declaration = type.declaration; + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -32263,46 +33070,59 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536) { + return mapper(type); + } + if (flags & 131072) { + var objectFlags = type.objectFlags; + if (objectFlags & 16) { + return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072) { - if (type.objectFlags & 16) { - return type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 && !(type.flags & 32764)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 && !(flags & 32764)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -32367,7 +33187,7 @@ var ts; return body.kind === 216 ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -32406,8 +33226,9 @@ var ts; return source.flags & 262144 ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 | 16777216)) : + target === globalFunctionType ? !!(source.flags & 131072) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } function isTypeComparableTo(source, target) { return isTypeRelatedTo(source, target, comparableRelation); @@ -32419,53 +33240,116 @@ var ts; return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); } function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 || (type.flags & 524288 && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268: case 193: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202: switch (node.operatorToken.kind) { case 58: case 26: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195: + return elaborateArrowFunction(node, source, target, relation); } return false; } - function elaborateElementwise(iterator, source, target) { + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0); + var constructSignatures = getSignaturesOfType(source, 1); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 | 32768)) && checkTypeRelatedTo(returnType, target, relation, undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + if (ts.isBlock(node.body)) { + return false; + } + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, undefined, undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } + } + return false; + } + function elaborateElementwise(iterator, source, target, relation) { var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, undefined); if (elaborated) { reportedError = true; } else { var resultObj = {}; var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, undefined, resultObj); if (result && specificSource !== sourcePropType) { - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -32476,13 +33360,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168) && getIndexInfoOfType(target, 1) || getIndexInfoOfType(target, 0) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -32516,8 +33403,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -32548,9 +33435,13 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + var tupleizedType = checkArrayLiteral(node, 3, true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -32599,8 +33490,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); @@ -32621,9 +33512,9 @@ var ts; source = instantiateSignatureInContextOf(source, target, undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { return 0; } var kind = target.declaration ? target.declaration.kind : 0; @@ -32645,11 +33536,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && @@ -32666,13 +33557,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); @@ -32828,10 +33719,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source === target || @@ -32946,10 +33837,10 @@ var ts; } function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 && source.flags & 33554432) { + if (source.flags & 448 && source.flags & 33554432) { source = source.regularType; } - if (target.flags & 192 && target.flags & 33554432) { + if (target.flags & 448 && target.flags & 33554432) { target = target.regularType; } if (source.flags & 8388608) { @@ -32991,13 +33882,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432) && - !(target.flags & 262144) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 | 131072 | 524288) && source !== globalObjectType && + target.flags & (131072 | 524288) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0); @@ -33070,7 +33958,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072) { + if (flags & 131072 || flags & 2097152 || flags & 4194304 || flags & 1048576 || flags & 8388608) { return recursiveTypeRelatedTo(source, target, false); } if (flags & (262144 | 524288)) { @@ -33080,32 +33968,6 @@ var ts; } } } - if (flags & 1048576) { - return isRelatedTo(source.type, target.type, false); - } - if (flags & 2097152) { - if (result = isRelatedTo(source.objectType, target.objectType, false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, false)) { - return result; - } - } - } - if (flags & 4194304) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608) { - return isRelatedTo(source.substitute, target.substitute, false); - } return 0; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -33121,8 +33983,8 @@ var ts; if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { if (!errorNode) return { value: ts.Debug.fail() }; @@ -33154,13 +34016,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; @@ -33189,7 +34054,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; @@ -33216,31 +34082,23 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; @@ -33383,6 +34241,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072)) { + if (flags & 1048576) { + return isRelatedTo(source.type, target.type, false); + } + var result_2 = 0; + if (flags & 2097152) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_2; + } + } + } + if (flags & 4194304) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608) { + return isRelatedTo(source.substitute, target.substitute, false); + } + return 0; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -33407,18 +34296,19 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; } } } } else if (target.flags & 2097152) { - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -33434,7 +34324,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -33502,6 +34391,25 @@ var ts; } } else { + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0; + } + var sourceIsPrimitive = !!(source.flags & 32764); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { var variances = getVariances(source.target); @@ -33516,29 +34424,20 @@ var ts; errorInfo = saveErrorInfo; } } - var sourceIsPrimitive = !!(source.flags & 32764); - if (relation !== identityRelation) { - source = getApparentType(source); + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1) || anyType, getIndexTypeOfType(target, 1) || anyType, reportErrors); } if (source.flags & (131072 | 524288) && target.flags & 131072) { var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); } } } @@ -33558,10 +34457,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -33684,29 +34583,6 @@ var ts; } return result; } - function isWeakType(type) { - if (type.flags & 131072) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); - } - if (type.flags & 524288) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 && target.flags & 131072)) { return 0; @@ -33738,8 +34614,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1) ? 0 : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1) ? @@ -33907,6 +34783,48 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + function isWeakType(type) { + if (type.flags & 131072) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 524288) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } function getMarkerTypeReference(type, source, target) { var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; })); result.objectFlags |= 8192; @@ -34134,8 +35052,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -34181,9 +35099,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 | 32768)); @@ -34205,10 +35128,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 && type.flags & 33554432 ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 && type.flags & 33554432 ? stringType : type.flags & 128 && type.flags & 33554432 ? numberType : - type.flags & 256 ? booleanType : + type.flags & 256 && type.flags & 33554432 ? booleanType : type.flags & 262144 ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -34229,13 +35152,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -34244,7 +35171,7 @@ var ts; return type.flags & 262144 ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 ? type.value === "" ? 64 : 0 : type.flags & 128 ? type.value === 0 ? 128 : 0 : - type.flags & 256 ? type === falseType ? 256 : 0 : + type.flags & 256 ? (type === falseType || type === regularFalseType) ? 256 : 0 : type.flags & 29148; } function removeDefinitelyFalsyTypes(type) { @@ -34258,11 +35185,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 ? emptyStringType : type.flags & 8 ? zeroType : - type.flags & 16 || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 | 8192 | 16384) || - type.flags & 64 && type.value === "" || - type.flags & 128 && type.value === 0 ? type : - neverType; + type.flags & 64 && type.value === "" || + type.flags & 128 && type.value === 0 ? type : + neverType; } function getNullableType(type, flags) { var missing = (flags & ~type.flags) & (8192 | 16384); @@ -34468,8 +35396,11 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + return; + } var diagnostic; switch (declaration.kind) { case 202: @@ -34492,43 +35423,48 @@ var ts; case 157: case 194: case 195: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728) { if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -34686,7 +35622,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34749,11 +35687,11 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8) && target.flags & 65536 && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -34801,6 +35739,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432) { var targetTypes = target.types; var typeVariableCount = 0; @@ -34831,7 +35772,12 @@ var ts; } else { if (!(priority & 32 && source.flags & (524288 | 15794176))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 | 524288))) { + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 | 524288)) { var key = source.id + "," + target.id; @@ -34914,33 +35860,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -34950,12 +35901,19 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0; + bivariant = bivariant || kind === 154 || kind === 153 || kind === 155; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -34986,8 +35944,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -35006,7 +35964,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 | 1048576); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 | 1048576); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128); @@ -35024,7 +35982,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { var candidates = widenObjectLiteralCandidates(inference.candidates); var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); var widenLiteralTypes = !primitiveConstraint && inference.topLevel && @@ -35032,7 +35990,7 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = context.flags & 1 || inference.priority & 28 ? + var unwidenedType = inference.priority & 28 ? getUnionType(baseCandidates, 2) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -35043,14 +36001,17 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2) { + else if (context.flags & 1) { inferredType = silentNeverType; } else { @@ -35059,7 +36020,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2)); } } } @@ -35087,11 +36048,40 @@ var ts; } return result; } + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + resolveName(node, node.escapedText, 67220415 | 1048576, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -35199,14 +36189,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144) { + if (type.flags & (16 | 512)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 && !(combined & 15794176)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -35250,13 +36256,28 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { if (assignedType.flags & 32768) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 && assignedType.flags & 256) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); + } + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -35264,8 +36285,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -35300,13 +36321,15 @@ var ts; } if (flags & 272) { return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; + (type === falseType || type === regularFalseType) ? 3030404 : 1981828 : + (type === falseType || type === regularFalseType) ? 3145092 : 4193668; } if (flags & 131072) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 : 4181984 : - strictNullChecks ? 1972176 : 4184016; + return ts.getObjectFlags(type) & 16 && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 : 4194303 : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 : 4181984 : + strictNullChecks ? 1972176 : 4184016; } if (flags & (4096 | 8192)) { return 2457472; @@ -35346,7 +36369,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, undefined, false, false) || errorType; } @@ -35429,10 +36452,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 || node.kind === 184 ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 || node.kind === 184 ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 && node.initializer && @@ -35478,6 +36501,21 @@ var ts; } return links.switchTypes; } + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269) { + if (clause.expression.kind === 9) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -35502,6 +36540,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144) { var types = type.types; @@ -35520,8 +36561,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -35590,8 +36631,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -35662,7 +36703,7 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { + if (flowDepth === 2000) { flowAnalysisDisabled = true; reportFlowControlError(reference); return errorType; @@ -35751,15 +36792,21 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } if (containsMatchingReference(reference, node)) { + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 || init.kind === 195)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } return undefined; @@ -35782,7 +36829,7 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -35811,15 +36858,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -36041,9 +37094,19 @@ var ts; if (type.flags & 1 && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -36054,11 +37117,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); @@ -36076,6 +37136,47 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + if (!(hasDefaultClause || (type.flags & 262144))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -36085,7 +37186,7 @@ var ts; return type; } var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -36100,21 +37201,12 @@ var ts; return type; } if (!targetType) { - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -36218,8 +37310,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; + if (!(links.flags & 8388608)) { + links.flags |= 8388608; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -36227,7 +37319,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608); }); } function markParameterAssignments(node) { if (node.kind === 71) { @@ -36270,7 +37362,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 67216319) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, 67220415) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -36303,8 +37395,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; break; } container = ts.getContainingClass(container); @@ -36315,8 +37407,8 @@ var ts; while (container.kind !== 277) { if (container.parent === declaration) { if (container.kind === 152 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; + getNodeLinks(declaration).flags |= 16777216; + getNodeLinks(node).flags |= 33554432; } break; } @@ -36329,7 +37421,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -36392,6 +37484,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 || (symbol.flags & (2 | 32)) === 0 || @@ -36411,19 +37506,39 @@ var ts; } if (containedInIterationStatement) { if (usedInFunction) { - getNodeLinks(current).flags |= 65536; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536; + } } if (container.kind === 223 && ts.getAncestor(symbol.valueDeclaration, 236).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304; } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; + getNodeLinks(symbol.valueDeclaration).flags |= 524288; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; + getNodeLinks(symbol.valueDeclaration).flags |= 262144; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { var current = node; while (current.parent.kind === 193) { @@ -36530,23 +37645,23 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 194 && - container.parent.kind === 202 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } - else if ((container.kind === 194 || container.kind === 237) && + else if (isInJS && + (container.kind === 194 || container.kind === 237) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -36561,13 +37676,36 @@ var ts; var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + if (container.kind === 194 && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3) { + return container.parent + .left + .expression + .expression; + } + else if (container.kind === 154 && + container.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6) { + return container.parent.parent.left.expression; + } + else if (container.kind === 194 && + container.parent.kind === 273 && + container.parent.parent.kind === 186 && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287) { @@ -36718,7 +37856,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -36765,7 +37903,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -36824,9 +37962,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; + if (contextualReturnType) { + if (functionFlags & 2) { + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -36887,10 +38037,17 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54: var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53: case 26: @@ -36899,8 +38056,8 @@ var ts; return undefined; } } - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0: return true; @@ -36916,19 +38073,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319, undefined, id.escapedText, true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415, undefined, id.escapedText, true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4: case 2: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -36946,6 +38130,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); } return undefined; }, true); @@ -36953,9 +38139,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, true); } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); if (node.flags & 8388608) { @@ -36968,8 +38151,8 @@ var ts; var type = getApparentTypeOfContextualType(objectLiteral); if (type) { if (!hasNonBindableDynamicName(element)) { - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -37022,44 +38205,34 @@ var ts; case 86: case 95: case 71: + case 140: return true; case 187: case 193: return isPossiblyDiscriminantValue(node.expression); + case 268: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } function getContextualType(node) { if (node.flags & 8388608) { @@ -37081,6 +38254,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205: return getContextualTypeForYieldOperand(parent); + case 199: + return getContextualTypeForAwaitOperand(parent); case 189: case 190: return getContextualTypeForArgument(parent, node); @@ -37105,7 +38280,7 @@ var ts; ts.Debug.assert(parent.parent.kind === 204); return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193: { - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268: @@ -37124,6 +38299,9 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -37131,7 +38309,7 @@ var ts; if (isTypeAny(valueType)) { return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -37195,11 +38373,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -37290,8 +38468,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -37323,7 +38501,7 @@ var ts; return (node.kind === 184 && !!node.initializer) || (node.kind === 202 && node.operatorToken.kind === 58); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -37333,7 +38511,7 @@ var ts; for (var index = 0; index < elementCount; index++) { var e = elements[index]; if (inDestructuringPattern && e.kind === 206) { - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1) || getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); if (restElementType) { @@ -37342,7 +38520,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206) { @@ -37352,33 +38530,44 @@ var ts; if (!hasNonEndingSpreadElement) { var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206; var minLength = elementCount - (hasRestElement ? 1 : 0); + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (!hasRestElement && pattern && (pattern.kind === 183 || pattern.kind === 185)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 && e.dotDotDotToken || e.kind === 206)) { - if (e.kind !== 208) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + if (!hasRestElement && pattern && (pattern.kind === 183 || pattern.kind === 185)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 && e.dotDotDotToken || e.kind === 206)) { + if (e.kind !== 208) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1; } return createArrayType(elementTypes.length ? @@ -37442,9 +38631,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 || contextualType.pattern.kind === 186); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -37462,7 +38651,7 @@ var ts; var type = memberDecl.kind === 273 ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -37643,12 +38832,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096); var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -37665,7 +38856,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -37673,7 +38864,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, 0, 4096); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -37682,7 +38873,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096); } } var parent = openingLikeElement.parent.kind === 258 ? openingLikeElement.parent : undefined; @@ -37692,13 +38883,15 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, 0, 4096); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, undefined, undefined), attributes.symbol, propagatingFlags, 4096); } } if (hasSpreadAnyType) { @@ -37710,7 +38903,7 @@ var ts; return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, undefined, undefined); - result.flags |= 268435456; + result.flags |= (propagatingFlags |= 268435456); result.objectFlags |= 128 | 4096; return result; } @@ -37736,7 +38929,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928); + var typeSymbol = exports && getSymbol(exports, name, 67897832); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } function getIntrinsicTagSymbol(node) { @@ -37775,7 +38968,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -37785,7 +38978,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 4 : 0); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, isJavascript ? 2 : 0); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -37842,7 +39035,7 @@ var ts; return getGlobalSymbol(JsxNames.JSX, 1920, undefined); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832); var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); if (propertiesOfJsxElementAttribPropInterface) { @@ -37859,7 +39052,7 @@ var ts; return undefined; } function getJsxLibraryManagedAttributes(jsxNamespace) { - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832); } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); @@ -38016,7 +39209,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, true); })); } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { @@ -38098,7 +39291,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319, reactRefErr, reactNamespace, true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415, reactRefErr, reactNamespace, true); if (reactSym) { reactSym.isReferenced = 67108863; if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { @@ -38179,10 +39372,10 @@ var ts; if (symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3; + ts.getAssignmentDeclarationKind(parent) === 3; } } function checkPropertyAccessibility(node, isSuper, type, prop) { @@ -38206,7 +39399,7 @@ var ts; } if ((flags & 128) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); return false; } @@ -38342,6 +39535,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192) && getFalsyFlags(flowType) & 8192) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); @@ -38449,7 +39648,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -38534,7 +39733,7 @@ var ts; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) - : ts.isInJavaScriptFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } function getForInVariableSymbol(node) { var initializer = node.initializer; @@ -38590,7 +39789,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -38598,7 +39797,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -38696,12 +39895,11 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var callIsIncomplete = false; - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { return true; } + var argCount; + var callIsIncomplete = false; if (node.kind === 191) { argCount = args.length; if (node.template.kind === 204) { @@ -38715,7 +39913,7 @@ var ts; } } else if (node.kind === 150) { - argCount = getEffectiveArgumentCount(node, undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -38724,10 +39922,10 @@ var ts; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { return false; @@ -38752,7 +39950,7 @@ var ts; return undefined; } function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { inferTypes(context.inferences, source, target); @@ -38760,7 +39958,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { var skipContextParamType = getTypeAtPosition(signature, 0); @@ -38796,43 +39994,36 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { + var arg = args[i]; + if (arg.kind !== 208) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 | 15794176) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { return arg.kind === 213 ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1) || anyType; @@ -38840,12 +40031,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -38854,23 +40042,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -38907,28 +40095,24 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 208) { - if (i === restIndex && (restType.flags & 65536 || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } function getThisArgumentOfCall(node) { @@ -38939,10 +40123,17 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } function getEffectiveCallArguments(node) { if (node.kind === 191) { var template = node.template; - var args_4 = [undefined]; + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -38950,178 +40141,70 @@ var ts; } return args_4; } - else if (node.kind === 150) { - return undefined; + if (node.kind === 150) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150) { - switch (node.parent.kind) { - case 238: - case 207: - return 1; - case 152: - return 2; - case 154: - case 156: - case 157: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 149: - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 238) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238: + case 207: + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149: + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152: + case 154: + case 156: + case 157: + var hasPropDesc = parent.kind !== 152 && languageVersion !== 0; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149) { - node = node.parent; - if (node.kind === 155) { - return anyType; - } - } - if (node.kind === 152 || - node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var element = node; - var name = element.name; - switch (name.kind) { - case 71: - return getLiteralType(ts.idText(name)); - case 8: - case 9: - return getLiteralType(name.text); - case 147: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 238) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149) { - return numberType; - } - if (node.kind === 152) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 || - node.kind === 156 || - node.kind === 157) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 150) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 150 || - (argIndex === 0 && node.kind === 191)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 191) { - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238: + case 207: + return 1; + case 152: + return 2; + case 154: + case 156: + case 157: + return languageVersion === 0 || signature.parameters.length <= 2 ? 2 : 3; + case 149: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -39130,6 +40213,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -39138,7 +40222,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -39149,16 +40236,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -39190,19 +40286,7 @@ var ts; } var args = getEffectiveCallArguments(node); var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; var candidateForArgumentError; var candidateForArgumentArityError; var candidateForTypeArgumentError; @@ -39229,14 +40313,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -39256,58 +40343,71 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) { + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { ts.Debug.assert(candidates.length > 0); return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) @@ -39322,7 +40422,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -39333,7 +40433,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -39360,17 +40460,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -39416,23 +40526,30 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { if (funcType !== errorType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); } if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0, relatedInformation); } return resolveErrorCall(node); } - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -39478,11 +40595,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -39549,10 +40668,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -39573,8 +40693,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -39607,8 +40727,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -39631,7 +40751,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, isForSignatureHelp) { @@ -39681,32 +40801,36 @@ var ts; links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; return result; } - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { if (ts.getJSDocClassTag(node)) return true; - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -39719,14 +40843,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -39769,7 +40890,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -39779,7 +40900,7 @@ var ts; return anyType; } } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -39787,8 +40908,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -39813,7 +40934,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319, undefined, undefined, false); + return globalESSymbol === resolveName(left, "Symbol", 67220415, undefined, undefined, false); } function checkImportCallExpression(node) { if (!checkGrammarArguments(node.arguments)) @@ -39868,7 +40989,7 @@ var ts; } if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319, undefined, undefined, true); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415, undefined, undefined, true); if (resolvedRequire === requireSymbol) { return true; } @@ -39991,14 +41112,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -40007,17 +41125,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -40041,15 +41149,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -40057,6 +41156,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -40136,6 +41246,14 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + var globalPromiseLikeType = getGlobalPromiseLikeType(true); + if (globalPromiseLikeType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -40242,10 +41360,40 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0; + if (hasDefault) { + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192; + } + } + else { + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64; + } + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197) { + var operandType = getTypeOfExpression(node.expression.expression); + var witnesses = getSwitchClauseTypeOfWitnesses(node); + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -40290,7 +41438,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; @@ -40341,6 +41489,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); if (checkMode === 1 && isContextSensitive(node)) { if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { var links_1 = getNodeLinks(node); @@ -40348,8 +41497,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -40385,7 +41536,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -40562,8 +41712,8 @@ var ts; } if (type.flags & 786432) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -40708,7 +41858,7 @@ var ts; if (element.kind !== 206) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -40732,8 +41882,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -40834,7 +41984,7 @@ var ts; return (target.flags & 24576) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -40963,9 +42113,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2) : leftType; case 58: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -40980,15 +42130,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928, undefined, name, false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832, undefined, name, false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -41033,8 +42183,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2: return true; case 1: @@ -41043,7 +42193,7 @@ var ts; case 3: case 4: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -41135,7 +42285,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266) { + if (node.kind === 266 && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; } return node; @@ -41174,19 +42324,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, true); var widened = ts.getCombinedNodeFlags(declaration) & 2 || - (ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -41212,11 +42358,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -41250,29 +42396,37 @@ var ts; return type; } function getTypeOfExpression(node, cache) { - if (node.kind === 189 && node.expression.kind !== 97 && !ts.isRequireCall(node, true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + var expr = ts.skipParentheses(node); + if (expr.kind === 189 && expr.expression.kind !== 97 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 || expr.kind === 210) { + return getTypeFromTypeNode(expr.type); + } return cache ? checkExpressionCached(node) : checkExpression(node); } function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1); node.contextualType = saveContextualType; return type; } - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -41287,13 +42441,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71: return checkIdentifier(node); @@ -41318,7 +42472,7 @@ var ts; case 12: return globalRegExpType; case 185: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186: return checkObjectLiteral(node, checkMode); case 187: @@ -41408,9 +42562,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { checkGrammarDecoratorsAndModifiers(node); checkVariableLikeDeclaration(node); @@ -41434,7 +42585,7 @@ var ts; error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -41835,7 +42986,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -41866,7 +43017,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -41963,8 +43114,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -42250,10 +43401,10 @@ var ts; case 246: case 249: case 248: - var result_3 = 0; + var result_4 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235: case 184: case 237: @@ -42374,7 +43525,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319, true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415, true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { @@ -42394,7 +43545,7 @@ var ts; return; } var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -42444,7 +43595,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 ? 67901928 : 1920) | 2097152; + var meaning = (typeName.kind === 71 ? 67897832 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol && rootSymbol.flags & 2097152 @@ -42662,14 +43813,14 @@ var ts; checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 && ts.nodeIsPresent(body)) { getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -43091,7 +44242,7 @@ var ts; return visit(n.expression); } else if (n.kind === 71) { - var symbol = resolveName(n, n.escapedText, 67216319 | 2097152, undefined, undefined, false); + var symbol = resolveName(n, n.escapedText, 67220415 | 2097152, undefined, undefined, false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -43158,7 +44309,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); markPropertyAsReferenced(property, undefined, false); - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97, parentType, property); } } @@ -43192,7 +44343,7 @@ var ts; if (node === symbol.valueDeclaration) { var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -43481,11 +44632,15 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } if (isReferenceToType(type, getGlobalIterableType(false)) || isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -43508,9 +44663,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -43965,13 +45122,15 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 2162688)) { var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -44013,7 +45172,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -44031,7 +45190,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -44168,6 +45327,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192); @@ -44604,8 +45765,8 @@ var ts; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (67216319 | 1048576) ? 67216319 : 0) | - (symbol.flags & 67901928 ? 67901928 : 0) | + var excludedMeanings = (symbol.flags & (67220415 | 1048576) ? 67220415 : 0) | + (symbol.flags & 67897832 ? 67897832 : 0) | (symbol.flags & 1920 ? 1920 : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 ? @@ -44615,7 +45776,7 @@ var ts; } if (compilerOptions.isolatedModules && node.kind === 255 - && !(target.flags & 67216319) + && !(target.flags & 67220415) && !(node.flags & 4194304)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -44666,13 +45827,13 @@ var ts; if (node.moduleReference.kind !== 257) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319) { + if (target.flags & 67220415) { var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 | 1920).flags & 1920)) { + if (!(resolveEntityName(moduleName, 67220415 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928) { + if (target.flags & 67897832) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -44721,12 +45882,12 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 | 67901928 | 1920 | 2097152, undefined, undefined, true); + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 | 67897832 | 1920 | 2097152, undefined, undefined, true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } @@ -44754,7 +45915,7 @@ var ts; } if (node.expression.kind === 71) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, true); } } @@ -44784,7 +45945,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -44826,7 +45987,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -44990,7 +46151,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -45042,13 +46203,20 @@ var ts; return addOptionality(type); } function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194: case 195: @@ -45100,9 +46268,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -45113,7 +46280,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -45195,7 +46361,7 @@ var ts; case 238: case 239: if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832); } break; case 194: @@ -45269,12 +46435,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -45299,7 +46465,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1: case 3: @@ -45325,7 +46491,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 && entityName.parent === entityName.parent.parent.left) { var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -45334,7 +46500,7 @@ var ts; } } if (entityName.parent.kind === 252 && ts.isEntityNameExpression(entityName)) { - var success = resolveEntityName(entityName, 67216319 | 67901928 | 1920 | 2097152, true); + var success = resolveEntityName(entityName, 67220415 | 67897832 | 1920 | 2097152, true); if (success && success !== unknownSymbol) { return success; } @@ -45358,9 +46524,9 @@ var ts; if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0; if (entityName.parent.kind === 209) { - meaning = 67901928; + meaning = 67897832; if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319; + meaning |= 67220415; } } else { @@ -45376,7 +46542,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 && entityName.parent.parent.kind === 301) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + ts.Debug.assert(!ts.isInJSFile(entityName)); var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -45389,7 +46555,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319, false, true); + return resolveEntityName(entityName, 67220415, false, true); } else if (entityName.kind === 187 || entityName.kind === 146) { var links = getNodeLinks(entityName); @@ -45406,7 +46572,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 ? 67901928 : 1920; + var meaning = entityName.parent.kind === 162 ? 67897832 : 1920; return resolveEntityName(entityName, meaning, false, true); } else if (entityName.parent.kind === 265) { @@ -45476,7 +46642,7 @@ var ts; case 13: if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 || node.parent.kind === 253) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -45490,6 +46656,7 @@ var ts; case 79: case 89: case 36: + case 75: return getSymbolOfNode(node.parent); case 181: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -45499,34 +46666,29 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274) { - return resolveEntityName(location.name, 67216319 | 2097152); + return resolveEntityName(location.name, 67220415 | 2097152); } return undefined; } function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 | 67901928 | 1920 | 2097152); + resolveEntityName(node.propertyName || node.name, 67220415 | 67897832 | 1920 | 2097152); } function getTypeOfNode(node) { if (node.flags & 8388608) { return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + if (classType && !classDecl.isImplements) { var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -45593,11 +46755,30 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71: + return getLiteralType(ts.idText(name)); + case 8: + case 9: + return getLiteralType(name.text); + case 147: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -45652,13 +46833,13 @@ var ts; var symbolLinks = getSymbolLinks(moduleSymbol); if (symbolLinks.exportsSomeValue === undefined) { symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319) + ? !!(moduleSymbol.flags & 67220415) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319); + return s && !!(s.flags & 67220415); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -45693,7 +46874,7 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); - if (isNonLocalAlias(symbol, 67216319)) { + if (isNonLocalAlias(symbol, 67220415)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -45706,11 +46887,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319, undefined, undefined, false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415, undefined, undefined, false)) { links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; + else if (nodeLinks_1.flags & 262144) { + var isDeclaredInLoop = nodeLinks_1.flags & 524288; var inLoopInitializer = ts.isIterationStatement(container, false); var inLoopBodyBlock = container.kind === 216 && ts.isIterationStatement(container.parent, false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -45778,7 +46959,7 @@ var ts; if (target === unknownSymbol) { return true; } - return !!(target.flags & 67216319) && + return !!(target.flags & 67220415) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -45791,7 +46972,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; - if (target && ts.getModifierFlags(node) & 1 && target.flags & 67216319) { + if (target && ts.getModifierFlags(node) & 1 && target.flags & 67220415) { return true; } } @@ -45824,6 +47005,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -45865,8 +47065,8 @@ var ts; if (!location) return ts.TypeReferenceSerializationKind.Unknown; } - var valueSymbol = resolveEntityName(typeName, 67216319, true, false, location); - var typeSymbol = resolveEntityName(typeName, 67901928, true, false, location); + var valueSymbol = resolveEntityName(typeName, 67220415, true, false, location); + var typeSymbol = resolveEntityName(typeName, 67897832, true, false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -45964,7 +47164,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 | 1048576 | 2097152, undefined, undefined, true); + return resolveName(location, reference.escapedText, 67220415 | 1048576 | 2097152, undefined, undefined, true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -45979,18 +47179,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 && type.flags & 33554432); + return !!(type.flags & 448 && type.flags & 33554432); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 ? nodeBuilder.symbolToExpression(type.symbol, 67220415, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); @@ -46028,6 +47230,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -46069,7 +47273,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 && node.parent.parent && node.parent.parent.kind === 271; @@ -46078,9 +47287,9 @@ var ts; if (!fileToDirective) { return undefined; } - var meaning = 67901928 | 1920; + var meaning = 67897832 | 1920; if ((node.kind === 71 && isInTypeQuery(node)) || (node.kind === 187 && !isInHeritageClause(node))) { - meaning = 67216319 | 1048576; + meaning = 67220415 | 1048576; } var symbol = resolveEntityName(node, meaning, true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -46158,6 +47367,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -46191,6 +47403,8 @@ var ts; globalArrayType = getGlobalType("Array", 1, true); globalObjectType = getGlobalType("Object", 0, true); globalFunctionType = getGlobalType("Function", 0, true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", 0, true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", 0, true) || globalFunctionType; globalStringType = getGlobalType("String", 0, true); globalNumberType = getGlobalType("Number", 0, true); globalBooleanType = getGlobalType("Boolean", 0, true); @@ -46215,29 +47429,28 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -46249,7 +47462,7 @@ var ts; for (var helper = 1; helper <= 65536; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -46617,10 +47830,31 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -46794,6 +48028,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { @@ -46818,8 +48055,9 @@ var ts; } var currentKind = void 0; switch (prop.kind) { - case 273: case 274: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + case 273: checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8) { checkGrammarNumericLiteral(name); @@ -47022,6 +48260,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -47108,24 +48349,32 @@ var ts; expr.kind === 200 && expr.operator === 38 && expr.operand.kind === 8; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 || node.initializer.kind === 86); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 && node.parent.parent.kind !== 225) { if (node.flags & 4194304) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -47259,10 +48508,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -47293,8 +48543,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 || ts.hasModifier(node, 32 | 128))) { @@ -50550,6 +51800,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -50558,19 +51823,7 @@ var ts; } ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -52706,8 +53959,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (524288 | 1048576)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 | 1048576)) + && !(element.transformFlags & (131072 | 262144)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -52754,7 +54007,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 1048576) { + if (element.transformFlags & 262144) { var temp = ts.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -53304,7 +54557,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); @@ -53333,9 +54586,11 @@ var ts; return ts.setTextRange(ts.createNodeArray(members), node.members); } function transformConstructor(node, isDerivedClass) { - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); } @@ -54420,7 +55675,7 @@ var ts; return ts.getGeneratedNameForNode(node); } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608) { + if (resolver.getNodeCheckFlags(node) & 16777216) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -54521,7 +55776,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1) { - if (resolver.getNodeCheckFlags(node) & 16777216) { + if (resolver.getNodeCheckFlags(node) & 33554432) { var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { var classAlias = classAliases[declaration.id]; @@ -54634,6 +55889,9 @@ var ts; var enabledSubstitutions; var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -54664,6 +55922,16 @@ var ts; return visitFunctionExpression(node); case 195: return visitArrowFunction(node); + case 187: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188: + if (capturedSuperProperties && node.expression.kind === 97) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -54848,21 +56116,30 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -54880,6 +56157,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -54912,6 +56191,7 @@ var ts; context.enableEmitNotification(156); context.enableEmitNotification(157); context.enableEmitNotification(155); + context.enableEmitNotification(217); } } function onEmitNode(hint, node, emitCallback) { @@ -54925,6 +56205,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -54947,13 +56234,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -54977,16 +56264,38 @@ var ts; || kind === 156 || kind === 157; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + function createSuperAccessVariableStatement(resolver, node, names) { + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined) + ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, true) + ])) + ], 2)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -55007,12 +56316,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); var ts; @@ -55029,6 +56338,9 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + var capturedSuperProperties; + var hasSuperElementAccess; + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -55097,6 +56409,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272: return visitCatchClause(node); + case 187: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188: + if (capturedSuperProperties && node.expression.kind === 97) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -55160,7 +56482,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { var objects = chunkObjectLiteralElements(node.properties); if (objects.length && objects[0].kind !== 186) { objects.unshift(ts.createObjectLiteral()); @@ -55182,7 +56504,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); } else if (node.operatorToken.kind === 26) { @@ -55191,7 +56513,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) { return ts.flattenDestructuringBinding(node, visitor, context, 1); } return ts.visitEachChild(node, visitor, context); @@ -55203,7 +56525,7 @@ var ts; return ts.visitEachChild(node, visitorNoDestructuringValue, context); } function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576) { + if (node.initializer.transformFlags & 262144) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -55290,7 +56612,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576) { + if (node.transformFlags & 262144) { return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -55367,19 +56689,31 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(39), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); + var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); - if (languageVersion >= 2) { + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -55403,7 +56737,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576) { + if (parameter.transformFlags & 262144) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { @@ -55426,6 +56760,7 @@ var ts; context.enableEmitNotification(156); context.enableEmitNotification(157); context.enableEmitNotification(155); + context.enableEmitNotification(217); } } function onEmitNode(hint, node, emitCallback) { @@ -55439,6 +56774,13 @@ var ts; return; } } + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } function onSubstituteNode(hint, node) { @@ -55461,13 +56803,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -55491,12 +56833,12 @@ var ts; || kind === 156 || kind === 157; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value"), location); + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), location); + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), undefined, [argumentExpression]), location); } } } @@ -56127,7 +57469,7 @@ var ts; return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && (ts.isStatement(node) || (node.kind === 216))) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432) !== 0; } function visitor(node) { @@ -56549,7 +57891,7 @@ var ts; } if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 | 32768))) { + && !(ctor.transformFlags & (8192 | 16384))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 || superCallExpression.left.kind !== 189) { @@ -56586,7 +57928,7 @@ var ts; } } function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072) !== 0; + return (node.transformFlags & 65536) !== 0; } function addDefaultValueAssignmentsIfNeeded(statements, node) { if (!shouldAddDefaultValueAssignments(node)) { @@ -56653,7 +57995,7 @@ var ts; statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 && node.kind !== 195) { + if (node.transformFlags & 16384 && node.kind !== 195) { captureThisForNode(statements, node, ts.createThis()); } } @@ -56785,7 +58127,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 8192) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -56993,21 +58335,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 + if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } function shouldEmitExplicitInitializerForLetDeclaration(node) { var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072; - var isDeclaredInLoop = flags & 262144; + var isCapturedInFunction = flags & 262144; + var isDeclaredInLoop = flags & 524288; var emittedAsTopLevel = (hierarchyFacts & 64) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -57188,7 +58536,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 && hierarchyFacts & 4) + if ((property.transformFlags & 4194304 && hierarchyFacts & 4) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -57214,7 +58562,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536) !== 0; } function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { @@ -57237,7 +58601,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps; @@ -57251,7 +58615,68 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224: return convertForInStatement(node, convertedLoopBody); + case 225: return convertForOfStatement(node, convertedLoopBody); + case 221: return convertDoStatement(node, convertedLoopBody); + case 222: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223: @@ -57266,150 +58691,175 @@ var ts; var loopParameters = []; var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { - if (outerConvertedLoopState.argumentsName) { - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { + if (convertedLoopState.argumentsName) { + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { - convertedLoopState.thisName = outerConvertedLoopState.thisName; + if (convertedLoopState.thisName) { + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + if (convertedLoopState.hoistedLocalVariables) { + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], true); - } - var containsYield = (node.statement.transformFlags & 16777216) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144; - } - var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 2097152)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; - if (currentState.argumentsName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.argumentsName = currentState.argumentsName; + if (state.argumentsName) { + if (outerState) { + outerState.argumentsName = state.argumentsName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, undefined, ts.createIdentifier("arguments"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { - if (outerConvertedLoopState) { - outerConvertedLoopState.thisName = currentState.thisName; + if (state.thisName) { + if (outerState) { + outerState.thisName = state.thisName; } else { - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, undefined, ts.createIdentifier("this"))); + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { - if (outerConvertedLoopState) { - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + if (state.hoistedLocalVariables) { + if (outerState) { + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, undefined, ts.createFalse())); + } if (extraVariableDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, undefined, p.outParamName); + } + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && hierarchyFacts & 4) + emitFlags |= 262144; + var statements = []; + statements.push(ts.createVariableStatement(undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2, 1, statements); + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, undefined, undefined, ts.visitNode(ts.createBlock(statements, true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - clone_3.statement = undefined; - clone_3 = ts.visitEachChild(clone_3, visitor, context); - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1, 1, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8; + if (containsYield && (hierarchyFacts & 4) !== 0) + emitFlags |= 262144; + var functionDeclaration = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, currentState.loopParameters, undefined, loopBody), emitFlags)) + ]), 2097152)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; var isSimpleLoop = !(state.nonLocalJumps & ~4) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0, statements); + copyOutParameters(state.loopOutParameters, 1, 0, statements); if (state.nonLocalJumps & 8) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8; + if (outerState) { + outerState.nonLocalJumps |= 8; returnStatement = ts.createReturn(loopResultName); } else { @@ -57422,8 +58872,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -57460,21 +58910,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304) { + flags |= 1; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -57569,7 +59027,7 @@ var ts; var ancestorFacts = enterSubtree(16286, 65); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 | 128) + var body = node.transformFlags & (16384 | 128) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156) { @@ -57650,7 +59108,7 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 524288 || + if (node.transformFlags & 131072 || node.expression.kind === 97 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -57658,7 +59116,7 @@ var ts; ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { @@ -57677,7 +59135,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { - if (node.transformFlags & 524288) { + if (node.transformFlags & 131072) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } @@ -57981,7 +59439,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -58167,10 +59625,10 @@ var ts; case 228: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 33554432)) { + else if (node.transformFlags & (512 | 8388608)) { return ts.visitEachChild(node, visitor, context); } else { @@ -58306,7 +59764,7 @@ var ts; return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 16777216) { + if (node.transformFlags & 4194304) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -58389,10 +59847,10 @@ var ts; else if (node.operatorToken.kind === 26) { return visitCommaExpression(node); } - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -58519,10 +59977,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -58987,7 +60445,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216) !== 0; + return !!node && (node.transformFlags & 4194304) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -59019,10 +60477,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -59726,7 +61184,10 @@ var ts; var needUMDDynamicImportHelper; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -59767,17 +61228,20 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createExpressionStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), - ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ - ts.createParameter(undefined, undefined, undefined, "require"), - ts.createParameter(undefined, undefined, undefined, "exports") - ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ + ts.createParameter(undefined, undefined, undefined, "require"), + ts.createParameter(undefined, undefined, undefined, "exports") + ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); ts.addEmitHelpers(updated, context.readEmitHelpers()); @@ -59925,7 +61389,7 @@ var ts; } } function moduleExpressionElementVisitor(node) { - if (!(node.transformFlags & 67108864) && !(node.transformFlags & 2048)) { + if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) { return node; } if (ts.isImportCall(node)) { @@ -59992,7 +61456,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384); + var containsLexicalThis = !!(node.transformFlags & 8192); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -60603,7 +62067,7 @@ var ts; var noSubstitution; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) { return node; } var id = ts.getOriginalNodeId(node); @@ -61224,7 +62688,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -61867,7 +63331,7 @@ var ts; function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 238) { - diagnosticMessage = node.parent.token === 108 ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -61900,11 +63364,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -61924,7 +63388,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -61942,6 +63406,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -61951,10 +63416,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -62018,15 +63483,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -62038,11 +63504,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], true, [], [], false, []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], true, [], [], false, []); return newFile; } needsDeclare = true; @@ -62055,6 +63522,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -62072,8 +63540,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -62084,11 +63553,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports([]), undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { if (emittedImports) { @@ -62117,20 +63589,23 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; var paths = ts.getOutputPathsFor(file, host, true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -62140,6 +63615,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71) { return name; @@ -62598,7 +64082,22 @@ var ts; return cleanup(ts.updateInterfaceDeclaration(input, undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); } case 237: { - return cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + var clean = cleanup(ts.updateFunctionDeclaration(input, undefined, ensureModifiers(input, isPrivate), undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, undefined); + return ts.createVariableStatement(undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242: { needsDeclare = false; @@ -62807,7 +64306,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -62821,7 +64320,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -62865,10 +64364,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235: case 152: case 151: + return !ts.hasModifier(node, 8); case 149: + case 235: return true; } return false; @@ -63875,19 +65375,23 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); - var isJs = ts.isSourceFileJavaScript(sourceFile); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -63906,7 +65410,7 @@ var ts; return ".json"; } if (options.jsx === 1) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { return ".jsx"; } @@ -63951,25 +65455,30 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, false); @@ -63987,11 +65496,11 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { nonJsFiles.forEach(collectLinkedAliases); @@ -64670,7 +66179,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -64682,7 +66191,7 @@ var ts; emitLiteral(node); } function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -65080,7 +66589,7 @@ var ts; function needsDotDotForPropertyAccess(expression) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23)); } @@ -65271,7 +66780,7 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -65935,13 +67444,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -65967,11 +67476,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -66126,7 +67640,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos - && !(ts.isArrowFunction(parentNode) && parentNode.type) + && ts.isArrowFunction(parentNode) + && !parentNode.type && !ts.some(parentNode.decorators) && !ts.some(parentNode.modifiers) && !ts.some(parentNode.typeParameters) @@ -66516,19 +68031,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } function pushNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { @@ -66683,7 +68198,7 @@ var ts; for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); - if (local && local.flags & (67216319 | 1048576 | 2097152)) { + if (local && local.flags & (67220415 | 1048576 | 2097152)) { return false; } } @@ -66748,7 +68263,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, true); } function generateNameForModuleOrEnum(node) { @@ -67189,15 +68704,20 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -67213,7 +68733,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -67223,7 +68743,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -67231,8 +68751,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); + var hash = system.createHash(data); + var mtimeBefore = system.getModifiedTime(fileName); if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); if (fingerprint && @@ -67242,8 +68762,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -67254,11 +68774,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -67270,36 +68790,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -67307,8 +68824,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -67333,7 +68850,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -67412,8 +68929,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); @@ -67428,11 +68945,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -67486,13 +69003,16 @@ var ts; } return resolutions; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; } @@ -67508,8 +69028,21 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -67519,16 +69052,12 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; function shouldProgramCreateNewSourceFiles(program, newOptions) { - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -67569,7 +69098,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json"]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; var _referencesArrayLiteralSyntax; @@ -67606,7 +69135,7 @@ var ts; var missingFilePaths; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { @@ -67618,11 +69147,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, false, false, undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -67698,7 +69228,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -67731,7 +69263,7 @@ var ts; if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } @@ -67761,13 +69293,13 @@ var ts; } var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } var unknownModuleNames; var result; @@ -67825,19 +69357,15 @@ var ts; ts.Debug.assert(j === resolutions.length); return result; function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -67863,30 +69391,30 @@ var ts; if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { return oldProgram.structureIsReused = 0; } - var oldRefs = oldProgram.getProjectReferences(); + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0; + } + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { return oldProgram.structureIsReused = 0; } } else { - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0; - } + ts.Debug.assert(!oldRefs); } var newSourceFiles = []; var filePaths = []; @@ -67900,7 +69428,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, undefined, shouldCreateNewSourceFile); if (!newSourceFile) { return oldProgram.structureIsReused = 0; @@ -67924,6 +69452,9 @@ var ts; fileChanged = newSourceFile !== oldSourceFile; } newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -67971,7 +69502,7 @@ var ts; modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -67986,7 +69517,7 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); if (resolutionsChanged) { @@ -68018,14 +69549,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { var path = toPath(f); if (getSourceFileByPath(path)) return true; @@ -68034,11 +69572,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -68048,11 +69587,12 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { - if (!resolvedRefOpts.options.outFile) + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -68104,7 +69644,7 @@ var ts; } if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -68158,9 +69698,9 @@ var ts; } } function getSyntacticDiagnosticsForFile(sourceFile) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68234,7 +69774,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -68447,7 +69987,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); var imports; var moduleAugmentations; @@ -68535,7 +70075,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -68589,11 +70129,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -68607,6 +70150,7 @@ var ts; return redirect; } function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames) { @@ -68659,7 +70203,7 @@ var ts; var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -68679,6 +70223,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); var existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -68706,22 +70251,22 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts") || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts") : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, false, undefined, file, ref.pos, ref.end); }); } @@ -68730,7 +70275,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -68806,7 +70351,7 @@ var ts; if (file.imports.length || file.moduleAugmentations.length) { var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -68815,7 +70360,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -68828,7 +70373,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -68847,34 +70392,26 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } return allFilesBelongToPath; } function parseProjectReferenceConfigFile(ref) { - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100); if (sourceFile === undefined) { @@ -68884,22 +70421,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -68939,9 +70470,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -68950,17 +70482,16 @@ var ts; } } } - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -69009,15 +70540,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -69042,7 +70573,7 @@ var ts; var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -69055,8 +70586,8 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } if (options.outDir || @@ -69067,15 +70598,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -69256,7 +70787,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts")) { var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts")) || !!getSourceFileByPath((filePathWithoutExtension + ".tsx")); @@ -69271,7 +70802,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -69279,13 +70813,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { @@ -69342,13 +70877,16 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } function getReferencedFileFromImportLiteral(checker, importName) { var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } function getReferencedFiles(program, sourceFile, getCanonicalFileName) { var referencedFiles; if (sourceFile.imports && sourceFile.imports.length > 0) { @@ -69365,7 +70903,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -69375,11 +70913,41 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + addReferenceFromAmbientModule(symbol); + } + } + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -69769,7 +71337,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -69782,7 +71350,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -69908,16 +71483,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { getProgram: function () { return program; }, getState: ts.notImplemented, @@ -70046,7 +71621,7 @@ var ts; return primaryResult; } var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; @@ -70166,7 +71741,7 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -70458,87 +72033,100 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 : importModuleSpecifierPreference === "non-relative" ? 1 : 2, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0; + case "index": return 1; + case "js": return 2; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 : 0; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 : 1, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 : 0, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2) + ts.Debug.assertNever(relativePreference); + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js") : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -70596,16 +72184,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -70623,7 +72201,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -70643,39 +72222,43 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -70687,6 +72270,8 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; @@ -70744,13 +72329,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json")) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0: + return ts.removeSuffix(noExtension, "/index"); + case 1: + return noExtension; + case 2: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts": + case ".d.ts": + return ".js"; + case ".tsx": + return options.jsx === 1 ? ".jsx" : ".js"; + case ".js": + case ".jsx": + case ".json": + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -70785,16 +72393,12 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -70836,7 +72440,7 @@ var ts; return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); @@ -70848,7 +72452,7 @@ var ts; reportSemanticDiagnostics = true; } } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -70879,6 +72483,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } if (!createProgram) { @@ -70888,7 +72511,7 @@ var ts; host; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -70902,17 +72525,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -70952,18 +72568,19 @@ var ts; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -70986,9 +72603,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -71056,7 +72674,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -71089,9 +72708,9 @@ var ts; } } var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(undefined, undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -71115,7 +72734,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { @@ -71275,12 +72894,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -71304,7 +72918,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -71395,7 +73011,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -71407,87 +73024,61 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - function createFileMap() { + function createFileMap(toPath) { var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts"); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json") ? ".json" : @@ -71499,7 +73090,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json")) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -71510,13 +73105,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts"); + var dts = ts.changeExtension(out, ".d.ts"); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -71527,748 +73126,746 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts"); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); + }; + } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + var unchangedOutputs = createFileMap(toPath); + var projectStatus = createFileMap(toPath); var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects - }; - } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - addProject(arg); - } - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } - } - ts.performBuild = performBuild; - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1)); - }); - } - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + watchWildCardDirectories(resolved, cfg); + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + if (!ts.fileExtensionIs(fileName, ".d.ts") && + (ts.fileExtensionIs(fileName, ".ts") || ts.fileExtensionIs(fileName, ".tsx"))) { + return false; + } + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts"))) { + return true; + } + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + function getFilesToClean() { + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); if (defaultOptions.dry) { - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } - function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } + function reportBuildQueue(graph) { + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json")) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -72303,6 +73900,7 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: + case UpToDateStatusType.ComputingUpstream: break; default: ts.assertType(status); @@ -72310,6 +73908,131 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +var ts; +(function (ts) { + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; + } + function anyValue(name, comment) { + return { kind: 0, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.release.js.map var ts; (function (ts) { @@ -72330,7 +74053,7 @@ var ts; return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); } function shouldBePretty(options) { - if (typeof options.pretty === "undefined") { + if (!options || typeof options.pretty === "undefined") { return defaultIsPretty(); } return options.pretty; @@ -72354,28 +74077,10 @@ var ts; ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } function executeCommandLine(args) { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - var reportDiag_1 = ts.createDiagnosticReporter(ts.sys, defaultIsPretty()); - var report = function (message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - return reportDiag_1(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); - }; - var buildHost = { - error: report, - verbose: report, - message: report, - errorDiagnostic: function (d) { return reportDiag_1(d); } - }; - var result = ts.performBuild(args.slice(1), ts.createCompilerHost({}), buildHost, ts.sys); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return ts.sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } var commandLine = ts.parseCommandLine(args); @@ -72467,6 +74172,42 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } + function performBuild(args) { + var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.help) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + // Update to pretty if host supports it + updateReportDiagnostic(); + if (projects.length === 0) { + ts.printVersion(); + ts.printHelp(ts.buildOpts, "--build "); + return ts.sys.exit(ts.ExitStatus.Success); + } + if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + if (buildOptions.watch) { + reportWatchModeWithoutSysSupport(); + } + // TODO: change this to host if watch => watchHost otherwiue without wathc + var builder = ts.createSolutionBuilder(ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); + if (buildOptions.clean) { + return ts.sys.exit(builder.cleanAllProjects()); + } + if (buildOptions.watch) { + builder.buildAllProjects(); + return builder.startWatching(); + } + return ts.sys.exit(builder.buildAllProjects()); + } function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { var host = ts.createCompilerHost(options); enableStatistics(options); @@ -72484,12 +74225,12 @@ var ts; } function updateWatchCompilationHost(watchCompilerHost) { var compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 64e13776da3..ac46ae0c134 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1456,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1961,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2059,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2628,6 +3005,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3056,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2747,38 +3127,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3233,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -3006,9 +3387,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3407,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3659,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3692,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3578,20 +3953,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4505,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5121,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5160,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5407,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5434,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5533,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5647,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5743,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5841,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5880,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5947,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,10 +6076,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5700,136 +6093,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6407,6 +6749,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6779,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6833,9 +7177,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6891,6 +7235,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7274,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7349,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7491,7 +7859,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,6 +7936,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +7959,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8040,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8147,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8377,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8417,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8792,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8481,6 +8856,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9148,18 +9524,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9575,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9605,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9625,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9653,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9667,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9701,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9745,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9760,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9791,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9800,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9910,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +9952,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10146,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10176,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10264,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10273,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10613,7 +11007,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11021,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11142,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11158,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11048,13 +11442,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11076,15 +11475,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11120,10 +11510,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11652,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11764,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +11941,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +11954,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12207,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12534,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12552,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12560,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12592,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12638,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12666,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12809,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14168,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14561,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14589,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14602,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14882,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15103,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15170,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15397,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15575,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15753,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15857,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15928,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16287,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16456,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16612,7 +17129,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17380,8 +17905,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20004,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20879,7 +21407,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -21004,13 +21532,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21546,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21096,7 +21619,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21277,10 +21800,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21815,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21910,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21925,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +21986,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22026,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22064,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22090,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22412,8 +22931,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22945,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23028,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23042,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23062,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23075,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23083,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23101,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23211,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23220,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23229,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23255,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23264,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23298,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23311,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23319,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23329,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23345,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23357,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23368,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23453,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23517,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23537,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23583,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23591,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23619,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23647,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23738,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23788,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23808,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23816,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23852,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23895,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23920,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23632,7 +24262,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23939,7 +24573,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24591,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +24642,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24661,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +24674,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +24786,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24832,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24840,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25054,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25079,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25097,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25123,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25134,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25332,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25354,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25363,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25494,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25515,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25541,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25561,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,14 +25607,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25099,15 +25841,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25887,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25906,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25917,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25982,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25991,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26005,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26022,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26053,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26094,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26147,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26166,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26204,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26216,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26285,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26415,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26428,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26473,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26505,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26722,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26777,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26857,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26936,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26334,6 +27104,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26432,6 +27203,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26834,7 +27607,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27230,7 +28002,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28022,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28110,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28129,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28354,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28401,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28418,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28499,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28523,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28534,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,37 +28617,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27914,7 +28681,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28711,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28768,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28789,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28815,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28856,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28869,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28953,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28969,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28989,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29007,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29048,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29060,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29086,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29124,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28395,6 +29162,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28470,40 +29240,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28524,7 +29294,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29305,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28588,35 +29358,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28634,7 +29404,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29415,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29427,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29437,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29457,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29468,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29482,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +29494,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +29509,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +29522,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +29541,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +29557,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +29573,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +29590,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +29619,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +29640,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +29651,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +29675,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +29686,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,24 +29695,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -29012,7 +29786,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29059,8 +29833,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,58 +29843,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29128,8 +29902,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29140,22 +29914,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29177,27 +29951,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29216,12 +29990,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29230,9 +30004,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29447,6 +30221,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30253,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,6 +30263,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29683,8 +30471,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30540,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30571,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29817,6 +30619,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +30631,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +30651,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +30663,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29946,6 +30751,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30795,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30932,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30993,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +31006,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30219,53 +31029,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30373,8 +31184,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31328,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,15 +31337,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30612,7 +31431,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31441,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31471,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31491,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30743,7 +31565,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +31574,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31629,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31732,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31753,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +31789,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +31806,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31878,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31932,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +31988,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32022,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32041,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32056,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32090,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,11 +32139,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,11 +32152,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32172,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32207,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32223,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32245,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32281,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32300,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32332,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32340,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32352,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31750,7 +32596,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32696,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32746,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32814,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32856,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32974,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32984,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32148,6 +33007,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32230,7 +33092,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32275,13 +33142,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33168,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,17 +33235,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32448,23 +33318,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33416,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33456,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33469,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33567,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33701,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33712,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33753,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,12 +33765,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -33009,7 +33887,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33902,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33116,6 +34001,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33174,7 +34062,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34246,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34270,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34319,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34329,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33603,27 +34495,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +34523,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33683,7 +34575,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34606,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34641,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34664,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34673,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34683,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33796,15 +34694,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34719,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34733,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +34760,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33889,8 +34783,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34792,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +34806,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -34005,9 +34899,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34050,19 +34944,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34977,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +35038,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35066,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34195,7 +35094,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35122,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35131,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35160,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35169,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,23 +35335,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34531,7 +35419,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34542,8 +35432,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35532,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35671,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35899,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35919,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36173,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35420,7 +36310,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +36333,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35497,6 +36387,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35608,7 +36499,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35778,10 +36669,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36694,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36774,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36782,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36815,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36831,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36841,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36890,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36911,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36029,10 +36949,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36123,8 +37043,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36205,7 +37129,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37229,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37242,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37279,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37310,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37397,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36514,6 +37438,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36550,7 +37475,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37494,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37540,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,10 +37734,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +37767,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37822,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37851,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +37860,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37042,16 +37990,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37100,10 +38048,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38079,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,7 +38108,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37278,6 +38229,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37346,10 +38305,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38320,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38365,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38393,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38490,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38499,8 @@ var 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, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38754,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,20 +38767,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37882,7 +38829,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38847,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38858,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38871,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38909,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38937,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39136,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39166,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39180,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39322,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39333,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39539,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39640,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39650,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39709,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39730,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38832,6 +39781,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38871,49 +39826,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39958,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39035,8 +40006,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40034,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40134,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40151,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40165,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40208,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40241,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40297,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40328,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40354,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40384,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40554,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40692,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40751,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40853,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40863,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39862,8 +40879,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39901,13 +40918,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40956,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,32 +40984,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40153,6 +41166,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41225,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41261,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41333,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41386,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41428,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41562,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41593,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41786,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42120,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41096,9 +42173,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41120,10 +42202,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42230,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42252,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42266,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41421,8 +42508,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41445,44 +42536,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41658,7 +42754,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41744,11 +42842,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41797,6 +42897,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42935,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +43046,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43087,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43131,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43155,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43173,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43186,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43199,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43228,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43257,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42251,14 +43413,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42302,6 +43480,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43500,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43516,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43554,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42403,7 +43602,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42489,10 +43688,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43737,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42562,6 +43778,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42580,8 +43799,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43880,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43961,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +44065,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +44078,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +44109,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42918,15 +44146,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44419,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44445,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44465,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43236,7 +44553,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +44570,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43392,8 +44699,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,7 +44708,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43449,7 +44756,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43493,8 +44800,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43508,8 +44815,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,7 +44829,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43600,6 +44907,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43624,22 +44934,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43781,31 +45111,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +45148,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43911,16 +45266,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,19 +45289,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44052,7 +45410,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45467,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44176,9 +45534,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +45595,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45616,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45639,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45659,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44312,6 +45716,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +45725,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +45744,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44408,47 +45810,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // 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) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44488,6 +45879,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44513,7 +45906,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45925,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45939,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +46011,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +46121,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46158,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46180,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46189,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44802,35 +46201,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44920,9 +46331,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46351,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46561,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46585,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46593,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46602,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45204,14 +46617,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46643,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46676,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46724,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46734,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46801,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46825,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +47047,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +47163,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47284,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47332,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47487,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47606,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47711,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47777,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47785,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47906,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47930,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47941,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47976,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47985,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +48043,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +48084,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +48095,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48166,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48200,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48221,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48310,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48319,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48333,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48384,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48467,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48497,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +48590,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +48601,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +48640,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47490,11 +48713,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +48729,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48818,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48894,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +48922,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47729,8 +48962,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47758,7 +48991,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,34 +49070,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +49114,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49171,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49182,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49192,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49219,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49278,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49403,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49416,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +49440,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +49447,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48320,6 +49543,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48437,10 +49670,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49774,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48560,6 +49844,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,8 +49854,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48611,7 +49898,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48816,8 +50102,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48977,7 +50263,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -49003,8 +50289,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49118,7 +50404,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50542,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50559,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50620,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50630,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50736,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,19 +50778,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49535,11 +50817,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50868,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50894,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50911,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50936,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50967,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +51060,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +51089,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51555,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51586,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50400,8 +51687,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50640,6 +51927,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51991,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +52020,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52253,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52276,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52333,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51304,8 +52591,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +52602,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +53088,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +53171,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53211,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53227,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52314,13 +53601,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +53638,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52890,7 +54183,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52901,7 +54197,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52944,7 +54240,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +54259,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53127,6 +54423,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54914,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54926,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54979,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +55040,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +55077,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55109,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +55157,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55324,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,13 +55395,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54157,9 +55462,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +55474,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54273,7 +55576,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55661,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55691,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55717,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55729,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55755,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55774,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55788,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55805,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55884,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55900,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55910,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +55918,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54732,13 +56031,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54799,13 +56117,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +56172,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +56185,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,7 +56205,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54963,7 +56281,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56294,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56339,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56402,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56506,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56521,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56577,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55279,7 +56620,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55293,9 +56639,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56730,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +56777,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +56806,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +56841,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57215,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57418,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57464,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57684,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57783,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57948,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57983,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61560,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61588,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62824,8 +64213,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +64280,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63831,7 +65220,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +65268,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65795,7 +67186,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65917,7 +67308,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66057,6 +67448,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66090,6 +67489,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66331,23 +67740,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +67784,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66400,6 +67821,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66422,6 +67845,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66450,13 +67881,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66481,18 +67912,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66520,12 +67995,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +68023,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66616,6 +68097,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66680,7 +68171,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* 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}); @@ -66712,7 +68203,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66727,7 +68218,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +68235,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +68332,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +68429,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +68483,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67009,6 +68512,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67031,6 +68536,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67059,13 +68572,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67090,13 +68603,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67754,6 +69267,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67934,7 +69452,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68532,7 +70050,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68603,7 +70121,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68732,7 +70250,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68920,7 +70438,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69210,19 +70728,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +70796,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69526,7 +71052,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69557,7 +71083,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69583,7 +71125,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,7 +71141,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69616,165 +71220,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,24 +71497,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69812,8 +71527,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +71568,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -70007,7 +71730,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70186,7 +71909,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70194,7 +71917,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70241,7 +71964,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70723,7 +72446,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71148,10 +72871,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71354,7 +73077,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71478,10 +73201,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71742,10 +73465,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72412,7 +74135,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +74167,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73529,7 +75252,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +75309,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +75340,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73862,7 +75591,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73929,7 +75658,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74894,7 +76623,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75979,7 +77708,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76786,7 +78515,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76821,11 +78550,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78580,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78598,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78608,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78680,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,11 +78701,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76987,6 +78719,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78738,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78751,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +78788,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +78796,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78817,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +79342,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77817,7 +79583,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,7 +79597,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77878,10 +79644,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79113,20 +80880,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +80921,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79198,26 +80970,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79242,12 +81019,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81753,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81775,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +82200,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +82411,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +83116,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +83148,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +83322,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83744,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83935,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84014,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +84528,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84561,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84571,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84579,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84591,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84603,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84619,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84653,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84680,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84768,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84784,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84846,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84855,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84879,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84906,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83162,7 +84967,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83209,7 +85014,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +85026,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +85118,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +85154,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +85199,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +85290,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +85302,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +85333,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +85354,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +85385,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +85412,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +85482,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +85498,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85534,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85559,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85574,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85637,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85703,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85794,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +86023,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84309,7 +86131,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +86187,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +86209,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,7 +86275,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84470,6 +86296,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +86326,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +86355,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +86442,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +86451,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +86471,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +86491,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +86511,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +86522,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86571,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86584,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86643,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,7 +86678,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +86691,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86708,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86907,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86924,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86935,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +87012,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +87022,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +87051,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +87062,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85765,7 +87620,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87633,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87814,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87972,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86248,7 +88110,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86588,121 +88451,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88625,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88642,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88663,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +88695,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +88721,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +88791,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88859,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88867,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88917,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88933,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88967,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88998,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +89012,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +89064,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +89099,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87286,7 +89173,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +89212,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +89239,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87532,12 +89420,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +89446,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87650,6 +89535,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +89557,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89575,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89646,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89661,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +89682,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +90531,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +90541,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -88735,6 +90752,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -88950,8 +90991,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89008,7 +91050,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89130,6 +91172,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89260,7 +91309,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89624,7 +91673,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -89642,8 +91691,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { // candidate should be in this node @@ -89651,15 +91700,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -89881,7 +91928,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -89995,7 +92042,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90003,7 +92050,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90145,6 +92192,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90514,7 +92568,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90522,11 +92576,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -91671,9 +93725,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_1 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_1(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -91687,27 +93774,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_1 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_1(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -91722,8 +93797,8 @@ var ts; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; _loop_2(moduleName); } } @@ -91833,7 +93908,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -91866,7 +93941,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -91890,6 +93965,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -91997,11 +94084,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92017,7 +94105,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92102,7 +94190,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92110,22 +94198,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92137,14 +94226,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92209,6 +94298,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92294,11 +94386,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92306,16 +94399,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92328,11 +94426,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92346,7 +94444,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92373,6 +94471,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -92781,7 +94884,10 @@ var ts; break; case 71 /* Identifier */: // For `

` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -92803,6 +94909,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -92811,6 +94918,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -92948,7 +95056,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -92963,9 +95071,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93002,7 +95108,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93030,12 +95136,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93054,7 +95160,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93075,7 +95181,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93105,7 +95211,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93129,6 +95235,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93364,7 +95477,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93398,14 +95512,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93559,10 +95678,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93574,6 +95690,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93594,7 +95712,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93609,6 +95726,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -93782,17 +95901,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -93815,7 +95936,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -93887,7 +96008,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -93907,14 +96028,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94379,9 +96500,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94426,7 +96544,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94440,7 +96558,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94507,6 +96625,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -94943,7 +97064,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95088,8 +97209,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95136,10 +97274,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95152,28 +97290,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_1 = def.node; return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_2 = def.node; var name_2 = ts.tokenToString(node_2.kind); return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_3 = def.node; var symbol = checker.getSymbolAtLocation(node_3); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_4 = def.node; return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95191,24 +97329,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95240,17 +97415,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95266,7 +97441,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95330,11 +97560,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95348,7 +97578,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95356,7 +97586,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95394,7 +97624,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95525,15 +97755,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -95636,19 +97866,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -95678,7 +97895,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -95801,7 +98018,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -95828,7 +98045,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -95998,12 +98215,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96233,7 +98451,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96291,8 +98509,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96300,39 +98519,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96344,8 +98549,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96358,11 +98581,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96370,19 +98595,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96471,14 +98696,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96574,7 +98799,7 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); var _loop_3 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); @@ -96602,7 +98827,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; @@ -96632,16 +98857,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -96655,7 +98887,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -96697,7 +98929,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -96963,6 +99195,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97173,7 +99415,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97206,7 +99448,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97269,7 +99511,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97329,7 +99571,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97721,7 +99963,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98047,28 +100289,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99425,9 +101688,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99436,28 +101699,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99508,22 +101785,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99532,17 +101819,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99559,12 +101850,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99581,9 +101872,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -99869,7 +102160,7 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { var _loop_6 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. @@ -99879,7 +102170,7 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { var state_2 = _loop_6(n); if (typeof state_2 === "object") return state_2.value; @@ -99895,10 +102186,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -99909,11 +102203,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -99967,7 +102278,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100091,13 +102402,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100120,7 +102431,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_1 = decl.symbol; if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { @@ -100164,13 +102475,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100195,10 +102506,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100208,7 +102519,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100227,22 +102538,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100375,13 +102709,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100519,7 +102856,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -100749,7 +103086,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -100821,7 +103158,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -100888,6 +103226,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -102613,13 +104952,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -103787,11 +106126,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -103806,7 +106145,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -103821,11 +106168,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -103844,6 +106213,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -103887,30 +106275,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -103933,7 +106328,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104058,7 +106453,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104090,7 +106485,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104098,22 +106493,22 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; @@ -104172,9 +106567,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104200,14 +106602,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104245,9 +106651,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105030,7 +107437,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105083,53 +107490,59 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } var _loop_10 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; @@ -105180,7 +107593,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105194,6 +107607,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105207,19 +107621,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105227,6 +107647,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105249,9 +107670,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105261,23 +107680,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105286,7 +107714,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105301,17 +107730,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105327,6 +107757,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105338,14 +107773,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105354,50 +107786,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105405,49 +107854,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_1 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105468,12 +107934,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105481,20 +107941,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105572,7 +108030,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -105689,7 +108147,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106175,33 +108633,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106262,24 +108727,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106321,7 +108786,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106369,17 +108834,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106389,7 +108850,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106397,11 +108873,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -106640,10 +109116,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -106682,7 +109158,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -106782,7 +109258,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -106792,7 +109268,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -106912,7 +109388,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -106922,24 +109400,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -107676,7 +110264,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -107808,22 +110396,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -107833,7 +110418,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -107931,38 +110516,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -107971,14 +110553,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -107991,30 +110581,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108022,9 +110612,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108038,36 +110628,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108078,13 +110694,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108135,9 +110759,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108150,10 +110776,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108381,16 +111011,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_1 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_1.set(name, symbol); }); } @@ -108406,17 +111038,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -108636,7 +111268,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -108662,6 +111294,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109757,7 +112589,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -109973,7 +112805,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110307,7 +113139,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110677,7 +113509,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -110809,7 +113641,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111401,7 +114233,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112154,7 +114986,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112496,8 +115328,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112534,6 +115367,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112555,7 +115392,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -112670,7 +115507,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -112793,27 +115630,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113020,19 +115855,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -114826,6 +117673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -114870,8 +117718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -114946,7 +117794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -115031,7 +117879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -115160,71 +118008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var __assign = (this && this.__assign) || function () { @@ -115251,6 +118034,15 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { var server; @@ -115453,12 +118245,13 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } + var indentStr = "\n "; function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115699,7 +118492,7 @@ var ts; var text; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -115983,6 +118776,7 @@ var ts; server.nullTypingsInstaller = { isKnownTypesPackageName: ts.returnFalse, installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116042,6 +118836,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116159,6 +118956,7 @@ var ts; this.lastReportedVersion = 0; this.projectProgramVersion = 0; this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; this.dirty = false; this.hasChangedAutomaticTypeDirectiveNames = false; this.typingFiles = server.emptyArray; @@ -116219,6 +119017,9 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116299,6 +119100,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); @@ -116458,7 +119262,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_1 = projectReferences; _b < projectReferences_1.length; _b++) { var ref = projectReferences_1[_b]; @@ -116520,7 +119324,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116812,7 +119616,9 @@ var ts; } }; Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -116860,9 +119666,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -116945,7 +119750,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117017,27 +119822,36 @@ var ts; server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { return this.directoryStructureHost; @@ -117053,11 +119867,13 @@ var ts; }; ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117074,7 +119890,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; ConfiguredProject.prototype.getGlobalProjectErrors = function () { return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray; @@ -117131,16 +119947,14 @@ var ts; } return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117154,6 +119968,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117179,6 +119999,9 @@ var ts; server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; server.maxFileSize = 4 * 1024 * 1024; server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117266,6 +120089,11 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117308,6 +120136,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117325,14 +120154,23 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = (function () { function ProjectService(opts) { var _this = this; this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); this.filenameToScriptInfoVersion = ts.createMap(); this.allJsFilesForOpenFileTelemetry = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); @@ -117345,9 +120183,10 @@ var ts; this.projectToSizeMap = ts.createMap(); this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117360,7 +120199,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117440,14 +120279,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117507,6 +120346,12 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117517,6 +120362,28 @@ var ts; }; this.eventHandler(event); }; + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -117673,6 +120540,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files"); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true); } @@ -118011,33 +120879,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { return; @@ -118049,12 +120890,12 @@ var ts; for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { var f = fileNames_1[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); return fileName; } } @@ -118065,9 +120906,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118077,21 +120918,35 @@ var ts; var compilerOptions = convertCompilerOptions(options); var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118110,8 +120965,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118122,31 +120976,76 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118194,40 +121093,28 @@ var ts; } project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) { var configFileSpecs = project.configFileSpecs; var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { var host = project.getCachedDirectoryStructureHost(); host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118354,10 +121241,77 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info"); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1, "node_modules for closed script infos in them"); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118416,6 +121370,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118433,7 +121388,17 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118447,16 +121412,16 @@ var ts; }; ProjectService.prototype.reloadProjects = function () { this.logger.info("reload projects."); - this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : - ts.returnTrue); + ts.returnTrue, "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); openFiles.forEach(function (openFileValue, path) { @@ -118467,18 +121432,15 @@ var ts; ts.Debug.assert(info.isScriptOpen()); var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -118527,7 +121489,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); addOriginalConfiguredProject(configuredProject); var originalScriptInfo = this.getScriptInfo(fileName); @@ -118567,7 +121530,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); if (info.isOrphan()) { configFileName = undefined; } @@ -118825,11 +121788,11 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_3.legacySafelist[cleanedTypingName]) { + var typeName = this_3.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); exclude = true; - var typeName = this_3.legacySafelist[cleanedTypingName]; if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); } @@ -118895,7 +121858,8 @@ var ts; else { externalProject.enableLanguageService(); } - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } this.closeExternalProject(proj.projectFileName); @@ -118935,7 +121899,9 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - project = this.createConfiguredProject(tsconfigFile); + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { project.addExternalProjectReference(); @@ -118944,7 +121910,8 @@ var ts; } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119137,7 +122104,7 @@ var ts; }; } server.toEvent = toEvent; - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119145,9 +122112,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119190,17 +122155,19 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; var _loop_8 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } @@ -119261,7 +122228,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119277,7 +122244,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119632,6 +122599,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -119646,21 +122614,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingStartEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -119687,10 +122667,13 @@ var ts; } this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -119698,6 +122681,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -120136,21 +123130,28 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_1 = map.get(fileName); if (!group_1) map.set(fileName, group_1 = { file: fileName, locs: [] }); - group_1.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120368,7 +123369,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full") @@ -120708,8 +123709,8 @@ var ts; var commands = args.command; for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -120864,8 +123865,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -120888,7 +123891,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack); } }; @@ -121840,13 +124843,18 @@ var ts; }; NodeTypingsInstaller.prototype.installPackage = function (options) { var _this = this; - var rq = __assign({ kind: "installPackage" }, options); - this.send(rq); + this.send(__assign({ kind: "installPackage" }, options)); ts.Debug.assert(this.packageInstalledPromise === undefined); return new Promise(function (resolve, reject) { _this.packageInstalledPromise = { resolve: resolve, reject: reject }; }); }; + NodeTypingsInstaller.prototype.inspectValue = function (options) { + var _this = this; + this.send({ kind: "inspectValue", options: options }); + ts.Debug.assert(this.inspectValuePromise === undefined); + return new Promise(function (resolve) { _this.inspectValuePromise = { resolve: resolve }; }); + }; NodeTypingsInstaller.prototype.attach = function (projectService) { var _this = this; this.projectService = projectService; @@ -121945,6 +124953,10 @@ var ts; this.event(response, "setTypings"); break; } + case server.ActionValueInspected: + this.inspectValuePromise.resolve(response.result); + this.inspectValuePromise = undefined; + break; case server.EventInitializationFailed: { var body = { @@ -122071,6 +125083,7 @@ var ts; globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, + typesMapLocation: typesMapLocation, }) || this; _this.eventPort = eventPort; if (_this.canUseEvents && _this.eventPort) { @@ -122190,13 +125203,16 @@ var ts; var cmdLineLogFileName = server.findArgument("--logFile"); var cmdLineVerbosity = getLogLevel(server.findArgument("--logVerbosity")); var envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG); - var logFileName = cmdLineLogFileName + var unsubstitutedLogFileName = cmdLineLogFileName ? ts.stripQuotes(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || (__dirname + "/.log" + process.pid.toString()) : undefined; + var substitutedLogFileName = unsubstitutedLogFileName + ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) + : undefined; var logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel; - return new Logger(logFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 + return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity); // TODO: GH#18217 } // This places log file in the directory containing editorServices.js // TODO: check that this location is writable @@ -122414,7 +125430,7 @@ var ts; } sys.require = function (initialDir, moduleName) { try { - return { module: require(ts.resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(ts.resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error: error }; @@ -122442,7 +125458,7 @@ var ts; } ts.setStackTraceLimit(); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); // TODO: GH#18217 - var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); + var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation) || ts.combinePaths(ts.getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); var npmLocation = server.findArgument(server.Arguments.NpmLocation); function parseStringArray(argName) { var arg = server.findArgument(argName); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index a16288c6c27..d8306559986 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5751,24 +5609,6 @@ declare namespace ts.server { remove(path: NormalizedPath): void; } function createNormalizedPathMap(): NormalizedPathMap; - interface ProjectOptions { - configHasExtendsProperty: boolean; - /** - * true if config file explicitly listed files - */ - configHasFilesProperty: boolean; - configHasIncludeProperty: boolean; - configHasExcludeProperty: boolean; - projectReferences: ReadonlyArray | undefined; - /** - * these fields can be present in the project file - */ - files?: string[]; - wildcardDirectories?: Map; - compilerOptions?: CompilerOptions; - typeAcquisition?: TypeAcquisition; - compileOnSave?: boolean; - } function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; function createSortedArray(): SortedArray; @@ -6602,15 +6442,17 @@ declare namespace ts.server.protocol { /** * Information about the item to be renamed. */ - interface RenameInfo { + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { /** * True if item can be renamed. */ - canRename: boolean; + canRename: true; /** - * Error message if item can not be renamed. + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ - localizedErrorMessage?: string; + fileToRename?: string; /** * Display name of the item to be renamed. */ @@ -6627,6 +6469,15 @@ declare namespace ts.server.protocol { * Optional modifiers for the kind (such as 'public'). */ kindModifiers: string; + /** Span of text to rename. */ + triggerSpan: TextSpan; + } + interface RenameInfoFailure { + canRename: false; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage: string; } /** * A group of text spans, all in 'file'. @@ -6635,7 +6486,11 @@ declare namespace ts.server.protocol { /** The file to which the spans apply */ file: string; /** The text spans in this group */ - locs: TextSpan[]; + locs: RenameTextSpan[]; + } + interface RenameTextSpan extends TextSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface RenameResponseBody { /** @@ -7148,7 +7003,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions; + command: CommandTypes.Completions | CommandTypes.CompletionInfo; arguments: CompletionsRequestArgs; } /** @@ -7660,6 +7515,35 @@ declare namespace ts.server.protocol { */ openFiles: string[]; } + type ProjectLoadingStartEventName = "projectLoadingStart"; + interface ProjectLoadingStartEvent extends Event { + event: ProjectLoadingStartEventName; + body: ProjectLoadingStartEventBody; + } + interface ProjectLoadingStartEventBody { + /** name of the project */ + projectName: string; + /** reason for loading */ + reason: string; + } + type ProjectLoadingFinishEventName = "projectLoadingFinish"; + interface ProjectLoadingFinishEvent extends Event { + event: ProjectLoadingFinishEventName; + body: ProjectLoadingFinishEventBody; + } + interface ProjectLoadingFinishEventBody { + /** name of the project */ + projectName: string; + } + type SurveyReadyEventName = "surveyReady"; + interface SurveyReadyEvent extends Event { + event: SurveyReadyEventName; + body: SurveyReadyEventBody; + } + interface SurveyReadyEventBody { + /** Name of the survey. This is an internal machine- and programmer-friendly name */ + surveyId: string; + } type LargeFileReferencedEventName = "largeFileReferenced"; interface LargeFileReferencedEvent extends Event { event: LargeFileReferencedEventName; @@ -7995,6 +7879,7 @@ declare namespace ts.server.protocol { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; + readonly lazyConfiguredProjectsFromExternalProject?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -8126,14 +8011,14 @@ declare namespace ts.server { getSnapshot(): IScriptSnapshot; private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): UserPreferences | undefined; + getPreferences(): protocol.UserPreferences | undefined; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: UserPreferences | undefined): void; + setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; getLatestVersion(): string; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): boolean; @@ -8238,6 +8123,7 @@ declare namespace ts.server { * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ private projectStateVersion; + protected isInitialLoadPending: () => boolean; private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; @@ -8261,6 +8147,7 @@ declare namespace ts.server { useCaseSensitiveFileNames(): boolean; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; readFile(fileName: string): string | undefined; + writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; @@ -8322,7 +8209,7 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(): void; + protected enableGlobalPlugins(options: CompilerOptions): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; @@ -8351,14 +8238,14 @@ declare namespace ts.server { * Otherwise it will create an InferredProject. */ class ConfiguredProject extends Project { - compileOnSaveEnabled: boolean; - private projectReferences; private typeAcquisition; private directoriesWatchedForWildcards; readonly canonicalConfigFilePath: NormalizedPath; /** Ref count to the project when opened from external project */ private externalProjectRefCount; private projectErrors; + private projectReferences; + protected isInitialLoadPending: () => boolean; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph * @returns: true if set of files in the project stays the same and false - otherwise. @@ -8391,6 +8278,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; + updateGraph(): boolean; getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -8399,6 +8287,9 @@ declare namespace ts.server { declare namespace ts.server { const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + const ProjectLoadingStartEvent = "projectLoadingStart"; + const ProjectLoadingFinishEvent = "projectLoadingFinish"; + const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -8410,6 +8301,25 @@ declare namespace ts.server { openFiles: string[]; }; } + interface ProjectLoadingStartEvent { + eventName: typeof ProjectLoadingStartEvent; + data: { + project: Project; + reason: string; + }; + } + interface ProjectLoadingFinishEvent { + eventName: typeof ProjectLoadingFinishEvent; + data: { + project: Project; + }; + } + interface SurveyReady { + eventName: typeof SurveyReady; + data: { + surveyId: string; + }; + } interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { @@ -8488,7 +8398,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8509,7 +8419,7 @@ declare namespace ts.server { function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; - preferences: UserPreferences; + preferences: protocol.UserPreferences; hostInfo: string; extraFileExtensions?: FileExtensionInfo[]; } @@ -8538,6 +8448,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8586,7 +8497,7 @@ declare namespace ts.server { private readonly throttledOperations; private readonly hostConfiguration; private safelist; - private legacySafelist; + private readonly legacySafelist; private pendingProjectUpdates; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; @@ -8607,6 +8518,8 @@ declare namespace ts.server { readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; + /** Tracks projects that we have already sent survey events for. */ + private readonly seenSurveyProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; @@ -8628,9 +8541,9 @@ declare namespace ts.server { */ private ensureProjectStructuresUptoDate; getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): UserPreferences; + getPreferences(file: NormalizedPath): protocol.UserPreferences; getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): UserPreferences; + getHostPreferences(): protocol.UserPreferences; private onSourceFileChanged; private handleDeletedFile; private onConfigChangedForConfiguredProject; @@ -8692,15 +8605,13 @@ declare namespace ts.server { private findConfiguredProjectByProjectName; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; - private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ private getFilenameForExceededTotalSizeLimitForNonTsFiles; private createExternalProject; - private sendProjectTelemetry; - private addFilesToNonInferredProjectAndUpdateGraph; + private addFilesToNonInferredProject; private createConfiguredProject; private updateNonInferredProjectFiles; - private updateNonInferredProject; + private updateRootAndOptionsOfNonInferredProject; private sendConfigFileDiagEvent; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; @@ -8708,6 +8619,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; @@ -8815,6 +8730,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8837,6 +8753,7 @@ declare namespace ts.server { private defaultEventHandler; private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; + private logErrorWorker; send(msg: protocol.Message): void; event(body: T, eventName: string): void; /** @deprecated */ @@ -8881,7 +8798,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index eea96a6f7fb..53d751f50a5 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -62,18 +62,27 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +97,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +726,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +787,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1164,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1284,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1452,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1957,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2055,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +3001,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3052,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3123,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3229,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3383,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3403,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3655,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3688,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3949,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4166,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4501,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5117,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5156,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5403,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5430,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5529,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5643,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5739,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5837,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5876,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5943,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6072,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6089,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6745,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6775,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7173,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7231,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7270,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7345,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7855,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7932,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7955,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8036,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8143,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8373,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8413,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8788,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8852,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9520,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9571,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9601,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9621,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9649,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9663,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9697,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9741,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9756,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9787,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9796,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9906,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9948,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10142,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10172,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10260,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10269,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +11003,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11017,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11138,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11154,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11438,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11471,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11506,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11648,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11760,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11937,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11950,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12203,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12530,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12548,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12556,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12588,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12634,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12662,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12805,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14164,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14557,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14585,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14598,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14878,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15099,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15166,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15393,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15571,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15749,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15853,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15924,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16283,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16452,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17125,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17901,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +20000,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21403,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21528,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21542,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21615,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21796,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21811,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21906,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21921,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21982,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22022,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22060,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22086,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22927,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22941,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23024,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23038,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23058,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23071,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23079,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23097,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23207,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23216,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23225,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23251,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23260,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23294,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23307,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23315,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23325,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23341,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23353,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23364,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23449,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23513,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23533,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23579,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23587,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23615,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23643,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23734,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23784,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23804,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23812,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23848,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23891,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23916,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24258,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24569,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24587,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24638,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24657,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24670,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24782,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24828,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24836,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25050,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25075,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25093,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25119,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25130,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25328,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25350,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25359,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25490,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25511,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25537,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25557,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25603,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25837,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25883,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25902,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25913,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25978,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25987,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +26001,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26018,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26049,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26090,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26143,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26162,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26200,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26212,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26281,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26411,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26424,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26469,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26501,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26718,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26773,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26853,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26932,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27100,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27199,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27603,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27998,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28018,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28106,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28125,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28350,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28397,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28414,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28495,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28519,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28530,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28613,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28677,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28707,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28764,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28785,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28811,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28852,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28865,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28949,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28965,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28985,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +29003,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29044,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29056,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29082,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29120,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29158,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29236,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29290,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29301,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29354,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29400,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29411,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29423,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29433,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29453,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29464,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29478,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29490,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29505,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29518,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29537,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29553,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29569,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29586,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29615,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29636,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29647,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29671,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29682,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29691,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29782,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29829,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29839,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29898,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29910,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29947,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29986,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +30000,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30217,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30249,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30259,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30467,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30536,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30567,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30615,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30627,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30647,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30659,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30747,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30791,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30928,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30989,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +31002,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31025,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31180,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31324,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31333,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31427,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31437,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31467,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31487,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31561,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31570,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31625,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31728,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31749,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31785,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31802,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31874,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31928,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31984,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32018,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32037,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32052,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32086,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32135,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32148,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32168,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32203,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32219,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32241,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32277,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32296,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32328,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32336,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32348,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32592,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32692,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32742,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32810,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32852,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32970,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32980,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +33003,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33088,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33138,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33164,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33231,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33314,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33412,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33452,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33465,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33563,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33697,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33708,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33749,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33761,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33883,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33898,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33997,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34058,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34242,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34266,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34315,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34325,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34491,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34519,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34571,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34602,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34637,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34660,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34669,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34679,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34690,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34715,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34729,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34756,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34779,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34788,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34802,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34895,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34940,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34973,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35034,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35062,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35090,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35118,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35127,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35156,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35165,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35331,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35415,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35428,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35528,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35667,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35895,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35915,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36169,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36306,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36329,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36383,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36495,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36665,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36690,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36770,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36778,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36811,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36827,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36837,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36886,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36907,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36945,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37039,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37125,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37225,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37238,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37275,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37306,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37393,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37434,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37471,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37490,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37536,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37730,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37763,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37818,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37847,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37856,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37986,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38044,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38075,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38104,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38225,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38301,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38316,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38361,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38389,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38486,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38495,8 @@ var 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, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38750,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38763,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38825,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38843,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38854,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38867,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38905,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38933,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39132,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39162,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39176,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39318,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39329,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39535,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39636,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39646,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39705,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39726,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39777,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39822,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39954,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +40002,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40030,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40130,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40147,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40161,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40204,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40237,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40293,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40324,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40350,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40380,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40550,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40688,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40747,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40849,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40859,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40875,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40914,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40952,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40980,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41162,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41221,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41257,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41329,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41382,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41424,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41558,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41589,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41782,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42116,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42169,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42198,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42226,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42248,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42262,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42504,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42532,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42750,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42838,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42893,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42931,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43042,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43083,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43127,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43151,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43169,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43182,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43195,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43224,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43253,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43409,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43476,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43496,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43512,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43550,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43598,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43684,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43733,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43774,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43795,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43876,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43957,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44061,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44074,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44105,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44142,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44415,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44441,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44461,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44549,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44566,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44695,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44704,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44752,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44796,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44811,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44825,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44903,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44930,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45107,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45144,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45262,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45285,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45406,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45463,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45530,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45591,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45612,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45635,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45655,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45712,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45721,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45740,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45806,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // 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) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45875,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45902,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45921,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45935,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +46007,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46117,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46154,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46176,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46185,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46197,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46327,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46347,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46557,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46581,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46589,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46598,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46613,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46639,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46672,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46720,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46730,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46797,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46821,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47043,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47159,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47280,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47328,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47483,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47602,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47707,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47773,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47781,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47902,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47926,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47937,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47972,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47981,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48039,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48080,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48091,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48162,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48196,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48217,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48306,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48315,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48329,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48380,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48463,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48493,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48586,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48597,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48636,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48709,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48725,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48814,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48890,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48918,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48958,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48987,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49066,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49110,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49167,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49178,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49188,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49215,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49274,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49399,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49412,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49436,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49443,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49539,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49666,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49770,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49840,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49850,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49894,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50098,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50259,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50285,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50400,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50538,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50555,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50616,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50626,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50732,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50774,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50813,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50864,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50890,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50907,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50932,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50963,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51056,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51085,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51551,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51582,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51683,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51923,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51987,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52016,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52249,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52272,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52329,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52587,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52598,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53084,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53167,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53207,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53223,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53597,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53634,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54179,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54193,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54236,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54255,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54419,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54910,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54922,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54975,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55036,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55073,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55105,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55153,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55320,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55391,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55458,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55470,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55572,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55657,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55687,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55713,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55725,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55751,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55770,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55784,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55801,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55880,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55896,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55906,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55914,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56027,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56113,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56168,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56181,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56201,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56277,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56290,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56335,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56398,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56502,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56517,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56573,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56616,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56635,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56726,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56773,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56802,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56837,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57211,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57414,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57460,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57680,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57779,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57944,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57979,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61556,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61584,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64209,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64276,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65216,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65264,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67182,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67304,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67444,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67485,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67736,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67780,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67817,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67841,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67877,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67908,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67991,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68019,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68093,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68167,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* 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}); @@ -66699,7 +68199,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68214,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68231,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68328,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68425,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68479,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68508,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68532,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68568,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68599,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69263,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69448,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70046,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70117,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70246,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70434,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70724,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70792,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71048,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71079,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71121,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71137,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71216,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71493,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71523,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71564,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71726,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71905,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71913,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71960,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72442,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72867,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73073,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73197,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73461,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74131,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74163,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75248,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75305,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75336,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75587,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75654,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76619,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77704,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78511,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78546,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78576,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78594,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78604,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78676,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78697,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78715,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78734,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78747,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78784,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78792,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78813,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79338,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79579,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79593,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79640,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79100,20 +80876,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80917,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80966,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81015,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81749,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81771,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82196,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82407,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83112,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83144,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83318,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83740,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83931,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84010,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84524,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84557,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84567,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84575,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84587,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84599,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84615,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84649,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84676,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84764,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84780,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84842,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84851,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84875,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84902,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84963,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85010,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85022,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85114,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85150,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85195,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85286,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85298,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85329,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85350,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85381,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85408,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85478,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85494,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85530,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85555,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85570,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85633,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85699,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85790,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86019,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86127,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86183,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86205,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86271,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86292,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86322,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86351,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86438,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86447,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86467,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86487,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86507,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86518,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86567,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86580,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86639,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86674,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86687,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86704,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86903,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86920,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86931,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +87008,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87018,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87047,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87058,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87616,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87629,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87810,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87968,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88106,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88447,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88621,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88638,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88659,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88691,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88717,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88787,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88855,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88863,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88913,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88929,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88963,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88994,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +89008,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89060,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89095,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89169,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89208,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89235,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89416,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89442,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89531,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89553,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89571,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89642,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89657,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89678,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90527,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90539,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90682,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90727,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90803,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90888,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90926,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91017,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91066,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91305,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91364,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91486,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91623,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91987,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +92005,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92014,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92242,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92356,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92364,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92506,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92882,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92890,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92905,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93272,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93281,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94039,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94088,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94105,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94222,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94255,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94279,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94398,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94419,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94504,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94512,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94540,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94612,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94700,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94713,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94740,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94758,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94785,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95198,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95223,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95232,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95370,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95385,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95422,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95450,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95474,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95495,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95525,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95549,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95791,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95826,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95992,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +96004,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96026,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96040,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96215,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96250,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96322,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96342,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96814,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96858,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96872,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96939,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97227,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97258,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97378,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97523,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97573,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97588,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97604,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97643,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97729,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97755,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97874,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97892,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97900,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97938,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95894,15 +98069,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98180,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98209,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98224,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98274,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98332,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98359,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98529,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98765,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98823,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98833,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98863,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98895,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98909,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98947,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99010,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99113,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99141,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99171,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99201,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99243,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99509,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99729,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99762,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99825,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99885,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99928,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99938,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99953,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100277,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100603,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101456,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +102002,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102013,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102099,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102133,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102164,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102186,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102474,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102484,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102500,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102517,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102592,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102716,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102745,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102789,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102820,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102833,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102852,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103023,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103170,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103400,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103472,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103540,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103614,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103633,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105266,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106440,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106459,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106482,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106527,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106589,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106642,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106767,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106799,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106807,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106842,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106881,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106899,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106916,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106965,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107751,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107804,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107907,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107921,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107935,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107961,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107984,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107994,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108028,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108044,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108071,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108087,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108100,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108168,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108248,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108255,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108344,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108461,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108947,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109041,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109100,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109148,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109164,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109187,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109430,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109472,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109501,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109528,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109572,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109582,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109702,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109714,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110578,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110710,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110732,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110830,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110867,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110895,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110926,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110942,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +111008,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111073,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111090,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111325,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111352,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111582,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111608,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112258,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112277,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112903,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113119,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113453,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113509,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113549,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113823,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113955,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114099,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114124,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114547,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115121,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115300,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115642,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115681,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115706,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115821,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115864,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115944,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116169,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { @@ -115398,15 +118190,16 @@ var ts; function isNonDuplicateInSortedArray(value, index, array) { return index === 0 || value !== array[index - 1]; } + var indentStr = "\n "; /* @internal */ function indent(str) { - return "\n " + str; + return indentStr + str.replace(/\n/g, indentStr); } server.indent = indent; /** Put stringified JSON on the next line, indented. */ /* @internal */ function stringifyIndented(json) { - return "\n " + JSON.stringify(json); + return indentStr + JSON.stringify(json); } server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); @@ -115715,7 +118508,7 @@ var ts; var fileName = tempFileName || this.fileName; var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; }; // Only non typescript files have size limitation - if (!ts.hasTypeScriptFileExtension(this.fileName)) { + if (!ts.hasTSFileExtension(this.fileName)) { var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > server.maxFileSize) { ts.Debug.assert(!!this.info.containingProjects.length); @@ -116030,6 +118823,7 @@ var ts; isKnownTypesPackageName: ts.returnFalse, // Should never be called because we never provide a types registry. installPackage: ts.notImplemented, + inspectValue: ts.notImplemented, enqueueInstallTypingsRequest: ts.noop, attach: ts.noop, onProjectClosed: ts.noop, @@ -116091,6 +118885,9 @@ var ts; TypingsCache.prototype.installPackage = function (options) { return this.installer.installPackage(options); }; + TypingsCache.prototype.inspectValue = function (options) { + return this.installer.inspectValue(options); + }; TypingsCache.prototype.enqueueInstallTypingsForProject = function (project, unresolvedImports, forceRefresh) { var typeAcquisition = project.getTypeAcquisition(); if (!typeAcquisition || !typeAcquisition.enable) { @@ -116236,6 +119033,7 @@ var ts; * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project */ this.projectStateVersion = 0; + this.isInitialLoadPending = ts.returnFalse; /*@internal*/ this.dirty = false; /*@internal*/ @@ -116301,6 +119099,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /* @internal */ + Project.prototype.inspectValue = function (options) { + return this.typingsCache.inspectValue(options); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -116385,6 +119187,9 @@ var ts; Project.prototype.readFile = function (fileName) { return this.projectService.host.readFile(fileName); }; + Project.prototype.writeFile = function (fileName, content) { + return this.projectService.host.writeFile(fileName, content); + }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist // (because we're watching for their creation). @@ -116568,7 +119373,7 @@ var ts; var f = _a[_i]; this.detachScriptInfoIfNotRoot(f.fileName); } - var projectReferences = this.program.getProjectReferences(); + var projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (var _b = 0, projectReferences_2 = projectReferences; _b < projectReferences_2.length; _b++) { var ref = projectReferences_2[_b]; @@ -116639,7 +119444,7 @@ var ts; return this.rootFiles; } return ts.map(this.program.getSourceFiles(), function (sourceFile) { - var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); ts.Debug.assert(!!scriptInfo, "getScriptInfo", function () { return "scriptInfo for a file '" + sourceFile.fileName + "' Path: '" + sourceFile.path + "' / '" + sourceFile.resolvedPath + "' is missing."; }); return scriptInfo; }); @@ -116949,8 +119754,8 @@ var ts; var sourceFiles = this.program.getSourceFiles(); var strBuilder = "\tFiles (" + sourceFiles.length + ")\n"; if (writeProjectFileNames) { - for (var _i = 0, sourceFiles_9 = sourceFiles; _i < sourceFiles_9.length; _i++) { - var file = sourceFiles_9[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var file = sourceFiles_7[_i]; strBuilder += "\t" + file.fileName + "\n"; } } @@ -116973,7 +119778,10 @@ var ts; }; /* @internal */ Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { - server.updateProjectIfDirty(this); + // Update the graph only if initial configured project load is not pending + if (!this.isInitialLoadPending()) { + server.updateProjectIfDirty(this); + } var info = { projectName: this.getProjectName(), version: this.projectProgramVersion, @@ -117026,9 +119834,8 @@ var ts; ts.orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); }; - Project.prototype.enableGlobalPlugins = function () { + Project.prototype.enableGlobalPlugins = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117037,7 +119844,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_26 = function (globalPluginName) { + var _loop_25 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -117052,7 +119859,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_26(globalPluginName); + _loop_25(globalPluginName); } } }; @@ -117127,7 +119934,7 @@ var ts; if (!projectRootPath && !projectService.useSingleInferredProject) { _this.canonicalCurrentDirectory = projectService.toCanonicalFileName(_this.currentDirectory); } - _this.enableGlobalPlugins(); + _this.enableGlobalPlugins(_this.getCompilerOptions()); return _this; } InferredProject.prototype.toggleJsInferredProject = function (isJsInferredProject) { @@ -117210,14 +120017,18 @@ var ts; var ConfiguredProject = /** @class */ (function (_super) { __extends(ConfiguredProject, _super); /*@internal*/ - function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) { - var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; - _this.compileOnSaveEnabled = compileOnSaveEnabled; - _this.projectReferences = projectReferences; + function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) { + var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, + /*hasExplicitListOfFiles*/ false, + /*lastFileExceededProgramSize*/ undefined, + /*compilerOptions*/ {}, + /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this; /** Ref count to the project when opened from external project */ _this.externalProjectRefCount = 0; + _this.isInitialLoadPending = ts.returnTrue; + /*@internal*/ + _this.sendLoadingProjectFinish = false; _this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName)); - _this.enablePlugins(); return _this; } /** @@ -117225,17 +120036,27 @@ var ts; * @returns: true if set of files in the project stays the same and false - otherwise. */ ConfiguredProject.prototype.updateGraph = function () { + this.isInitialLoadPending = ts.returnFalse; var reloadLevel = this.pendingReload; this.pendingReload = ts.ConfigFileProgramReloadLevel.None; + var result; switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: - return this.projectService.reloadFileNamesOfConfiguredProject(this); + result = this.projectService.reloadFileNamesOfConfiguredProject(this); + break; case ts.ConfigFileProgramReloadLevel.Full: - this.projectService.reloadConfiguredProject(this); - return true; + var reason = ts.Debug.assertDefined(this.pendingReloadReason); + this.pendingReloadReason = undefined; + this.projectService.reloadConfiguredProject(this, reason); + result = true; + break; default: - return _super.prototype.updateGraph.call(this); + result = _super.prototype.updateGraph.call(this); } + this.projectService.sendProjectLoadingFinishEvent(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; }; /*@internal*/ ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () { @@ -117253,11 +120074,14 @@ var ts; /*@internal*/ ConfiguredProject.prototype.getResolvedProjectReferences = function () { var program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); }; ConfiguredProject.prototype.enablePlugins = function () { + this.enablePluginsWithOptions(this.getCompilerOptions()); + }; + /*@internal*/ + ConfiguredProject.prototype.enablePluginsWithOptions = function (options) { var host = this.projectService.host; - var options = this.getCompilationSettings(); if (!host.require) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -117277,7 +120101,7 @@ var ts; this.enablePlugin(pluginConfigEntry, searchPaths); } } - this.enableGlobalPlugins(); + this.enableGlobalPlugins(options); }; /** * Get the errors that dont have any file name associated @@ -117355,17 +120179,16 @@ var ts; // The project is referenced only if open files impacted by this project are present in this project return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false; }; + /*@internal*/ + ConfiguredProject.prototype.hasExternalProjectRef = function () { + return !!this.externalProjectRefCount; + }; ConfiguredProject.prototype.getEffectiveTypeRoots = function () { return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || []; }; /*@internal*/ - ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (hasFileNames) { - if (hasFileNames) { - ts.filterMutate(this.projectErrors, function (error) { return !ts.isErrorNoInputFiles(error); }); // TODO: GH#18217 - } - else if (!this.configFileSpecs.filesSpecs && !ts.some(this.projectErrors, ts.isErrorNoInputFiles)) { // TODO: GH#18217 - this.projectErrors.push(ts.getErrorForNoInputFiles(this.configFileSpecs, this.getConfigFilePath())); - } + ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) { + ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); }; return ConfiguredProject; }(Project)); @@ -117385,6 +120208,12 @@ var ts; _this.excludedFiles = []; return _this; } + ExternalProject.prototype.updateGraph = function () { + var result = _super.prototype.updateGraph.call(this); + this.projectService.sendProjectTelemetry(this); + this.projectService.sendSurveyReady(this); + return result; + }; ExternalProject.prototype.getExcludedFiles = function () { return this.excludedFiles; }; @@ -117412,6 +120241,9 @@ var ts; server.maxFileSize = 4 * 1024 * 1024; // tslint:disable variable-name server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; + server.ProjectLoadingStartEvent = "projectLoadingStart"; + server.ProjectLoadingFinishEvent = "projectLoadingFinish"; + server.SurveyReady = "surveyReady"; server.LargeFileReferencedEvent = "largeFileReferenced"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -117522,6 +120354,12 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; + /*@internal*/ + function convertUserPreferences(preferences) { + var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]); + return userPreferences; + } + server.convertUserPreferences = convertUserPreferences; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -117565,6 +120403,7 @@ var ts; WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; WatchType["TypeRoots"] = "Type root directory"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { @@ -117582,11 +120421,19 @@ var ts; function getDetailWatchInfo(watchType, project) { return "Project: " + (project ? project.getProjectName() : "") + " WatchType: " + watchType; } + function isScriptInfoWatchedFromNodeModules(info) { + return !info.isScriptOpen() && info.mTime !== undefined; + } /*@internal*/ function updateProjectIfDirty(project) { return project.dirty && project.updateGraph(); } server.updateProjectIfDirty = updateProjectIfDirty; + function setProjectOptionsUsed(project) { + if (project.projectKind === server.ProjectKind.Configured) { + project.projectOptions = true; + } + } var ProjectService = /** @class */ (function () { function ProjectService(opts) { var _this = this; @@ -117594,6 +120441,7 @@ var ts; * Container of all known scripts */ this.filenameToScriptInfo = ts.createMap(); + this.scriptInfoInNodeModulesWatchers = ts.createMap(); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -117640,10 +120488,12 @@ var ts; */ this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = ts.createMap(); + /** Tracks projects that we have already sent survey events for. */ + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117656,7 +120506,7 @@ var ts; this.globalPlugins = opts.globalPlugins || server.emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || server.emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(ts.getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); if (this.host.realpath) { @@ -117745,14 +120595,14 @@ var ts; this.safelist = raw.typesMap; for (var key in raw.simpleMap) { if (raw.simpleMap.hasOwnProperty(key)) { - this.legacySafelist[key] = raw.simpleMap[key].toLowerCase(); + this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); } } } catch (e) { this.logger.info("Error loading types map: " + e); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist.clear(); } }; ProjectService.prototype.updateTypingsForProject = function (response) { @@ -117819,6 +120669,13 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendSurveyReadyEvent = function (surveyId) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ eventName: server.SurveyReady, data: { surveyId: surveyId } }); + }; + /* @internal */ ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) { if (!this.eventHandler) { return; @@ -117830,6 +120687,30 @@ var ts; this.eventHandler(event); }; /* @internal */ + ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) { + if (!this.eventHandler) { + return; + } + project.sendLoadingProjectFinish = true; + var event = { + eventName: server.ProjectLoadingStartEvent, + data: { project: project, reason: reason } + }; + this.eventHandler(event); + }; + /* @internal */ + ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) { + if (!this.eventHandler || !project.sendLoadingProjectFinish) { + return; + } + project.sendLoadingProjectFinish = false; + var event = { + eventName: server.ProjectLoadingFinishEvent, + data: { project: project } + }; + this.eventHandler(event); + }; + /* @internal */ ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) { this.delayUpdateProjectGraph(project); this.delayEnsureProjectForOpenFiles(); @@ -118027,6 +120908,7 @@ var ts; else { this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */); project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = "Change in config file detected"; this.delayUpdateProjectGraph(project); // As we scheduled the update on configured project graph, // we would need to schedule the project reload for only the root of inferred projects @@ -118086,7 +120968,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_27 = function (inferredProject) { + var _loop_26 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -118107,7 +120989,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_27(inferredProject); + _loop_26(inferredProject); } } return project; @@ -118482,35 +121364,6 @@ var ts; ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { return findProjectByName(projectFileName, this.externalProjects); }; - ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename, cachedDirectoryStructureHost) { - configFilename = ts.normalizePath(configFilename); - var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 - var result = ts.parseJsonText(configFilename, configFileContent); - if (!result.endOfFileToken) { - result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; - } - var errors = result.parseDiagnostics; - var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, cachedDirectoryStructureHost, ts.getDirectoryPath(configFilename), - /*existingOptions*/ {}, configFilename, - /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); - if (parsedCommandLine.errors.length) { - errors.push.apply(errors, parsedCommandLine.errors); - } - ts.Debug.assert(!!parsedCommandLine.fileNames); - var projectOptions = { - files: parsedCommandLine.fileNames, - compilerOptions: parsedCommandLine.options, - configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, - configHasFilesProperty: parsedCommandLine.raw.files !== undefined, - configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined, - wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), - typeAcquisition: parsedCommandLine.typeAcquisition, - compileOnSave: parsedCommandLine.compileOnSave, - projectReferences: parsedCommandLine.projectReferences - }; - return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs }; - }; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) { if (options && options.disableSizeLimit || !this.host.getFileSize) { @@ -118523,12 +121376,12 @@ var ts; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var f = fileNames_2[_i]; var fileName = propertyReader.getFileName(f); - if (ts.hasTypeScriptFileExtension(fileName)) { + if (ts.hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTypeScriptFileExtension: ts.hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -118540,9 +121393,9 @@ var ts; return "Non TS file size exceeded limit (" + totalNonTsFileSize + "). Largest files: " + files.map(function (file) { return file.name + ":" + file.size; }).join(", "); } function getTop5LargestFiles(_a) { - var propertyReader = _a.propertyReader, hasTypeScriptFileExtension = _a.hasTypeScriptFileExtension, host = _a.host; + var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host; return fileNames.map(function (f) { return propertyReader.getFileName(f); }) - .filter(function (name) { return hasTypeScriptFileExtension(name); }) + .filter(function (name) { return hasTSFileExtension(name); }) .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217 .sort(function (a, b) { return b.size - a.size; }) .slice(0, 5); @@ -118553,21 +121406,37 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProjectAndUpdateGraph(project, files, externalFilePropertyReader, typeAcquisition); + this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); this.externalProjects.push(project); - this.sendProjectTelemetry(projectFileName, project); return project; }; - ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { - if (this.seenProjects.has(projectKey)) { + /*@internal*/ + ProjectService.prototype.sendSurveyReady = function (project) { + if (this.seenSurveyProjects.has(project.projectName)) { return; } - this.seenProjects.set(projectKey, true); + if (project.getCompilerOptions().checkJs !== undefined) { + var name = "checkJs"; + this.logger.info("Survey " + name + " is ready"); + this.sendSurveyReadyEvent(name); + this.seenSurveyProjects.set(project.projectName, true); + } + }; + /*@internal*/ + ProjectService.prototype.sendProjectTelemetry = function (project) { + if (this.seenProjects.has(project.projectName)) { + setProjectOptionsUsed(project); + return; + } + this.seenProjects.set(project.projectName, true); if (!this.eventHandler || !this.host.createSHA256Hash) { + setProjectOptionsUsed(project); return; } + var projectOptions = project.projectKind === server.ProjectKind.Configured ? project.projectOptions : undefined; + setProjectOptionsUsed(project); var data = { - projectId: this.host.createSHA256Hash(projectKey), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118586,8 +121455,7 @@ var ts; if (!(project instanceof server.ConfiguredProject)) { return "other"; } - var configFilePath = project instanceof server.ConfiguredProject ? project.getConfigFilePath() : undefined; // TODO: GH#18217 - return server.getBaseConfigFileName(configFilePath) || "other"; + return server.getBaseConfigFileName(project.getConfigFilePath()) || "other"; } function convertTypeAcquisition(_a) { var enable = _a.enable, include = _a.include, exclude = _a.exclude; @@ -118598,34 +121466,88 @@ var ts; }; } }; - ProjectService.prototype.addFilesToNonInferredProjectAndUpdateGraph = function (project, files, propertyReader, typeAcquisition) { + ProjectService.prototype.addFilesToNonInferredProject = function (project, files, propertyReader, typeAcquisition) { this.updateNonInferredProjectFiles(project, files, propertyReader); project.setTypeAcquisition(typeAcquisition); - // This doesnt need scheduling since its either creation or reload of the project - project.updateGraph(); }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217 - var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, // TODO: GH#18217 - lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences); - project.configFileSpecs = configFileSpecs; + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); // TODO: We probably should also watch the configFiles that are extended project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); - if (!lastFileExceededProgramSize) { - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - project.setProjectErrors(configFileErrors); - var filesToAdd = projectOptions.files.concat(project.getExternalFiles()); - this.addFilesToNonInferredProjectAndUpdateGraph(project, filesToAdd, fileNamePropertyReader, projectOptions.typeAcquisition); // TODO: GH#18217 this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); - this.sendProjectTelemetry(configFileName, project, projectOptions); return project; }; + /* @internal */ + ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; + return project; + }; + /* @internal */ + ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) { + var project = this.createConfiguredProject(configFileName); + this.loadConfiguredProject(project, reason); + return project; + }; + /* @internal */ + ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) { + var project = this.createAndLoadConfiguredProject(configFileName, reason); + project.updateGraph(); + return project; + }; + /** + * Read the config file of the project, and update the project root file names. + */ + /* @internal */ + ProjectService.prototype.loadConfiguredProject = function (project, reason) { + this.sendProjectLoadingStartEvent(project, reason); + // Read updated contents from disk + var configFilename = ts.normalizePath(project.getConfigFilePath()); + var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217 + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; + } + var configFileErrors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), + /*existingOptions*/ {}, configFilename, + /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions); + if (parsedCommandLine.errors.length) { + configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + var compilerOptions = parsedCommandLine.options; + // Update the project + if (!project.projectOptions) { + project.projectOptions = { + configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined, + configHasFilesProperty: parsedCommandLine.raw.files !== undefined, + configHasIncludeProperty: parsedCommandLine.raw.include !== undefined, + configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined + }; + } + project.configFileSpecs = parsedCommandLine.configFileSpecs; + project.canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(parsedCommandLine.raw); + project.setProjectErrors(configFileErrors); + project.updateReferences(parsedCommandLine.projectReferences); + var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); + if (lastFileExceededProgramSize) { + project.disableLanguageService(lastFileExceededProgramSize); + project.stopWatchingWildCards(); + } + else { + project.enableLanguageService(); + project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217 + } + project.enablePluginsWithOptions(compilerOptions); + var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); + this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217 + }; ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) { var projectRootFilesMap = project.getRootFilesMap(); var newRootScriptInfoMap = ts.createMap(); @@ -118681,14 +121603,14 @@ var ts; // mark the project as dirty unconditionally project.markAsDirty(); }; - ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { + ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) { project.setCompilerOptions(newOptions); // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently // therefore if it is undefined, it should not be updated. if (compileOnSave !== undefined) { project.compileOnSaveEnabled = compileOnSave; } - this.addFilesToNonInferredProjectAndUpdateGraph(project, newUncheckedFiles, propertyReader, newTypeAcquisition); + this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); }; /** * Reload the file names from config file specs and update the project graph @@ -118698,37 +121620,24 @@ var ts; var configFileSpecs = project.configFileSpecs; // TODO: GH#18217 var configFileName = project.getConfigFilePath(); var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions); - project.updateErrorOnNoInputFiles(fileNamesResult.fileNames.length !== 0); - this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames, fileNamePropertyReader); + project.updateErrorOnNoInputFiles(fileNamesResult); + this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader); return project.updateGraph(); }; /** - * Read the config file of the project again and update the project + * Read the config file of the project again by clearing the cache and update the project graph */ /* @internal */ - ProjectService.prototype.reloadConfiguredProject = function (project) { + ProjectService.prototype.reloadConfiguredProject = function (project, reason) { // At this point, there is no reason to not have configFile in the host var host = project.getCachedDirectoryStructureHost(); // Clear the cache since we are reloading the project from disk host.clearCache(); var configFileName = project.getConfigFilePath(); this.logger.info("Reloading configured project " + configFileName); - // Read updated contents from disk - var _a = this.convertConfigFileContentToProjectOptions(configFileName, host), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; - // Update the project - project.configFileSpecs = configFileSpecs; - project.setProjectErrors(configFileErrors); - project.updateReferences(projectOptions.projectReferences); - var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); // TODO: GH#18217 - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - project.stopWatchingWildCards(); - } - else { - project.enableLanguageService(); - project.watchWildcards(projectOptions.wildcardDirectories); // TODO: GH#18217 - } - this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave); // TODO: GH#18217 + // Load project from the disk + this.loadConfiguredProject(project, reason); + project.updateGraph(); this.sendConfigFileDiagEvent(project, configFileName); }; ProjectService.prototype.sendConfigFileDiagEvent = function (project, triggerFile) { @@ -118853,7 +121762,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_28 = function (project) { + var _loop_27 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -118870,7 +121779,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_28(project); + _loop_27(project); } } } @@ -118883,10 +121792,80 @@ var ts; if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - var fileName = info.fileName; - info.fileWatcher = this.watchFactory.watchFilePath(this.host, fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + var indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules)); + } } }; + ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) { + var _this = this; + // Watch only directory + var existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + var watchDir = dir + "/node_modules"; + var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) { + var fileOrDirectoryPath = _this.toPath(fileOrDirectory); + // Has extension + ts.Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + _this.refreshScriptInfosInDirectory(watchDir); + } + else { + var info = _this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + _this.refreshScriptInfo(info); + } + } + // Folder + else if (!ts.hasExtension(fileOrDirectoryPath)) { + _this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */); + var result = { + close: function () { + if (result.refCount === 1) { + watcher.close(); + _this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + }; + ProjectService.prototype.getModifiedTime = function (info) { + return (this.host.getModifiedTime(info.path) || ts.missingFileModifiedTime).getTime(); + }; + ProjectService.prototype.refreshScriptInfo = function (info) { + var mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + var eventKind = ts.getFileWatcherEventKind(info.mTime, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + }; + ProjectService.prototype.refreshScriptInfosInDirectory = function (dir) { + var _this = this; + dir = dir + ts.directorySeparator; + this.filenameToScriptInfo.forEach(function (info) { + if (isScriptInfoWatchedFromNodeModules(info) && ts.startsWith(info.path, dir)) { + _this.refreshScriptInfo(info); + } + }); + }; ProjectService.prototype.stopWatchingScriptInfo = function (info) { if (info.fileWatcher) { info.fileWatcher.close(); @@ -118952,6 +121931,7 @@ var ts; return this.filenameToScriptInfo.get(fileName); }; ProjectService.prototype.setHostConfiguration = function (args) { + var _this = this; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { @@ -118969,7 +121949,18 @@ var ts; this.logger.info("Format host information updated"); } if (args.preferences) { + var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject; this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences); + if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { + // Load configured projects for external projects that are pending reload + this.configuredProjects.forEach(function (project) { + if (project.hasExternalProjectRef() && + project.pendingReload === ts.ConfigFileProgramReloadLevel.Full && + !_this.pendingProjectUpdates.has(project.getProjectName())) { + project.updateGraph(); + } + }); + } } if (args.extraFileExtensions) { this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; @@ -118994,7 +121985,7 @@ var ts; // (and would separate out below reloading of projects to be called when immediate reload is needed) // as there is no need to load contents of the files from the disk // Reload Projects - this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue); + this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects"); this.ensureProjectForOpenFiles(); }; ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) { @@ -119002,8 +121993,8 @@ var ts; this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, /*delayReload*/ true, ignoreIfNotRootOfInferredProject ? function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project - ts.returnTrue // Reload all the open files impacted by config file - ); + ts.returnTrue, // Reload all the open files impacted by config file + "Change in config file detected"); this.delayEnsureProjectForOpenFiles(); }; /** @@ -119013,7 +122004,7 @@ var ts; * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor) { + ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) { var _this = this; var updatedProjects = ts.createMap(); // try to reload config file for all open files @@ -119030,18 +122021,16 @@ var ts; // otherwise we create a new one. var configFileName = _this.getConfigFileNameForFile(info); if (configFileName) { - var project = _this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - _this.createConfiguredProject(configFileName); - updatedProjects.set(configFileName, true); - } - else if (!updatedProjects.has(configFileName)) { + var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName); + if (!updatedProjects.has(configFileName)) { if (delayReload) { project.pendingReload = ts.ConfigFileProgramReloadLevel.Full; + project.pendingReloadReason = reason; _this.delayUpdateProjectGraph(project); } else { - _this.reloadConfiguredProject(project); + // reload from the disk + _this.reloadConfiguredProject(project, reason); } updatedProjects.set(configFileName, true); } @@ -119121,7 +122110,8 @@ var ts; var configFileName = this.getConfigFileNameForFile(originalFileInfo); if (!configFileName) return undefined; - var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); + var configuredProject = this.findConfiguredProjectByProjectName(configFileName) || + this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName); updateProjectIfDirty(configuredProject); // Keep this configured project as referenced from project addOriginalConfiguredProject(configuredProject); @@ -119165,7 +122155,7 @@ var ts; if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createConfiguredProject(configFileName); + project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open"); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -119276,13 +122266,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_29 = function (proj) { + var _loop_28 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_29(proj); + _loop_28(proj); } }; /* @internal */ @@ -119392,7 +122382,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_30 = function (name) { + var _loop_29 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -119410,7 +122400,7 @@ var ts; } } if (rule.exclude) { - var _loop_32 = function (exclude) { + var _loop_31 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -119437,7 +122427,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_32(exclude); + _loop_31(exclude); } } else { @@ -119453,11 +122443,11 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_30(name); + _loop_29(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_31 = function (i) { + var _loop_30 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -119468,13 +122458,13 @@ var ts; if (ts.fileExtensionIs(baseName, "js")) { var inferredTypingName = ts.removeFileExtension(baseName); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - if (this_4.legacySafelist[cleanedTypingName]) { + var typeName = this_4.legacySafelist.get(cleanedTypingName); + if (typeName !== undefined) { this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist"); excludedFiles.push(normalizedNames[i]); // *exclude* it from the project... exclude = true; // ... but *include* it in the list of types to acquire - var typeName = this_4.legacySafelist[cleanedTypingName]; // Same best-effort dedupe as above if (typeAcqInclude.indexOf(typeName) < 0) { typeAcqInclude.push(typeName); @@ -119495,7 +122485,7 @@ var ts; }; var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_31(i); + _loop_30(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -119546,7 +122536,9 @@ var ts; externalProject.enableLanguageService(); } // external project already exists and not config files were added - update the project and return; - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + // The graph update here isnt postponed since any file open operation needs all updated external projects + this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave); + externalProject.updateGraph(); return; } // some config files were added to external project (that previously were not there) @@ -119594,8 +122586,10 @@ var ts; var tsconfigFile = tsConfigFiles_1[_b]; var project = this.findConfiguredProjectByProjectName(tsconfigFile); if (!project) { - // errors are stored in the project - project = this.createConfiguredProject(tsconfigFile); + // errors are stored in the project, do not need to update the graph + project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? + this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) : + this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName); } if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project @@ -119605,8 +122599,11 @@ var ts; } else { // no config files - remove the item from the collection + // Create external project and update its graph, do not delay update since + // any file open operation needs all updated external projects this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles); + project.updateGraph(); } }; ProjectService.prototype.hasDeferredExtension = function () { @@ -119822,7 +122819,7 @@ var ts; /** * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. */ - function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + function combineProjectOutput(defaultValue, getValue, projects, action) { var outputs = ts.flatMap(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); if (!ts.isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach(function (projects, path) { @@ -119830,9 +122827,7 @@ var ts; outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); }); } - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); + return ts.deduplicate(outputs, ts.equateValues); } function combineProjectOutputFromEveryProject(projectService, action, areEqual) { var outputs = []; @@ -119877,24 +122872,27 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation, projectService) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, tryAddToTodo) { + combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; - var _loop_33 = function (outputReferencedSymbol) { - var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, outputReferencedSymbol.definition); }); + var _loop_32 = function (outputReferencedSymbol) { + var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); + var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); if (!symbolToAddTo) { - symbolToAddTo = { definition: outputReferencedSymbol.definition, references: [] }; + symbolToAddTo = { definition: definition, references: [] }; outputs.push(symbolToAddTo); } for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) { var ref = _a[_i]; - if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(ref))) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { symbolToAddTo.references.push(ref); } } }; for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.position) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; - _loop_33(outputReferencedSymbol); + _loop_32(outputReferencedSymbol); } }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -119950,7 +122948,7 @@ var ts; seenProjects.set(projectAndLocation.project.projectName, true); var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); if (!originalLocation) - return false; + return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { @@ -119966,7 +122964,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -120326,6 +123324,7 @@ var ts; globalPlugins: opts.globalPlugins, pluginProbeLocations: opts.pluginProbeLocations, allowLocalPluginLoads: opts.allowLocalPluginLoads, + typesMapLocation: opts.typesMapLocation, syntaxOnly: opts.syntaxOnly, }; this.projectService = new server.ProjectService(settings); @@ -120340,21 +123339,33 @@ var ts; var openFiles = event.data.openFiles; this.projectsUpdatedInBackgroundEvent(openFiles); break; + case server.ProjectLoadingStartEvent: + var _a = event.data, project = _a.project, reason = _a.reason; + this.event({ projectName: project.getProjectName(), reason: reason }, server.ProjectLoadingStartEvent); + break; + case server.ProjectLoadingFinishEvent: + var finishProject = event.data.project; + this.event({ projectName: finishProject.getProjectName() }, server.ProjectLoadingStartEvent); + break; case server.LargeFileReferencedEvent: - var _a = event.data, file = _a.file, fileSize = _a.fileSize, maxFileSize_1 = _a.maxFileSize; - this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, "largeFileReferenced"); + var _b = event.data, file = _b.file, fileSize = _b.fileSize, maxFileSize_1 = _b.maxFileSize; + this.event({ file: file, fileSize: fileSize, maxFileSize: maxFileSize_1 }, server.LargeFileReferencedEvent); break; case server.ConfigFileDiagEvent: - var _b = event.data, triggerFile = _b.triggerFile, configFile = _b.configFileName, diagnostics = _b.diagnostics; + var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics; var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); }); this.event({ triggerFile: triggerFile, configFile: configFile, diagnostics: bakedDiags - }, "configFileDiag"); + }, server.ConfigFileDiagEvent); + break; + case server.SurveyReady: + var surveyId = event.data.surveyId; + this.event({ surveyId: surveyId }, server.SurveyReady); break; case server.ProjectLanguageServiceStateEvent: { - var eventName = "projectLanguageServiceState"; + var eventName = server.ProjectLanguageServiceStateEvent; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled @@ -120383,10 +123394,13 @@ var ts; // Send project changed event this.event({ openFiles: openFiles - }, "projectsUpdatedInBackground"); + }, server.ProjectsUpdatedInBackgroundEvent); } }; Session.prototype.logError = function (err, cmd) { + this.logErrorWorker(err, cmd); + }; + Session.prototype.logErrorWorker = function (err, cmd, fileRequest) { var msg = "Exception on executing command " + cmd; if (err.message) { msg += ":\n" + server.indent(err.message); @@ -120394,6 +123408,17 @@ var ts; msg += "\n" + server.indent(err.stack); } } + if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } + } + catch (_b) { } // tslint:disable-line no-empty + } this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { @@ -120852,22 +123877,28 @@ var ts; if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = Session.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position)); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; - // strips 'triggerSpan' - Session.mapRenameInfo = function (_a) { - var canRename = _a.canRename, localizedErrorMessage = _a.localizedErrorMessage, displayName = _a.displayName, fullDisplayName = _a.fullDisplayName, kind = _a.kind, kindModifiers = _a.kindModifiers; - return { canRename: canRename, localizedErrorMessage: localizedErrorMessage, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers }; + Session.prototype.mapRenameInfo = function (info, scriptInfo) { + if (info.canRename) { + var canRename = info.canRename, fileToRename = info.fileToRename, displayName = info.displayName, fullDisplayName = info.fullDisplayName, kind = info.kind, kindModifiers = info.kindModifiers, triggerSpan = info.triggerSpan; + return ts.identity({ canRename: canRename, fileToRename: fileToRename, displayName: displayName, fullDisplayName: fullDisplayName, kind: kind, kindModifiers: kindModifiers, triggerSpan: this.toLocationTextSpan(triggerSpan, scriptInfo) }); + } + else { + return info; + } }; Session.prototype.toSpanGroups = function (locations) { var map = ts.createMap(); for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { - var _a = locations_1[_i], fileName = _a.fileName, textSpan = _a.textSpan; + var _a = locations_1[_i]; + var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]); var group_2 = map.get(fileName); if (!group_2) map.set(fileName, group_2 = { file: fileName, locs: [] }); - group_2.locs.push(this.toLocationTextSpan(textSpan, ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)))); + var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName)); + group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText)); } return ts.arrayFrom(map.values()); }; @@ -120884,7 +123915,7 @@ var ts; var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : ""; var nameSpan = nameInfo && nameInfo.textSpan; var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - var symbolName_4 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; + var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; var refs = ts.flatMap(references, function (referencedSymbol) { return referencedSymbol.references.map(function (_a) { var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; @@ -120895,7 +123926,7 @@ var ts; return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); }); }); - var result = { refs: refs, symbolName: symbolName_4, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; + var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; return result; } else { @@ -121099,7 +124130,7 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, this.getPreferences(file), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions })); if (completions === undefined) return undefined; if (kind === "completions-full" /* CompletionsFull */) @@ -121441,8 +124472,8 @@ var ts; var commands = args.command; // They should be sending back the command we sent them. for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) { var command = _a[_i]; - var project = this.getFileAndProject(command).project; - project.getLanguageService().applyCodeActionCommand(command).then(function (_result) { }, function (_error) { }); + var _b = this.getFileAndProject(command), file = _b.file, project = _b.project; + project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then(function (_result) { }, function (_error) { }); } return {}; }; @@ -121602,8 +124633,10 @@ var ts; } } var request; + var relevantFile; try { request = JSON.parse(message); + relevantFile = request.arguments && request.arguments.file ? request.arguments : undefined; var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.hasLevel(server.LogLevel.requestTime)) { var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); @@ -121627,7 +124660,7 @@ var ts; this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true); return; } - this.logError(err, message); + this.logErrorWorker(err, message, relevantFile); this.doOutput( /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack); @@ -121686,8 +124719,8 @@ var ts; continue; } for (var i = textChanges_4.length - 1; i >= 0; i--) { - var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 096362cc6a7..fdd11aa3484 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescript.js b/lib/typescript.js index 2af0b764874..bb0d451215a 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1443,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1948,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2046,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +2992,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3043,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3114,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3220,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3374,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3394,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3646,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3679,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3940,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4157,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4492,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5108,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5147,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5394,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5421,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5520,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5634,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5730,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5828,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5867,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5934,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6063,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6080,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6736,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6766,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7164,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7222,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7261,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7336,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7846,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7923,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7946,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8027,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8134,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8364,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8404,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8779,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8843,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9511,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9562,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9592,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9612,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9640,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9654,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9688,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9732,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9747,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9778,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9787,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9897,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9939,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10133,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10163,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10251,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10260,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +10994,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11008,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11129,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11145,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11429,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11462,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11497,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11639,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11751,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11928,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11941,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12194,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12521,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12539,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12547,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12579,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12625,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12653,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12796,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14155,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14548,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14576,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14589,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14869,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15090,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15157,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15384,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15562,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15740,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15844,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15915,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16274,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16443,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17116,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17892,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +19991,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21394,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21519,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21533,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21606,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21787,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21802,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21897,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21912,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21973,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22013,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22051,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22077,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22918,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22932,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23015,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23029,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23049,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23062,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23070,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23088,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23198,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23207,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23216,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23242,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23251,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23285,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23298,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23306,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23316,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23332,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23344,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23355,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23440,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23504,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23524,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23570,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23578,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23606,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23634,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23725,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23775,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23795,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23803,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23839,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23882,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23907,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24249,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24560,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24578,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24629,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24648,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24661,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24773,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24819,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24827,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25041,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25066,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25084,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25110,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25121,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25319,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25341,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25350,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25481,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25502,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25528,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25548,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25594,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25828,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25874,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25893,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25904,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25969,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25978,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25992,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26009,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26040,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26081,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26134,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26153,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26191,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26203,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26272,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26402,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26415,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26460,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26492,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26709,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26764,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26844,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26923,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27091,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27190,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27594,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27989,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28009,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28097,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28116,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28341,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28388,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28405,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28486,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28510,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28521,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28604,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28668,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28698,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28755,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28776,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28802,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28843,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28856,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28940,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28956,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28976,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28994,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29035,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29047,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29073,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29111,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29149,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29227,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29281,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29292,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29345,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29391,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29402,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29414,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29424,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29455,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29469,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29481,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29496,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29509,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29528,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29544,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29560,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29577,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29606,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29627,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29638,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29662,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29673,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29682,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29773,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29820,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29830,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29889,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29901,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29938,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29977,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +29991,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30208,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30240,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30250,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30458,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30527,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30558,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30606,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30618,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30638,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30650,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30738,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30782,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30919,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30980,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30993,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31016,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31171,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31315,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31324,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31418,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31428,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31458,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31478,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31552,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31561,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31616,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31719,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31740,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31776,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31793,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31865,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31919,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31975,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32009,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32028,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32043,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32077,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32126,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32139,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32159,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32194,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32210,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32232,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32268,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32287,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32319,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32327,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32339,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32583,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32683,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32733,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32801,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32843,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32961,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32971,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +32994,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33079,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33129,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33155,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33222,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33305,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33403,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33443,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33456,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33554,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33688,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33699,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33740,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33752,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33874,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33889,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33988,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34049,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34233,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34257,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34306,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34316,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34482,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34510,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34562,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34593,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34628,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34651,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34660,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34670,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34681,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34706,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34720,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34747,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34770,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34779,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34793,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34886,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34931,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34964,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35025,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35053,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35081,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35109,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35118,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35147,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35156,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35322,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35406,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35419,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35519,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35658,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35886,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35906,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36160,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36297,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36320,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36374,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36486,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36656,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36681,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36761,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36769,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36802,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36818,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36828,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36877,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36898,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36936,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37030,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37116,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37216,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37229,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37266,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37297,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37384,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37425,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37462,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37481,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37527,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37721,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37754,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37809,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37838,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37847,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37977,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38035,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38066,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38095,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38216,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38292,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38307,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38352,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38380,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38477,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38486,8 @@ var 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, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38741,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38754,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38816,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38834,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38845,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38858,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38896,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38924,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39123,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39153,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39167,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39309,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39320,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39526,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39627,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39637,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39696,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39717,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39768,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39813,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39945,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +39993,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40021,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40121,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40138,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40152,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40195,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40228,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40284,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40315,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40341,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40371,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40541,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40679,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40738,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40840,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40850,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40866,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40905,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40943,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40971,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41153,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41212,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41248,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41320,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41373,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41415,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41549,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41580,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41773,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42107,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42160,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42189,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42217,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42239,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42253,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42495,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42523,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42741,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42829,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42884,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42922,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43033,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43074,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43118,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43142,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43160,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43173,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43186,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43215,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43244,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43400,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43467,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43487,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43503,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43541,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43589,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43675,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43724,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43765,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43786,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43867,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43948,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44052,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44065,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44096,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44133,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44406,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44432,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44452,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44540,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44557,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44686,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44695,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44743,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44787,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44802,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44816,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44894,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44921,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45098,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45135,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45253,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45276,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45397,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45454,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45521,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45582,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45603,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45626,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45646,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45703,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45712,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45731,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45797,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // 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) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45866,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45893,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45912,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45926,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45998,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46108,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46145,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46167,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46176,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46188,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46318,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46338,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46548,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46572,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46580,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46589,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46604,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46630,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46663,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46711,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46721,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46788,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46812,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47034,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47150,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47271,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47319,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47474,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47593,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47698,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47764,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47772,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47893,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47917,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47928,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47963,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47972,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48030,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48071,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48082,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48153,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48187,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48208,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48297,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48306,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48320,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48371,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48454,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48484,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48577,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48588,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48627,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48700,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48716,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48805,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48881,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48909,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48949,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48978,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49057,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49101,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49158,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49169,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49179,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49206,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49265,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49390,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49403,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49427,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49434,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49530,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49657,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49761,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49831,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49841,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49885,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50089,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50250,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50276,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50391,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50529,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50546,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50607,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50617,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50723,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50765,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50804,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50855,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50881,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50898,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50923,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50954,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51047,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51076,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51542,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51573,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51674,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51914,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51978,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52007,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52240,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52263,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52320,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52578,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52589,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53075,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53158,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53198,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53214,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53588,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53625,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54170,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54184,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54227,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54246,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54410,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54901,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54913,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54966,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55027,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55064,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55096,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55144,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55311,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55382,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55449,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55461,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55563,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55648,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55678,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55704,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55716,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55742,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55761,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55775,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55792,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55871,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55887,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55897,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55905,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56018,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56104,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56159,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56172,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56192,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56268,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56281,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56326,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56389,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56493,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56508,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56564,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56607,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56626,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56717,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56764,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56793,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56828,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57202,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57405,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57451,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57671,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57770,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57935,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57970,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61547,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61575,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64200,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64267,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65207,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65255,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67173,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67295,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67435,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67476,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67727,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67771,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67808,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67832,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67868,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67899,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67982,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68010,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68084,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68158,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* 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}); @@ -66699,7 +68190,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68205,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68222,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68319,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68416,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68470,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68499,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68523,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68559,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68590,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69254,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69439,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70037,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70108,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70237,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70425,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70715,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70783,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71039,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71070,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71112,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71128,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71207,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71484,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71514,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71555,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71717,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71896,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71904,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71951,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72433,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72858,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73064,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73188,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73452,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74122,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74154,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75239,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75296,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75327,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75578,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75645,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76610,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77695,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78502,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78537,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78567,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78585,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78595,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78667,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78688,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78706,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78725,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78738,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78775,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78783,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78804,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79329,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79570,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79584,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79631,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79100,20 +80867,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80908,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80957,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81006,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81740,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81762,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82187,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82398,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83103,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83135,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83309,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83731,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83922,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84001,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84515,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84548,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84558,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84566,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84578,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84590,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84606,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84640,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84667,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84755,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84771,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84833,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84842,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84866,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84893,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84954,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85001,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85013,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85105,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85141,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85186,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85277,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85289,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85320,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85341,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85372,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85399,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85469,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85485,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85521,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85546,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85561,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85624,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85690,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85781,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86010,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86118,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86174,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86196,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86262,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86283,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86313,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86342,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86429,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86438,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86458,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86478,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86498,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86509,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86558,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86571,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86630,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86665,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86678,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86695,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86894,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86911,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86922,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86999,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87009,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87038,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87049,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87607,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87620,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87801,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87959,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88097,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88438,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88612,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88629,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88650,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88682,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88708,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88778,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88846,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88854,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88904,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88920,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88954,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88985,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88999,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89051,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89086,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89160,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89199,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89226,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89407,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89433,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89522,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89544,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89562,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89633,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89648,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89669,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90518,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90530,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90917,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91057,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91296,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91355,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91477,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91614,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91978,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91996,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92005,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92233,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92347,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92355,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92497,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92873,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92881,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92896,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93263,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93272,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94030,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94079,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94096,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94213,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94246,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94270,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94389,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94410,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94495,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94503,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94531,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94603,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94691,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94704,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94731,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94749,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94776,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95189,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95214,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95223,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95361,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95376,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95413,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95441,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95465,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95486,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95516,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95540,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95782,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95817,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95983,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95995,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96017,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96031,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96206,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96241,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96313,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96333,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96805,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96849,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96863,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96930,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97218,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97249,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97369,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97514,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97564,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97579,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97595,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97634,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97720,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97746,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97865,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97883,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97891,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97929,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95894,15 +98060,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98171,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98200,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98215,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98265,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98323,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98350,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98520,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98756,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98814,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98824,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98854,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98886,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98900,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98938,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99001,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99104,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99132,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99162,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99192,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99234,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99500,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99720,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99753,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99816,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99876,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99919,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99929,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99944,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100268,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100594,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101447,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101993,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102004,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102090,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102124,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102155,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102177,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102465,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102475,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102491,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102508,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102583,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102707,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102736,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102780,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102811,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102824,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102843,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103014,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103161,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103391,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103463,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103531,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103605,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103624,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105257,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106431,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106450,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106473,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106518,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106580,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106633,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106758,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106790,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106798,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106833,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106872,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106890,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106907,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106956,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107742,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107795,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107898,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107912,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107926,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107952,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107975,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107985,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108019,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108035,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108062,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108078,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108091,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108159,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108239,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108246,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108335,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108452,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108938,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109032,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109091,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109139,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109155,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109178,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109421,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109463,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109492,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109519,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109563,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109573,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109693,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109705,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110569,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110701,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110723,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110821,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110858,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110886,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110917,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110933,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +110999,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111064,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111081,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111316,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111343,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111573,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111599,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112249,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112268,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112894,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113110,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113444,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113500,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113540,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113814,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113946,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114090,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114115,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114538,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115112,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115291,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115633,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115672,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115697,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115812,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115855,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115935,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116160,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 887e98b6f5d..6f680858962 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ const version: string; } @@ -69,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -536,6 +537,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } @@ -632,6 +634,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -668,6 +671,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; @@ -1079,7 +1083,7 @@ declare namespace ts { } interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } interface NewExpression extends PrimaryExpression, Declaration { @@ -1808,7 +1812,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -2056,32 +2061,32 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, - Value = 67216319, - Type = 67901928, + Value = 67220415, + Type = 67897832, Namespace = 1920, Module = 1536, Accessor = 98304, - FunctionScopedVariableExcludes = 67216318, - BlockScopedVariableExcludes = 67216319, - ParameterExcludes = 67216319, + FunctionScopedVariableExcludes = 67220414, + BlockScopedVariableExcludes = 67220415, + ParameterExcludes = 67220415, PropertyExcludes = 0, EnumMemberExcludes = 68008959, - FunctionExcludes = 67215791, + FunctionExcludes = 67219887, ClassExcludes = 68008383, - InterfaceExcludes = 67901832, + InterfaceExcludes = 67897736, RegularEnumExcludes = 68008191, ConstEnumExcludes = 68008831, - ValueModuleExcludes = 67215503, + ValueModuleExcludes = 110735, NamespaceModuleExcludes = 0, - MethodExcludes = 67208127, - GetAccessorExcludes = 67150783, - SetAccessorExcludes = 67183551, - TypeParameterExcludes = 67639784, - TypeAliasExcludes = 67901928, + MethodExcludes = 67212223, + GetAccessorExcludes = 67154879, + SetAccessorExcludes = 67187647, + TypeParameterExcludes = 67635688, + TypeAliasExcludes = 67897832, AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, @@ -2490,6 +2495,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2587,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2597,6 @@ declare namespace ts { oldProgram?: Program; configFileParsingDiagnostics?: ReadonlyArray; } - interface UpToDateHost { - fileExists(fileName: string): boolean; - getModifiedTime(fileName: string): Date | undefined; - getUnchangedTime?(fileName: string): Date | undefined; - getLastStatus?(fileName: string): UpToDateStatus | undefined; - setLastStatus?(fileName: string, status: UpToDateStatus): void; - parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; - } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2698,9 +2695,6 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; - getModifiedTime?(fileName: string): Date | undefined; - setModifiedTime?(fileName: string, date: Date): void; - deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -3001,6 +2995,16 @@ declare namespace ts { Parameters = 1296, IndexSignatureParameters = 4432 } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ + readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly allowTextChangesInNewFiles?: boolean; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -3209,17 +3213,27 @@ declare namespace ts { /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param: TypeParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -4171,14 +4185,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { + /** @deprecated */ interface ResolveProjectReferencePathHost { fileExists(fileName: string): boolean; } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -4303,32 +4318,43 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; - interface WatchCompilerHost { + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; + /** Host that has watch functionality used in --watch mode */ + interface WatchHost { + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + interface WatchCompilerHost extends WatchHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; - /** If provided, called with Diagnostic message that informs about change in watch status */ - onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4361,14 +4387,6 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; - /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; - /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ - setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - /** If provided, will be used to reset existing delayed compilation */ - clearTimeout?(timeoutId: any): void; } /** * Host to create watch with root files and options @@ -4378,6 +4396,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4432,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ @@ -4423,184 +4443,11 @@ declare namespace ts { */ function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } -declare namespace ts { - interface BuildHost { - verbose(diag: DiagnosticMessage, ...args: string[]): void; - error(diag: DiagnosticMessage, ...args: string[]): void; - errorDiagnostic(diag: Diagnostic): void; - message(diag: DiagnosticMessage, ...args: string[]): void; - } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - /** - * Map from config file name to up-to-date status - */ - projectStatus: FileMap; - invalidatedProjects: FileMap; - queuedProjects: FileMap; - missingRoots: Map; - } - type Mapper = ReturnType; - interface DependencyGraph { - buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; - } - interface BuildOptions { - dry: boolean; - force: boolean; - verbose: boolean; - } - enum UpToDateStatusType { - Unbuildable = 0, - UpToDate = 1, - /** - * The project appears out of date because its upstream inputs are newer than its outputs, - * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. - * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. - */ - UpToDateWithUpstreamTypes = 2, - OutputMissing = 3, - OutOfDateWithSelf = 4, - OutOfDateWithUpstream = 5, - UpstreamOutOfDate = 6, - UpstreamBlocked = 7, - /** - * Projects with no outputs (i.e. "solution" files) - */ - ContainerOnly = 8 - } - type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; - namespace Status { - /** - * The project can't be built at all in its current state. For example, - * its config file cannot be parsed, or it has a syntax error or missing file - */ - interface Unbuildable { - type: UpToDateStatusType.Unbuildable; - reason: string; - } - /** - * This project doesn't have any outputs, so "is it up to date" is a meaningless question. - */ - interface ContainerOnly { - type: UpToDateStatusType.ContainerOnly; - } - /** - * The project is up to date with respect to its inputs. - * We track what the newest input file is. - */ - interface UpToDate { - type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; - newestInputFileTime?: Date; - newestInputFileName?: string; - newestDeclarationFileContentChangedTime?: Date; - newestOutputFileTime?: Date; - newestOutputFileName?: string; - oldestOutputFileName?: string; - } - /** - * One or more of the outputs of the project does not exist. - */ - interface OutputMissing { - type: UpToDateStatusType.OutputMissing; - /** - * The name of the first output file that didn't exist - */ - missingOutputFileName: string; - } - /** - * One or more of the project's outputs is older than its newest input. - */ - interface OutOfDateWithSelf { - type: UpToDateStatusType.OutOfDateWithSelf; - outOfDateOutputFileName: string; - newerInputFileName: string; - } - /** - * This project depends on an out-of-date project, so shouldn't be built yet - */ - interface UpstreamOutOfDate { - type: UpToDateStatusType.UpstreamOutOfDate; - upstreamProjectName: string; - } - /** - * This project depends an upstream project with build errors - */ - interface UpstreamBlocked { - type: UpToDateStatusType.UpstreamBlocked; - upstreamProjectName: string; - } - /** - * One or more of the project's outputs is older than the newest output of - * an upstream project. - */ - interface OutOfDateWithUpstream { - type: UpToDateStatusType.OutOfDateWithUpstream; - outOfDateOutputFileName: string; - newerProjectName: string; - } - } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; - } - function createDependencyMapper(): { - addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; - getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; - getKeys: () => ReadonlyArray; - }; - function createBuildContext(options: BuildOptions): BuildContext; - function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; - /** - * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but - * can dynamically add/remove other projects based on changes on the rootNames' references - */ - function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { - buildAllProjects: () => ExitStatus; - getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; - getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; - cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; - resetBuildContext: (opts?: BuildOptions) => void; - getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; - invalidateProject: (configFileName: string) => void; - buildInvalidatedProjects: () => void; - buildDependentInvalidatedProjects: () => void; - resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; - startWatching: () => void; - }; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; - function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; - function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; -} declare namespace ts.server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; + type ActionValueInspected = "action::valueInspected"; type EventTypesRegistry = "event::typesRegistry"; type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; @@ -4609,7 +4456,7 @@ declare namespace ts.server { " __sortedArrayBrand": any; } interface TypingInstallerResponse { - readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -4817,14 +4664,7 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; - } - interface UserPreferences { - readonly disableSuggestions?: boolean; - readonly quotePreference?: "double" | "single"; - readonly includeCompletionsForModuleExports?: boolean; - readonly includeCompletionsWithInsertText?: boolean; - readonly importModuleSpecifierPreference?: "relative" | "non-relative"; - readonly allowTextChangesInNewFiles?: boolean; + writeFile?(fileName: string, content: string): void; } interface LanguageService { cleanupSemanticCache(): void; @@ -4882,9 +4722,9 @@ declare namespace ts { toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; - applyCodeActionCommand(action: CodeActionCommand): Promise; - applyCodeActionCommand(action: CodeActionCommand[]): Promise; - applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; + applyCodeActionCommand(action: CodeActionCommand, formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; + applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[], formatSettings?: FormatCodeSettings): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand): Promise; /** @deprecated `fileName` will be ignored */ @@ -5046,9 +4886,16 @@ declare namespace ts { changes: ReadonlyArray; commands?: ReadonlyArray; } - type CodeActionCommand = InstallPackageAction; + type CodeActionCommand = InstallPackageAction | GenerateTypesAction; interface InstallPackageAction { } + interface GenerateTypesAction extends GenerateTypesOptions { + } + interface GenerateTypesOptions { + readonly file: string; + readonly fileToGenerateTypesFor: string; + readonly outputFileName: string; + } /** * A set of one or more available refactoring actions, grouped under a parent refactoring. */ @@ -5114,6 +4961,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5266,15 +5115,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; - localizedErrorMessage?: string; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 2af0b764874..bb0d451215a 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -62,7 +62,7 @@ var __extends = (this && this.__extends) || (function () { ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); - } + }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -73,7 +73,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -88,6 +88,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -716,17 +717,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -771,7 +778,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1148,7 +1155,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1268,6 +1275,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1432,7 +1443,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1935,6 +1948,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2029,6 +2046,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2615,6 +2992,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3043,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2734,38 +3114,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2840,14 +3220,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -2993,9 +3374,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3014,22 +3394,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3266,25 +3646,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3303,25 +3679,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3565,20 +3940,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3796,17 +4157,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4127,11 +4492,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4742,7 +5108,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4781,6 +5147,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5024,7 +5394,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5052,6 +5421,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5143,6 +5520,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5256,7 +5634,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5350,7 +5730,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5448,6 +5828,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5478,9 +5867,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5545,6 +5934,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5673,10 +6063,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5687,136 +6080,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6394,6 +6736,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6423,6 +6766,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6820,9 +7164,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6878,6 +7222,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6916,6 +7261,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6973,6 +7336,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7478,7 +7846,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7555,6 +7923,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +7946,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7657,22 +8027,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7777,6 +8134,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8001,12 +8364,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8033,13 +8404,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8408,6 +8779,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8468,6 +8843,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9135,18 +9511,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9186,14 +9562,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9216,15 +9592,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9232,26 +9612,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9260,7 +9640,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9274,30 +9654,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9308,7 +9688,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9352,12 +9732,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9367,9 +9747,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9398,7 +9778,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9407,11 +9787,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9517,7 +9897,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9559,6 +9939,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9749,6 +10133,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9773,32 +10163,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9857,7 +10251,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9866,7 +10260,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10600,7 +10994,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10614,7 +11008,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10735,7 +11129,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10751,7 +11145,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11035,13 +11429,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11063,15 +11462,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11107,10 +11497,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11249,6 +11639,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11339,6 +11751,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11514,6 +11928,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11525,12 +11941,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11756,13 +12194,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12090,13 +12521,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12108,9 +12539,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12118,10 +12547,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12152,7 +12579,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12198,15 +12625,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12227,6 +12653,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12353,7 +12796,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13699,7 +14155,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14092,6 +14548,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14108,9 +14576,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14122,13 +14589,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14401,8 +14869,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14624,6 +15090,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14684,6 +15157,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14910,36 +15384,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15067,14 +15562,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15245,6 +15740,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15333,6 +15844,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15403,6 +15915,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15761,7 +16274,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15930,8 +16443,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16599,7 +17116,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17367,8 +17892,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19464,8 +19991,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20866,7 +21394,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -20991,13 +21519,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21012,7 +21533,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21083,7 +21606,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21264,10 +21787,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21281,14 +21802,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21376,7 +21897,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21391,7 +21912,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21452,7 +21973,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21492,17 +22013,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21530,7 +22051,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21556,9 +22077,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22399,8 +22918,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +22932,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22461,21 +23015,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22490,6 +23029,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22508,6 +23049,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22520,6 +23062,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22527,6 +23070,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22544,6 +23088,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22653,6 +23198,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23207,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23216,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22685,6 +23242,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23251,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23285,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23298,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22745,6 +23306,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22754,6 +23316,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22769,6 +23332,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22780,6 +23344,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22790,6 +23355,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22874,30 +23440,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22956,12 +23504,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22974,6 +23524,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23019,6 +23570,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23026,6 +23578,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23053,6 +23606,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23080,7 +23634,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23133,20 +23725,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23182,16 +23775,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23203,7 +23795,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23211,7 +23803,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23247,7 +23839,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +23882,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23305,7 +23907,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23619,7 +24249,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23926,7 +24560,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23943,8 +24578,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23980,19 +24629,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24000,7 +24648,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +24661,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24110,11 +24773,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24161,7 +24819,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24169,7 +24827,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24383,7 +25041,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24408,10 +25066,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24421,9 +25084,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24431,7 +25110,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24442,16 +25121,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24640,6 +25319,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24656,7 +25341,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24665,48 +25350,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24750,7 +25481,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24770,7 +25502,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24797,11 +25528,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24817,7 +25548,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24856,14 +25594,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25086,15 +25828,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25132,7 +25874,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25151,7 +25893,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25162,74 +25904,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25241,8 +25969,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25250,7 +25978,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25264,7 +25992,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25281,29 +26009,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25311,7 +26040,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25352,52 +26081,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25411,12 +26134,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25430,40 +26153,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25475,6 +26191,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25486,51 +26203,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25550,87 +26272,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25638,11 +26402,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25651,43 +26415,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25695,24 +26460,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25727,9 +26492,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25944,13 +26709,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -25995,7 +26764,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26075,7 +26844,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26153,12 +26923,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26321,6 +27091,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26419,6 +27190,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26821,7 +27594,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27217,7 +27989,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27237,7 +28009,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27325,9 +28097,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27347,7 +28116,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27572,7 +28341,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27619,7 +28388,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27636,15 +28405,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27717,15 +28486,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27741,7 +28510,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27752,9 +28521,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27835,37 +28604,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27901,7 +28668,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27931,7 +28698,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -27988,7 +28755,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28009,7 +28776,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28035,40 +28802,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28077,7 +28843,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28090,7 +28856,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28174,8 +28940,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28187,10 +28956,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28207,7 +28976,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28225,10 +28994,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28266,10 +29035,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28278,14 +29047,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28304,9 +29073,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28344,7 +29111,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28382,6 +29149,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28457,40 +29227,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28511,7 +29281,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28522,25 +29292,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28575,35 +29345,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28621,7 +29391,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28632,7 +29402,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28644,7 +29414,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28654,11 +29424,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28674,7 +29444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28685,7 +29455,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28699,11 +29469,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28711,10 +29481,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28726,7 +29496,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28739,13 +29509,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28758,7 +29528,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28774,13 +29544,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28790,7 +29560,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28807,26 +29577,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28834,18 +29606,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28853,7 +29627,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28864,22 +29638,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28888,7 +29662,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28899,7 +29673,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28908,24 +29682,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -28999,7 +29773,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29046,8 +29820,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29056,58 +29830,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29115,8 +29889,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29127,22 +29901,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29164,27 +29938,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29203,12 +29977,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29217,9 +29991,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29434,6 +30208,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29454,7 +30240,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29463,6 +30250,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29670,8 +30458,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29739,7 +30527,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29769,8 +30558,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29804,6 +30606,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29815,6 +30618,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +30638,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +30650,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29933,6 +30738,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29975,6 +30782,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30110,35 +30919,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30171,7 +30980,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30184,8 +30993,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30206,53 +31016,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30360,8 +31171,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30504,7 +31315,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30513,15 +31324,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30599,7 +31418,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30609,7 +31428,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30636,7 +31458,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30656,7 +31478,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30730,7 +31552,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30739,7 +31561,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30794,14 +31616,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30897,9 +31719,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30918,29 +31740,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30951,7 +31776,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30968,6 +31793,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31037,7 +31865,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31091,7 +31919,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31147,7 +31975,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31181,7 +32009,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31200,7 +32028,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31215,10 +32043,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31249,7 +32077,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31298,11 +32126,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31311,11 +32139,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31331,7 +32159,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31366,15 +32194,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31382,9 +32210,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31392,6 +32232,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32268,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32287,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31472,7 +32319,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31480,7 +32327,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31492,24 +32339,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31737,7 +32583,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31837,7 +32683,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31887,7 +32733,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31952,11 +32801,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -31994,7 +32843,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32102,7 +32961,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32112,7 +32971,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32135,6 +32994,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32217,7 +33079,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32262,13 +33129,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32288,7 +33155,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32355,17 +33222,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32435,23 +33305,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32533,8 +33403,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32573,7 +33443,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32586,7 +33456,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32684,18 +33554,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32823,7 +33688,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32834,7 +33699,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32875,6 +33740,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32884,12 +33752,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32996,7 +33874,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33004,7 +33889,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33103,6 +33988,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33161,7 +34049,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33345,10 +34233,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33369,7 +34257,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33418,6 +34306,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33426,6 +34316,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33590,27 +34482,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33618,11 +34510,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33670,7 +34562,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33701,16 +34593,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33730,16 +34628,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33753,8 +34651,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33762,9 +34660,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33772,7 +34670,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33783,15 +34681,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33810,7 +34706,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33824,10 +34720,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33851,9 +34747,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33876,8 +34770,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33885,7 +34779,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33899,8 +34793,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -33992,9 +34886,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34037,19 +34931,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34063,7 +34964,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34124,7 +35025,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34152,14 +35053,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34182,7 +35081,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34210,7 +35109,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34219,11 +35118,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34248,7 +35147,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34257,22 +35156,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34431,23 +35322,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34518,7 +35406,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34529,8 +35419,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34629,7 +35519,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34768,9 +35658,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -34996,7 +35886,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35016,7 +35906,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35270,7 +36160,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35407,7 +36297,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35430,7 +36320,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35484,6 +36374,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35595,7 +36486,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35765,10 +36656,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35785,7 +36681,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35864,6 +36761,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35871,8 +36769,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35894,8 +36802,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35910,7 +36818,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35920,9 +36828,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35972,6 +36877,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35979,14 +36898,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36016,10 +36936,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36110,8 +37030,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36192,7 +37116,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36292,7 +37216,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36305,7 +37229,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36342,7 +37266,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36373,7 +37297,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36460,7 +37384,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36501,6 +37425,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36537,7 +37462,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36556,8 +37481,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36598,7 +37527,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36792,10 +37721,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36825,7 +37754,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36880,14 +37809,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36895,7 +37838,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36904,16 +37847,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37029,16 +37977,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37087,10 +38035,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37118,6 +38066,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37144,7 +38095,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37265,6 +38216,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37333,10 +38292,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37351,15 +38307,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37405,7 +38352,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37433,7 +38380,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37530,10 +38477,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37542,8 +38486,8 @@ var 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, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37797,7 +38741,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37810,20 +38754,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37869,7 +38816,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37887,7 +38834,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37895,20 +38845,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37922,37 +38858,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37973,7 +38896,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38000,17 +38924,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38188,7 +39123,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38218,7 +39153,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38232,7 +39167,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38374,8 +39309,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38385,7 +39320,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38591,7 +39526,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38692,7 +39627,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38702,7 +39637,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38761,8 +39696,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38772,30 +39717,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38819,6 +39768,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38858,49 +39813,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38974,7 +39945,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39022,8 +39993,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39049,33 +40021,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39084,15 +40121,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39101,10 +40138,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39115,13 +40152,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39155,8 +40195,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39188,9 +40228,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39239,8 +40284,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39270,9 +40315,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39295,11 +40341,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39325,13 +40371,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39495,10 +40541,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39633,10 +40679,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39692,13 +40738,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39797,7 +40840,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39807,32 +40850,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39849,8 +40866,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39888,13 +40905,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39923,7 +40943,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39950,32 +40971,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40140,6 +41153,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40168,20 +41212,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40199,7 +41248,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40272,6 +41320,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40305,36 +41373,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40357,10 +41415,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40491,33 +41549,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40549,8 +41580,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40742,6 +41773,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41030,8 +42107,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41083,9 +42160,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41107,10 +42189,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41135,13 +42217,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41153,7 +42239,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41167,11 +42253,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41408,8 +42495,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41432,44 +42523,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41645,7 +42741,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41731,11 +42829,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41784,6 +42884,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41819,7 +42922,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41915,33 +43033,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41951,12 +43074,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -41987,8 +43118,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42011,7 +43142,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42029,7 +43160,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42042,10 +43173,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42056,16 +43186,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42082,7 +43215,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42111,11 +43244,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42238,14 +43400,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42289,6 +43467,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42297,8 +43487,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42306,8 +43503,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42344,13 +43541,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42390,7 +43589,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42476,10 +43675,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42525,6 +43724,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42549,6 +43765,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42567,8 +43786,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42648,8 +43867,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42729,8 +43948,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42833,11 +44052,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42846,6 +44065,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42869,7 +44096,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42905,15 +44133,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43172,12 +44406,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43188,11 +44432,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43211,6 +44452,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43223,7 +44540,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43240,22 +44557,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43379,8 +44686,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43388,7 +44695,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43436,7 +44743,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43480,8 +44787,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43495,8 +44802,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43509,7 +44816,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43587,6 +44894,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43611,22 +44921,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43768,31 +45098,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43807,13 +45135,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43898,16 +45253,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43919,19 +45276,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44039,7 +45397,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44096,7 +45454,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44163,9 +45521,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44212,7 +45582,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44233,13 +45603,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44249,9 +45626,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44269,19 +45646,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44299,6 +45703,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +45712,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44329,8 +45731,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44395,47 +45797,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // 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) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44475,6 +45866,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44500,7 +45893,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44519,6 +45912,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44527,7 +45926,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44599,11 +45998,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44709,8 +46108,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44746,7 +46145,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44768,7 +46167,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44777,7 +46176,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44789,35 +46188,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44907,9 +46318,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44927,7 +46338,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45137,12 +46548,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45159,7 +46572,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45167,7 +46580,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45176,7 +46589,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45191,14 +46604,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45215,7 +46630,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45248,7 +46663,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45296,7 +46711,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45306,7 +46721,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45373,7 +46788,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45397,7 +46812,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45619,7 +47034,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45735,7 +47150,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45856,10 +47271,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45904,7 +47319,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46059,6 +47474,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46172,7 +47593,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46277,7 +47698,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46343,7 +47764,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46351,7 +47772,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46472,16 +47893,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46499,7 +47917,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46510,11 +47928,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46545,7 +47963,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46554,7 +47972,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46612,58 +48030,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46671,12 +48071,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46685,23 +48082,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46756,36 +48153,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46799,19 +48187,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46819,283 +48208,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47104,6 +48297,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47112,7 +48306,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47123,16 +48320,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47165,36 +48371,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47264,14 +48454,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47291,60 +48484,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47364,7 +48577,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47375,7 +48588,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47414,17 +48627,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47477,11 +48700,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47493,16 +48716,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47575,11 +48805,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47649,10 +48881,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47676,8 +48909,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47716,8 +48949,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47745,7 +48978,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47824,34 +49057,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47864,14 +49101,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47924,7 +49158,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47935,7 +49169,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47945,8 +49179,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47972,7 +49206,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48031,7 +49265,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48156,14 +49390,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48172,17 +49403,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48206,15 +49427,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48222,6 +49434,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48307,6 +49530,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48424,10 +49657,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48477,7 +49761,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48547,6 +49831,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48556,8 +49841,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48598,7 +49885,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48803,8 +50089,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48964,7 +50250,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -48990,8 +50276,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49105,7 +50391,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49243,9 +50529,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49260,15 +50546,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49321,8 +50607,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +50617,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49437,7 +50723,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49479,19 +50765,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49522,11 +50804,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49573,15 +50855,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49595,9 +50881,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49608,13 +50898,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49633,13 +50923,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49664,7 +50954,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49757,9 +51047,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49789,7 +51076,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50255,7 +51542,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50286,7 +51573,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50387,8 +51674,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50627,6 +51914,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50684,13 +51978,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50720,10 +52007,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50953,7 +52240,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50976,7 +52263,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51033,7 +52320,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51291,8 +52578,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51302,7 +52589,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51788,7 +53075,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51871,7 +53158,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51911,7 +53198,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51927,7 +53214,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52301,13 +53588,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52334,9 +53625,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52877,7 +54170,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52888,7 +54184,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52931,7 +54227,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52950,7 +54246,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53114,6 +54410,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53603,8 +54901,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53615,7 +54913,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53668,14 +54966,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53729,13 +55027,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53766,7 +55064,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53798,7 +55096,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53846,7 +55144,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54013,7 +55311,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54084,13 +55382,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54144,9 +55449,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54157,7 +55461,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54260,7 +55563,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54345,12 +55648,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54375,7 +55678,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54401,7 +55704,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54413,7 +55716,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54439,10 +55742,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54458,7 +55761,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54472,7 +55775,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54489,7 +55792,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54568,7 +55871,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54584,6 +55887,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54593,7 +55897,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54601,30 +55905,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54719,13 +56018,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54786,13 +56104,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54841,7 +56159,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54854,11 +56172,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54874,7 +56192,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54950,7 +56268,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54963,7 +56281,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55008,6 +56326,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55052,9 +56389,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55156,7 +56493,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55171,18 +56508,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55225,6 +56564,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,7 +56607,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55280,9 +56626,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55371,6 +56717,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55415,6 +56764,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55442,31 +56793,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55478,7 +56828,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55852,11 +57202,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56034,6 +57405,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56077,8 +57451,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56295,6 +57671,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56391,26 +57770,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56550,10 +57935,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56584,8 +57970,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60161,6 +61547,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60174,19 +61575,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62811,8 +64200,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62878,7 +64267,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63818,7 +65207,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63866,9 +65255,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65782,7 +67173,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65904,7 +67295,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66044,6 +67435,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66077,6 +67476,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66318,23 +67727,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66352,6 +67771,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66387,6 +67808,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66409,6 +67832,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66437,13 +67868,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66468,18 +67899,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66507,12 +67982,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66535,6 +68010,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66603,6 +68084,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66667,7 +68158,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* 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}); @@ -66699,7 +68190,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66714,7 +68205,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66731,7 +68222,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66828,7 +68319,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66925,25 +68416,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66967,7 +68470,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -66996,6 +68499,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67018,6 +68523,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67046,13 +68559,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67077,13 +68590,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67741,6 +69254,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67921,7 +69439,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68519,7 +70037,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68590,7 +70108,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68719,7 +70237,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68907,7 +70425,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69197,19 +70715,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69257,8 +70783,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69513,7 +71039,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69544,7 +71070,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69570,7 +71112,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69586,7 +71128,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69603,165 +71207,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69769,24 +71484,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69799,8 +71514,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69840,21 +71555,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -69994,7 +71717,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70173,7 +71896,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70181,7 +71904,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70228,7 +71951,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70710,7 +72433,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71135,10 +72858,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71341,7 +73064,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71465,10 +73188,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71729,10 +73452,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72399,7 +74122,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72431,10 +74154,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73516,7 +75239,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73570,6 +75296,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73600,22 +75327,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73849,7 +75578,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73916,7 +75645,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74881,7 +76610,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75966,7 +77695,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76773,7 +78502,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76808,11 +78537,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76838,7 +78567,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +78585,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76865,10 +78595,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76937,15 +78667,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76957,11 +78688,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76974,6 +78706,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -76992,8 +78725,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77004,11 +78738,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77038,7 +78775,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77046,13 +78783,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77062,6 +78804,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77578,10 +79329,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77804,7 +79570,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77818,7 +79584,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77865,10 +79631,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79100,20 +80867,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79136,7 +80908,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79185,26 +80957,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79229,12 +81006,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79963,7 +81740,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79985,7 +81762,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80410,7 +82187,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80621,7 +82398,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81324,13 +83103,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81356,11 +83135,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81525,7 +83309,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81946,19 +83731,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82137,7 +83922,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82216,7 +84001,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82730,17 +84515,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82756,7 +84548,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82766,7 +84558,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82774,8 +84566,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82786,8 +84578,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82798,11 +84590,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82814,36 +84606,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82851,8 +84640,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82878,7 +84667,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82966,8 +84755,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82982,11 +84771,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83044,7 +84833,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83053,6 +84842,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83073,8 +84866,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83084,21 +84893,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83149,7 +84954,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83196,7 +85001,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83208,11 +85013,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83299,7 +85105,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83333,9 +85141,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83378,13 +85186,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83469,8 +85277,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83478,15 +85289,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83516,15 +85320,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83532,16 +85341,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83564,7 +85372,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83591,7 +85399,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83657,7 +85469,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83673,7 +85485,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83708,14 +85521,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83726,11 +85546,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83740,12 +85561,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83802,7 +85624,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83868,9 +85690,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83959,7 +85781,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84188,7 +86010,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84296,7 +86118,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84352,11 +86174,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84371,6 +86196,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84436,7 +86262,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84457,6 +86283,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84486,24 +86313,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84513,7 +86342,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84600,7 +86429,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84609,7 +86438,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84629,7 +86458,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84649,27 +86478,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84677,7 +86498,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84688,22 +86509,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84743,9 +86558,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84755,17 +86571,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84815,15 +86630,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84850,7 +86665,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84863,9 +86678,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84880,15 +86695,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85079,7 +86894,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85096,7 +86911,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85104,17 +86922,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85184,7 +86999,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85194,6 +87009,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85217,7 +87038,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85228,11 +87049,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85752,7 +87607,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85765,7 +87620,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85939,16 +87801,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86097,7 +87959,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86235,7 +88097,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86575,121 +88438,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86753,16 +88612,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86780,7 +88629,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86800,25 +88650,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86827,20 +88682,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86855,12 +88708,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86923,13 +88778,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86968,11 +88846,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86981,7 +88854,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87031,7 +88904,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87047,7 +88920,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87081,6 +88954,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87093,7 +88985,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87107,17 +88999,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87166,18 +89051,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87200,9 +89086,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87273,7 +89160,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87311,9 +89199,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87338,7 +89226,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87519,12 +89407,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87550,7 +89433,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87637,6 +89522,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87657,7 +89544,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87674,94 +89562,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87774,7 +89633,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87785,13 +89648,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87802,808 +89669,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88639,7 +90518,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88649,6 +90530,142 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var server; (function (server) { @@ -88656,6 +90673,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88700,8 +90718,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88776,7 +90794,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88861,7 +90879,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -88899,8 +90917,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; + var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_6.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -88990,71 +91008,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); var ts; (function (ts) { var ScriptSnapshot; @@ -89104,6 +91057,30 @@ var ts; IndentStyle[IndentStyle["Block"] = 1] = "Block"; IndentStyle[IndentStyle["Smart"] = 2] = "Smart"; })(IndentStyle = ts.IndentStyle || (ts.IndentStyle = {})); + /* @internal */ + ts.testFormatSettings = { + baseIndentSize: 0, + indentSize: 4, + tabSize: 4, + newLineCharacter: "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterConstructor: false, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceAfterTypeAssertion: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + insertSpaceBeforeTypeAnnotation: false + }; var SymbolDisplayPartKind; (function (SymbolDisplayPartKind) { SymbolDisplayPartKind[SymbolDisplayPartKind["aliasName"] = 0] = "aliasName"; @@ -89319,8 +91296,9 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 149 /* Parameter */: case 235 /* VariableDeclaration */: + return ts.isInJSFile(node) && ts.getJSDocEnumTag(node) ? 7 /* All */ : 1 /* Value */; + case 149 /* Parameter */: case 184 /* BindingElement */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: @@ -89377,7 +91355,7 @@ var ts; if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 252 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */ || node.parent.kind === 257 /* ExternalModuleReference */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -89499,6 +91477,13 @@ var ts; return undefined; } ts.getTargetLabel = getTargetLabel; + function hasPropertyAccessExpressionWithName(node, funcName) { + if (!ts.isPropertyAccessExpression(node.expression)) { + return false; + } + return node.expression.name.text === funcName; + } + ts.hasPropertyAccessExpressionWithName = hasPropertyAccessExpressionWithName; function isJumpStatementTarget(node) { return node.kind === 71 /* Identifier */ && ts.isBreakOrContinueStatement(node.parent) && node.parent.label === node; } @@ -89629,7 +91614,7 @@ var ts; case 249 /* NamespaceImport */: return "alias" /* alias */; case 202 /* BinaryExpression */: - var kind = ts.getSpecialPropertyAssignmentKind(node); + var kind = ts.getAssignmentDeclarationKind(node); var right = node.right; switch (kind) { case 0 /* None */: @@ -89993,7 +91978,7 @@ var ts; ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; function find(n) { - if (isNonWhitespaceToken(n)) { + if (isNonWhitespaceToken(n) && n.kind !== 1 /* EndOfFileToken */) { return n; } var children = n.getChildren(sourceFile); @@ -90011,8 +91996,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); + var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_2 && findRightmostToken(candidate_2, sourceFile); } else { // candidate should be in this node @@ -90020,15 +92005,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); - return candidate && findRightmostToken(candidate, sourceFile); - } + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + return candidate && findRightmostToken(candidate, sourceFile); } } ts.findPrecedingToken = findPrecedingToken; @@ -90250,7 +92233,7 @@ var ts; function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth(sourceFile) !== 0; + return n.kind === 1 /* EndOfFileToken */ ? !!n.jsDoc : n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; @@ -90364,7 +92347,7 @@ var ts; } ts.createTextSpanFromNode = createTextSpanFromNode; function createTextRangeFromNode(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile), node.end); + return ts.createRange(node.getStart(sourceFile), node.end); } ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { @@ -90372,7 +92355,7 @@ var ts; } ts.createTextSpanFromRange = createTextSpanFromRange; function createTextRangeFromSpan(span) { - return ts.createTextRange(span.start, span.start + span.length); + return ts.createRange(span.start, span.start + span.length); } ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { @@ -90514,6 +92497,13 @@ var ts; }); } ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function isObjectBindingElementWithoutPropertyName(bindingElement) { + return ts.isBindingElement(bindingElement) && + ts.isObjectBindingPattern(bindingElement.parent) && + ts.isIdentifier(bindingElement.name) && + !bindingElement.propertyName; + } + ts.isObjectBindingElementWithoutPropertyName = isObjectBindingElementWithoutPropertyName; function getPropertySymbolFromBindingElement(checker, bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); @@ -90883,7 +92873,7 @@ var ts; function getSynthesizedDeepCloneWithRenames(node, includeTrivia, renameMap, checker, callback) { if (includeTrivia === void 0) { includeTrivia = true; } var clone; - if (node && ts.isIdentifier(node) && renameMap && checker) { + if (ts.isIdentifier(node) && renameMap && checker) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { @@ -90891,11 +92881,11 @@ var ts; } } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) + if (callback && clone) callback(node, clone); return clone; } @@ -90906,14 +92896,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_7 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_7)) { - clone_7.textSourceNode = node; + var clone_8 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_8)) { + clone_8.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_7)) { - clone_7.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_8)) { + clone_8.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_7, node); + return ts.setTextRange(clone_8, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -91273,7 +93263,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -91282,8 +93272,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -92040,9 +94030,42 @@ var ts; } } } + // check for a version redirect + var packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + var packageJson = ts.readJson(packageJsonPath, host); + var typesVersions = packageJson.typesVersions; + if (typeof typesVersions === "object") { + var versionResult = ts.getPackageJsonTypesVersionsPaths(typesVersions); + var versionPaths = versionResult && versionResult.paths; + var rest = absolutePath.slice(ts.ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result, fragment, baseDirectory, fileExtensions, paths, host) { + for (var path in paths) { + if (!ts.hasProperty(paths, path)) + continue; + var patterns = paths[path]; + if (patterns) { + var _loop_10 = function (name, kind) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === name; })) { + result.push(nameAndKind(name, kind)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { + var _b = _a[_i], name = _b.name, kind = _b.kind; + _loop_10(name, kind); + } + } + } + } /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -92056,27 +94079,15 @@ var ts; var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); - var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - for (var path in paths) { - var patterns = paths[path]; - if (paths.hasOwnProperty(path) && patterns) { - var _loop_11 = function (name, kind) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(function (entry) { return entry.name === name; })) { - result.push(nameAndKind(name, kind)); - } - }; - for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { - var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_11(name, kind); - } - } + var absolute = ts.normalizePath(ts.combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; - for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { - var ambientName = _d[_c]; + for (var _i = 0, _a = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _i < _a.length; _i++) { + var ambientName = _a[_i]; result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); @@ -92085,15 +94096,15 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_11 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); } }; - for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { - var moduleName = _f[_e]; - _loop_12(moduleName); + for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { + var moduleName = _c[_b]; + _loop_11(moduleName); } } if (!foundGlobal) { @@ -92202,7 +94213,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var typesName = _a[_i]; - var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + var moduleName = ts.unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -92235,7 +94246,7 @@ var ts; var typeDirectory = directories_2[_i]; typeDirectory = ts.normalizePath(typeDirectory); var directoryName = ts.getBaseFileName(typeDirectory); - var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + var moduleName = ts.unmangleScopedPackageName(directoryName); pushResult(moduleName); } } @@ -92259,6 +94270,18 @@ var ts; }); return paths; } + function findPackageJson(directory, host) { + var packageJson; + ts.forEachAncestorDirectory(directory, function (ancestor) { + if (ancestor === "node_modules") + return true; + packageJson = ts.findConfigFile(ancestor, function (f) { return tryFileExists(host, f); }, "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } function enumerateNodeModulesVisibleToScript(host, scriptPath) { if (!host.readFile || !host.fileExists) return ts.emptyArray; @@ -92366,11 +94389,12 @@ var ts; var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; - KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["All"] = 1] = "All"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 2] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 3] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -92386,7 +94410,7 @@ var ts; return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); - if (triggerCharacter && (!contextToken || !isValidTrigger(sourceFile, triggerCharacter, contextToken, position))) + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) @@ -92471,7 +94495,7 @@ var ts; var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { @@ -92479,22 +94503,23 @@ var ts; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - // TODO add filter for keyword based on type/value/namespace and also location - // Add all keywords if - // - this is not a member completion list (all the keywords) - // - other filters are enabled in required scenario so add those keywords - var isMemberCompletion = isMemberCompletionKind(completionKind); - if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { - ts.addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== 0 /* None */) { + var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); + for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + var keywordEntry = _a[_i]; + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } } - for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { - var literal = literals_1[_i]; + for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { + var literal = literals_1[_b]; entries.push(createCompletionEntryForLiteral(literal)); } - return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } function isUncheckedFile(sourceFile, compilerOptions) { - return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + return ts.isSourceFileJS(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind) { switch (kind) { @@ -92506,14 +94531,14 @@ var ts; return false; } } - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { entries.push({ name: realName, kind: "warning" /* warning */, @@ -92578,6 +94603,9 @@ var ts; }; } function quote(text, preferences) { + if (/^\d+$/.test(text)) { + return text; + } var quoted = JSON.stringify(text); switch (preferences.quotePreference) { case undefined: @@ -92663,11 +94691,12 @@ var ts; StringLiteralCompletionKind[StringLiteralCompletionKind["Types"] = 2] = "Types"; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { - switch (node.parent.kind) { + var parent = node.parent; + switch (parent.kind) { case 180 /* LiteralType */: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case 162 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent)), isNewIdentifier: false }; case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { @@ -92675,16 +94704,21 @@ var ts; // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(parent.parent.objectType)); case 181 /* ImportType */: return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case 171 /* UnionType */: - return ts.isTypeReferenceNode(node.parent.parent.parent) ? { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent)), isNewIdentifier: false } : undefined; + case 171 /* UnionType */: { + if (!ts.isTypeReferenceNode(parent.parent.parent)) + return undefined; + var alreadyUsedTypes_1 = getAlreadyUsedTypesInStringLiteralUnion(parent.parent, parent); + var types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent)).filter(function (t) { return !ts.contains(alreadyUsedTypes_1, t.value); }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: false }; + } default: return undefined; } case 273 /* PropertyAssignment */: - if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { + if (ts.isObjectLiteralExpression(parent.parent) && parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -92697,11 +94731,11 @@ var ts; // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case 188 /* ElementAccessExpression */: { - var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + var _a = parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -92715,7 +94749,7 @@ var ts; } case 189 /* CallExpression */: case 190 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(parent)) { var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -92742,6 +94776,11 @@ var ts; return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } + function getAlreadyUsedTypesInStringLiteralUnion(union, current) { + return ts.mapDefined(union.types, function (type) { + return type !== current && ts.isLiteralTypeNode(type) && ts.isStringLiteral(type.literal) ? type.literal.text : undefined; + }); + } function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { var isNewIdentifier = false; var uniques = ts.createMap(); @@ -93150,7 +95189,10 @@ var ts; break; case 71 /* Identifier */: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !parent.initializer && + ts.findChildOfKind(parent, 58 /* EqualsToken */, sourceFile)) { isJsxInitializer = previousToken; } } @@ -93172,6 +95214,7 @@ var ts; tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -93180,6 +95223,7 @@ var ts; symbols = [tagSymbol]; } completionKind = 3 /* MemberLike */; + keywordFilters = 0 /* None */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -93317,7 +95361,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter - keywordFilters = 3 /* ConstructorParameterKeywords */; + keywordFilters = 4 /* ConstructorParameterKeywords */; return 1 /* Success */; } function tryGetJsxCompletionSymbols() { @@ -93332,9 +95376,7 @@ var ts; return 1 /* Success */; } function getGlobalCompletions() { - if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { - keywordFilters = 4 /* FunctionLikeBodyKeywords */; - } + keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; // Get all entities in the current scope. completionKind = 1 /* Global */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); @@ -93371,7 +95413,7 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 277 /* SourceFile */) { @@ -93399,12 +95441,12 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (ts.programContainsEs6Modules(program)) + return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } @@ -93423,7 +95465,7 @@ var ts; var isTypeOnlyCompletion = insideJsDocTagTypeExpression || !isContextTokenValueLocation(contextToken) && (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)); var allowTypes = isTypeOnlyCompletion || !isContextTokenValueLocation(contextToken) && ts.isPossiblyTypeArgumentPosition(contextToken, sourceFile, typeChecker); if (isTypeOnlyCompletion) - keywordFilters = 5 /* TypeKeywords */; + keywordFilters = 6 /* TypeKeywords */; ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok @@ -93444,7 +95486,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } function isContextTokenValueLocation(contextToken) { @@ -93474,7 +95516,7 @@ var ts; symbol = symbol.exportSymbol || symbol; // This is an alias, follow what it aliases symbol = ts.skipAlias(symbol, typeChecker); - if (symbol.flags & 67901928 /* Type */) { + if (symbol.flags & 67897832 /* Type */) { return true; } if (symbol.flags & 1536 /* Module */) { @@ -93498,6 +95540,13 @@ var ts; if (!ts.addToSeen(seenResolvedModules, ts.getSymbolId(resolvedModuleSymbol))) { return; } + if (resolvedModuleSymbol !== moduleSymbol && + // Don't add another completion for `export =` of a symbol that's already global. + // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. + ts.some(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + symbols.push(resolvedModuleSymbol); + symbolToOriginInfoMap[ts.getSymbolId(resolvedModuleSymbol)] = { kind: 3 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: false }; + } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. @@ -93733,7 +95782,8 @@ var ts; completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; - keywordFilters = ts.isClassLike(decl) ? 1 /* ClassElementKeywords */ : 2 /* InterfaceElementKeywords */; + keywordFilters = contextToken.kind === 39 /* AsteriskToken */ ? 0 /* None */ : + ts.isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; // If you're in an interface you don't want to repeat things from super-interface. So just stop here. if (!ts.isClassLike(decl)) return 1 /* Success */; @@ -93767,14 +95817,19 @@ var ts; */ function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { + var parent = contextToken.parent; switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | case 26 /* CommaToken */: // const x = { a: 0, | - var parent = contextToken.parent; if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; + case 39 /* AsteriskToken */: + return ts.isMethodDeclaration(parent) ? ts.tryCast(parent.parent, ts.isObjectLiteralExpression) : undefined; + case 71 /* Identifier */: + return contextToken.text === "async" && ts.isShorthandPropertyAssignment(contextToken.parent) + ? contextToken.parent.parent : undefined; } } return undefined; @@ -93928,10 +95983,7 @@ var ts; containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromObjectTypeDeclaration(contextToken)) { - return false; - } - // falls through + return !isFromObjectTypeDeclaration(contextToken); case 75 /* ClassKeyword */: case 83 /* EnumKeyword */: case 109 /* InterfaceKeyword */: @@ -93943,6 +95995,8 @@ var ts; case 116 /* YieldKeyword */: case 139 /* TypeKeyword */: // type htm| return true; + case 39 /* AsteriskToken */: + return ts.isFunctionLike(contextToken.parent) && !ts.isMethodDeclaration(contextToken.parent); } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here @@ -93963,7 +96017,6 @@ var ts; // Previous token may have been a keyword that was converted to an identifier. switch (keywordForNode(contextToken)) { case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: case 75 /* ClassKeyword */: case 76 /* ConstKeyword */: case 124 /* DeclareKeyword */: @@ -93978,6 +96031,8 @@ var ts; case 104 /* VarKeyword */: case 116 /* YieldKeyword */: return true; + case 120 /* AsyncKeyword */: + return ts.isPropertyDeclaration(contextToken.parent); } return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent) @@ -94151,17 +96206,19 @@ var ts; var kind = ts.stringToToken(entry.name); switch (keywordFilter) { case 0 /* None */: - // "undefined" is a global variable, so don't need a keyword completion for it. - return kind !== 140 /* UndefinedKeyword */; - case 1 /* ClassElementKeywords */: + return false; + case 1 /* All */: + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === 124 /* DeclareKeyword */ || kind === 129 /* ModuleKeyword */ + || ts.isTypeKeyword(kind) && kind !== 140 /* UndefinedKeyword */; + case 2 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* InterfaceElementKeywords */: + case 3 /* InterfaceElementKeywords */: return isInterfaceOrTypeLiteralCompletionKeyword(kind); - case 3 /* ConstructorParameterKeywords */: + case 4 /* ConstructorParameterKeywords */: return ts.isParameterPropertyModifier(kind); - case 4 /* FunctionLikeBodyKeywords */: + case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); - case 5 /* TypeKeywords */: + case 6 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); @@ -94184,7 +96241,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 120 /* AsyncKeyword */ || !isClassMemberCompletionKeyword(kind); + return kind === 120 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -94256,7 +96313,7 @@ var ts; if (!isFromObjectTypeDeclaration(contextToken)) return undefined; var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; - return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + return (isValidKeyword(contextToken.kind) || contextToken.kind === 39 /* AsteriskToken */ || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 ? contextToken.parent.parent : undefined; } } @@ -94276,14 +96333,14 @@ var ts; case "'": case "`": // Only automatically bring up completions if this is an opening quote. - return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + return !!contextToken && isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; case "<": // Opening JSX tag - return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + return !!contextToken && contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); case "/": - return ts.isStringLiteralLike(contextToken) + return !!contextToken && (ts.isStringLiteralLike(contextToken) ? !!ts.tryGetImportFromModuleSpecifier(contextToken) - : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent)); default: return ts.Debug.assertNever(triggerCharacter); } @@ -94748,9 +96805,6 @@ var ts; // for those settings. var buckets = ts.createMap(); var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getKeyForCompilationSettings(settings) { - return "_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths); - } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { @@ -94795,7 +96849,7 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); - var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target || 1 /* ES5 */; if (!entry && externalCache) { var sourceFile = externalCache.getDocument(key, path); if (sourceFile) { @@ -94809,7 +96863,7 @@ var ts; } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); if (externalCache) { externalCache.setDocument(key, path, sourceFile); } @@ -94876,6 +96930,9 @@ var ts; }; } ts.createDocumentRegistryInternal = createDocumentRegistryInternal; + function getKeyForCompilationSettings(settings) { + return ts.sourceFileAffectingCompilerOptions.map(function (option) { return ts.getCompilerOptionValue(settings, option); }).join("|"); + } })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -95161,8 +97218,8 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var referencingFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var referencingFile = sourceFiles_3[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { @@ -95192,8 +97249,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -95312,7 +97369,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95457,8 +97514,25 @@ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { - function nodeEntry(node, isInString) { - return { type: "node", node: node.name || node, isInString: isInString }; + var DefinitionKind; + (function (DefinitionKind) { + DefinitionKind[DefinitionKind["Symbol"] = 0] = "Symbol"; + DefinitionKind[DefinitionKind["Label"] = 1] = "Label"; + DefinitionKind[DefinitionKind["Keyword"] = 2] = "Keyword"; + DefinitionKind[DefinitionKind["This"] = 3] = "This"; + DefinitionKind[DefinitionKind["String"] = 4] = "String"; + })(DefinitionKind = FindAllReferences.DefinitionKind || (FindAllReferences.DefinitionKind = {})); + var EntryKind; + (function (EntryKind) { + EntryKind[EntryKind["Span"] = 0] = "Span"; + EntryKind[EntryKind["Node"] = 1] = "Node"; + EntryKind[EntryKind["StringLiteral"] = 2] = "StringLiteral"; + EntryKind[EntryKind["SearchedLocalFoundProperty"] = 3] = "SearchedLocalFoundProperty"; + EntryKind[EntryKind["SearchedPropertyFoundLocal"] = 4] = "SearchedPropertyFoundLocal"; + })(EntryKind = FindAllReferences.EntryKind || (FindAllReferences.EntryKind = {})); + function nodeEntry(node, kind) { + if (kind === void 0) { kind = 1 /* Node */; } + return { kind: kind, node: node.name || node }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { @@ -95490,9 +97564,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { - var result_6 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); - return result_6; + var result_7 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); + return result_7; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -95505,10 +97579,10 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { - return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); + function findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, convertEntry) { + return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), function (entry) { return convertEntry(entry, node); }); } - FindAllReferences.findReferencedEntries = findReferencedEntries; + FindAllReferences.findReferenceOrRenameEntries = findReferenceOrRenameEntries; function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } @@ -95521,28 +97595,28 @@ var ts; function definitionToReferencedSymbolDefinitionInfo(def, checker, originalNode) { var info = (function () { switch (def.type) { - case "symbol": { + case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } - case "label": { + case 1 /* Label */: { var node_3 = def.node; return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } - case "keyword": { + case 2 /* Keyword */: { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } - case "this": { + case 3 /* This */: { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } - case "string": { + case 4 /* String */: { var node_6 = def.node; return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } @@ -95560,24 +97634,61 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } + function toRenameLocation(entry, originalNode) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { - if (entry.type === "span") { - return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; + var _a = entryToDocumentSpan(entry), textSpan = _a.textSpan, fileName = _a.fileName; + if (entry.kind === 0 /* Span */) { + return { textSpan: textSpan, fileName: fileName, isWriteAccess: false, isDefinition: false }; } - var node = entry.node, isInString = entry.isInString; - var sourceFile = node.getSourceFile(); + var kind = entry.kind, node = entry.node; return { - fileName: sourceFile.fileName, - textSpan: getTextSpan(node, sourceFile), + textSpan: textSpan, + fileName: fileName, isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ - || ts.isAnyDeclarationName(node) + || !!ts.getDeclarationFromName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString, + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; } + FindAllReferences.toReferenceEntry = toReferenceEntry; + function entryToDocumentSpan(entry) { + if (entry.kind === 0 /* Span */) { + return { textSpan: entry.textSpan, fileName: entry.fileName }; + } + else { + var sourceFile = entry.node.getSourceFile(); + return { textSpan: getTextSpan(entry.node, sourceFile), fileName: sourceFile.fileName }; + } + } + function getPrefixAndSuffixText(entry, originalNode) { + if (entry.kind !== 0 /* Span */ && ts.isIdentifier(originalNode)) { + var node = entry.node, kind = entry.kind; + var name = originalNode.text; + var isShorthandAssignment = ts.isShorthandPropertyAssignment(node.parent); + if (isShorthandAssignment || ts.isObjectBindingElementWithoutPropertyName(node.parent)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: name + ": " }; + } + } + } + return ts.emptyOptions; + } function toImplementationLocation(entry, checker) { - if (entry.type === "node") { + if (entry.kind !== 0 /* Span */) { var node = entry.node; var sourceFile = node.getSourceFile(); return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); @@ -95609,17 +97720,17 @@ var ts; } } function toHighlightSpan(entry) { - if (entry.type === "span") { + if (entry.kind === 0 /* Span */) { var fileName = entry.fileName, textSpan = entry.textSpan; return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } - var node = entry.node, isInString = entry.isInString; + var node = entry.node, kind = entry.kind; var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, - isInString: isInString + isInString: kind === 2 /* StringLiteral */ ? true : undefined, }; return { fileName: sourceFile.fileName, span: span }; } @@ -95635,7 +97746,62 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node) { - return node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isWriteAccess(node); + var decl = ts.getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === 79 /* DefaultKeyword */ || ts.isWriteAccess(node); + } + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl) { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & 4194304 /* Ambient */)) + return true; + switch (decl.kind) { + case 202 /* BinaryExpression */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 79 /* DefaultKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 255 /* ExportSpecifier */: + case 248 /* ImportClause */: // default import + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 239 /* InterfaceDeclaration */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocTypedefTag */: + case 265 /* JsxAttribute */: + case 242 /* ModuleDeclaration */: + case 245 /* NamespaceExportDeclaration */: + case 249 /* NamespaceImport */: + case 149 /* Parameter */: + case 274 /* ShorthandPropertyAssignment */: + case 240 /* TypeAliasDeclaration */: + case 148 /* TypeParameter */: + return true; + case 273 /* PropertyAssignment */: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(decl.parent); + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return !!decl.body; + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + return !!decl.initializer || ts.isCatchClause(decl.parent); + case 153 /* MethodSignature */: + case 151 /* PropertySignature */: + case 303 /* JSDocPropertyTag */: + case 297 /* JSDocParameterTag */: + return false; + default: + return ts.Debug.failBadSyntaxKind(decl); + } } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -95699,11 +97865,11 @@ var ts; } } // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. - return { type: "node", node: reference.literal }; + return FindAllReferences.nodeEntry(reference.literal); } else { return { - type: "span", + kind: 0 /* Span */, fileName: reference.referencingFile.fileName, textSpan: ts.createTextSpanFromRange(reference.ref), }; @@ -95717,7 +97883,7 @@ var ts; break; case 242 /* ModuleDeclaration */: if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push({ type: "node", node: decl.name }); + references.push(FindAllReferences.nodeEntry(decl.name)); } break; default: @@ -95725,7 +97891,7 @@ var ts; ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; + return references.length ? [{ definition: { type: 0 /* Symbol */, symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -95763,7 +97929,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -95894,15 +98060,15 @@ var ts; var references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references: references }); + this.result.push({ definition: { type: 0 /* Symbol */, symbol: searchSymbol }, references: references }); } - return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; + return function (node, kind) { return references.push(FindAllReferences.nodeEntry(node, kind)); }; }; /** Add a reference with no associated definition. */ State.prototype.addStringOrCommentReference = function (fileName, textSpan) { this.result.push({ definition: undefined, - references: [{ type: "span", fileName: fileName, textSpan: textSpan }] + references: [{ kind: 0 /* Span */, fileName: fileName, textSpan: textSpan }] }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ @@ -96005,19 +98171,6 @@ var ts; ? checker.getPropertySymbolOfDestructuringAssignment(location) : undefined; } - function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); - if (bindingElement && - bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && - ts.isIdentifier(bindingElement.name) && - !bindingElement.propertyName) { - return bindingElement; - } - } - function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); - } /** * Determines the smallest scope in which a symbol may have named references. * Note that not every construct has been accounted for. This function can @@ -96047,7 +98200,7 @@ var ts; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (getObjectBindingElementWithoutPropertyName(symbol)) { + if (declarations.some(ts.isObjectBindingElementWithoutPropertyName)) { return undefined; } /* @@ -96062,8 +98215,8 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out @@ -96112,8 +98265,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { - var sourceFile = sourceFiles_7[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var sourceFile = sourceFiles_5[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -96170,7 +98323,7 @@ var ts; // Only pick labels that are either the target label, or have a target that is the target label return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "label", node: targetLabel }, references: references }]; + return [{ definition: { type: 1 /* Label */, node: targetLabel }, references: references }]; } function isValidReferencePosition(node, searchSymbolName) { // Compare the length so we filter out strict superstrings of the symbol we are looking for @@ -96197,7 +98350,7 @@ var ts; return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; + return references.length ? [{ definition: { type: 2 /* Keyword */, node: references[0].node }, references: references }] : undefined; } function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { if (addReferencesHere === void 0) { addReferencesHere = true; } @@ -96367,12 +98520,13 @@ var ts; } } function addReference(referenceLocation, relatedSymbol, state) { - var addRef = state.referenceAdder(relatedSymbol); + var _a = "kind" in relatedSymbol ? relatedSymbol : { kind: undefined, symbol: relatedSymbol }, kind = _a.kind, symbol = _a.symbol; + var addRef = state.referenceAdder(symbol); if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { - addRef(referenceLocation); + addRef(referenceLocation, kind); } } /** Adds references when a constructor is used with `new this()` in its own class and `super()` calls in subclasses. */ @@ -96602,7 +98756,7 @@ var ts; // and has the same static qualifier as the original 'super's owner. return container && (32 /* Static */ & ts.getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? FindAllReferences.nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references: references }]; + return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); @@ -96660,8 +98814,9 @@ var ts; } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); + var thisParameter = ts.firstDefined(references, function (r) { return ts.isParameter(r.node.parent) ? r.node : undefined; }); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: 3 /* This */, node: thisParameter || thisOrSuperKeyword }, references: references }]; } @@ -96669,39 +98824,25 @@ var ts; var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { - return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, 2 /* StringLiteral */) : undefined; }); }); return [{ - definition: { type: "string", node: node }, + definition: { type: 4 /* String */, node: node }, references: references }]; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is in a context sensitive location (i.e. in an object literal) try - // to get a contextual type for it, and add the property symbol from the contextual - // type to the search set - var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); - var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), fromRoot); - if (res_1) - return res_1; - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - var res1 = propertySymbol && cbSymbol(propertySymbol); - if (res1) - return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -96713,8 +98854,26 @@ var ts; * so that when matching with potential reference symbol, both symbols from property declaration and variable declaration * will be included correctly. */ - var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); // gets the local symbol + if (shorthandValueSymbol && isForRenamePopulateSearchSymbolSet) { + // When renaming 'x' in `const o = { x }`, just rename the local variable, not the property. + return cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); + } + // If the location is in a context sensitive location (i.e. in an object literal) try + // to get a contextual type for it, and add the property symbol from the contextual + // type to the search set + var contextualType = checker.getContextualType(containingObjectLiteralElement.parent); + var res_1 = contextualType && ts.firstDefined(ts.getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker, contextualType, /*unionSymbolOk*/ true), function (sym) { return fromRoot(sym, 4 /* SearchedPropertyFoundLocal */); }); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 4 /* SearchedPropertyFoundLocal */); + if (res1) + return res1; + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, 3 /* SearchedLocalFoundProperty */); if (res2) return res2; } @@ -96727,11 +98886,13 @@ var ts; ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If this is symbol of binding element without propertyName declaration in Object binding pattern - // Include the property in the search - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); - function fromRoot(sym) { + // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. + // Don't do this when populating search set for a rename -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + function fromRoot(sym, kind) { // If this is a union property: // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. @@ -96739,19 +98900,19 @@ var ts; // - In populateSearchSymbolsSet, add the root the list // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - return cbSymbol(sym, rootSymbol) + return cbSymbol(sym, rootSymbol, /*baseSymbol*/ undefined, kind) // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) - ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base, kind); }) : undefined); }); } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. - ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, /*allowBaseTypes*/ function (rootSymbol) { return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); @@ -96777,8 +98938,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -96840,14 +99001,14 @@ var ts; /* @internal */ var ts; (function (ts) { - function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, _preferences, sourceMapper) { var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); - updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } ts.getEditsForFileRename = getEditsForFileRename; @@ -96943,9 +99104,9 @@ var ts; return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); } } - function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_13 = function (sourceFile) { + var _loop_12 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -96971,13 +99132,13 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) : undefined; }); }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_13(sourceFile); + _loop_12(sourceFile); } } function combineNormal(pathA, pathB) { @@ -97001,16 +99162,23 @@ var ts; } } function getSourceFileToImportFromResolved(resolved, oldToNew, host) { - return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); - function getIfExists(oldLocation) { - var newLocation = oldToNew(oldLocation); - return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); + function tryEach(cb) { + return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + } + function tryGetNewFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + } + function tryGetOldFile(oldFileName) { + var newFileName = oldToNew(oldFileName); + return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { - for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + for (var _i = 0, _a = sourceFile.referencedFiles || ts.emptyArray; _i < _a.length; _i++) { // TODO: GH#26162 var ref = _a[_i]; var updated = updateRef(ref.fileName); if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) @@ -97024,7 +99192,7 @@ var ts; } } function createStringRange(node, sourceFile) { - return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + return ts.createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { if (!ts.isObjectLiteralExpression(objectLiteral)) @@ -97066,7 +99234,7 @@ var ts; } var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); // Don't go to the component constructor definition for a JSX element, just go to the component definition. - if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); // For a function, if this is the original function definition, return just sigInfo. // If this is the original constructor definition, parent is the class. @@ -97332,6 +99500,16 @@ var ts; // Don't go to a function type, go to the value having that type. return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } + function isConstructorLike(node) { + switch (node.kind) { + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return true; + default: + return false; + } + } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); /* @internal */ @@ -97542,7 +99720,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +99753,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +99816,7 @@ var ts; // * if the caret was directly in front of the object, then we add an extra line and indentation. var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, ts.hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; @@ -97698,7 +99876,7 @@ var ts; return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; case 202 /* BinaryExpression */: { var be = commentOwner; - if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { + if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { return "quit"; } var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; @@ -97741,7 +99919,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_14 = function (sourceFile) { + var _loop_13 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -97751,9 +99929,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { - var sourceFile = sourceFiles_8[_i]; - _loop_14(sourceFile); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + _loop_13(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -97766,8 +99944,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -98090,7 +100268,7 @@ var ts; addLeafNode(node); break; case 202 /* BinaryExpression */: { - var special = ts.getSpecialPropertyAssignmentKind(node); + var special = ts.getAssignmentDeclarationKind(node); switch (special) { case 1 /* ExportsProperty */: case 2 /* ModuleExports */: @@ -98416,28 +100594,49 @@ var ts; return ts.getNodeModifiers(node); } function getFunctionOrClassName(node) { + var parent = node.parent; if (node.name && ts.getFullWidth(node.name) > 0) { return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 235 /* VariableDeclaration */) { - return ts.declarationNameToString(node.parent.name); + else if (ts.isVariableDeclaration(parent)) { + return ts.declarationNameToString(parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 202 /* BinaryExpression */ && - node.parent.operatorToken.kind === 58 /* EqualsToken */) { - return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); + else if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */) { + return nodeText(parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { - return nodeText(node.parent.name); + else if (ts.isPropertyAssignment(parent)) { + return nodeText(parent.name); } // Default exports are named "default" else if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } + else if (ts.isClassLike(node)) { + return ""; + } + else if (ts.isCallExpression(parent)) { + var name = getCalledExpressionName(parent.expression); + if (name !== undefined) { + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + return name + "(" + args + ") callback"; + } + } + return ""; + } + function getCalledExpressionName(expr) { + if (ts.isIdentifier(expr)) { + return expr.text; + } + else if (ts.isPropertyAccessExpression(expr)) { + var left = getCalledExpressionName(expr.expression); + var right = expr.name.text; + return left === undefined ? right : left + "." + right; + } else { - return ts.isClassLike(node) ? "" : ""; + return undefined; } } function isFunctionOrClassExpression(node) { @@ -99248,13 +101447,13 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_15 = function (start) { + var _loop_14 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_15(start); + var state_3 = _loop_14(start); if (typeof state_3 === "object") return state_3.value; } @@ -99794,9 +101993,9 @@ var ts; if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { return undefined; } - // Can't rename a module name. - if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) - return undefined; + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 147 /* ComputedPropertyName */) ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) @@ -99805,28 +102004,42 @@ var ts; var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node, sourceFile, moduleSymbol) { + if (!ts.isExternalModuleNameRelative(node.text)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_a_module_via_a_global_import); + } + var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (!moduleSourceFile) + return undefined; + var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; + var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; + // Span should only be the last component of the path. + 1 to account for the quote character. + var triggerSpan = ts.createTextSpan(node.getStart(sourceFile) + 1 + indexAfterLastSlash, node.text.length - indexAfterLastSlash); + return { + canRename: true, + fileToRename: name, + kind: kind, + displayName: name, + fullDisplayName: name, + kindModifiers: "" /* none */, + triggerSpan: triggerSpan, + }; + } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { canRename: true, + fileToRename: undefined, kind: kind, displayName: displayName, - localizedErrorMessage: undefined, fullDisplayName: fullDisplayName, kindModifiers: kindModifiers, triggerSpan: createTriggerSpanForNode(node, sourceFile) }; } function getRenameInfoError(diagnostic) { - // TODO: GH#18217 - return { - canRename: false, - localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), - displayName: undefined, - fullDisplayName: undefined, - kind: undefined, - kindModifiers: undefined, - triggerSpan: undefined - }; + return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic) }; } function createTriggerSpanForNode(node, sourceFile) { var start = node.getStart(sourceFile); @@ -99877,22 +102090,32 @@ var ts; if (onlyUseSyntacticOwners && (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position))) { return undefined; } - var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker); + var isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; + var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); // Extra syntactic and semantic filtering of signature help - var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); + var candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return ts.isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return ts.isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } - return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return candidateInfo.kind === 0 /* Candidate */ + ? createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker) + : createTypeHelpItems(candidateInfo.symbol, argumentInfo, sourceFile, typeChecker); + }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function getCandidateInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var CandidateOrTypeKind; + (function (CandidateOrTypeKind) { + CandidateOrTypeKind[CandidateOrTypeKind["Candidate"] = 0] = "Candidate"; + CandidateOrTypeKind[CandidateOrTypeKind["Type"] = 1] = "Type"; + })(CandidateOrTypeKind || (CandidateOrTypeKind = {})); + function getCandidateOrTypeInfo(_a, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { var invocation = _a.invocation, argumentCount = _a.argumentCount; switch (invocation.kind) { case 0 /* Call */: { @@ -99901,17 +102124,21 @@ var ts; } var candidates = []; var resolvedSignature = checker.getResolvedSignatureForSignatureHelp(invocation.node, candidates, argumentCount); // TODO: GH#18217 - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; + return candidates.length === 0 ? undefined : { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: resolvedSignature }; } case 1 /* TypeArgs */: { - if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + var called = invocation.called; + if (onlyUseSyntacticOwners && !containsPrecedingToken(startingToken, sourceFile, ts.isIdentifier(called) ? called.parent : called)) { return undefined; } - var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentCount, checker); - return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + var candidates = ts.getPossibleGenericSignatures(called, argumentCount, checker); + if (candidates.length !== 0) + return { kind: 0 /* Candidate */, candidates: candidates, resolvedSignature: ts.first(candidates) }; + var symbol = checker.getSymbolAtLocation(called); + return symbol && { kind: 1 /* Type */, symbol: symbol }; } case 2 /* Contextual */: - return { candidates: [invocation.signature], resolvedSignature: invocation.signature }; + return { kind: 0 /* Candidate */, candidates: [invocation.signature], resolvedSignature: invocation.signature }; default: return ts.Debug.assertNever(invocation); } @@ -99928,12 +102155,12 @@ var ts; return !!containingList && ts.contains(invocationChildren, containingList); } case 27 /* LessThanToken */: - return lessThanFollowsCalledExpression(startingToken, sourceFile, node.expression); + return containsPrecedingToken(startingToken, sourceFile, node.expression); default: return false; } } - function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { + function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { if (argumentInfo.invocation.kind === 2 /* Contextual */) return undefined; // See if we can find some symbol with the call expression name that has call signatures. @@ -99950,9 +102177,9 @@ var ts; }); }); } - function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + function containsPrecedingToken(startingToken, sourceFile, container) { var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); - return ts.rangeContainsRange(calledExpression, precedingToken); + return ts.rangeContainsRange(container, precedingToken); } function getArgumentInfoForCompletions(node, position, sourceFile) { var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -100238,8 +102465,8 @@ var ts; } return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } - function getContainingArgumentInfo(node, position, sourceFile, checker) { - var _loop_16 = function (n) { + function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { + var _loop_15 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -100248,8 +102475,8 @@ var ts; return { value: argumentInfo }; } }; - for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { - var state_4 = _loop_16(n); + for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { + var state_4 = _loop_15(n); if (typeof state_4 === "object") return state_4.value; } @@ -100264,10 +102491,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; function createSignatureHelpItems(candidates, resolvedSignature, _a, sourceFile, typeChecker) { var isTypeParameterList = _a.isTypeParameterList, argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; - var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + var enclosingDeclaration = getEnclosingDeclarationFromInvocation(invocation); var callTargetSymbol = invocation.kind === 2 /* Contextual */ ? invocation.symbol : typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol ? ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined) : ts.emptyArray; var items = candidates.map(function (candidateSignature) { return getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile); }); @@ -100278,11 +102508,28 @@ var ts; ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; } + function createTypeHelpItems(symbol, _a, sourceFile, checker) { + var argumentCount = _a.argumentCount, applicableSpan = _a.argumentsSpan, invocation = _a.invocation, argumentIndex = _a.argumentIndex; + var typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (!typeParameters) + return undefined; + var items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: 0, argumentIndex: argumentIndex, argumentCount: argumentCount }; + } + function getTypeHelpItem(symbol, typeParameters, checker, enclosingDeclaration, sourceFile) { + var typeSymbolDisplay = ts.symbolToDisplayParts(checker, symbol); + var printer = ts.createPrinter({ removeComments: true }); + var parameters = typeParameters.map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); + var documentation = symbol.getDocumentationComment(checker); + var tags = symbol.getJsDocTags(); + var prefixDisplayParts = typeSymbolDisplay.concat([ts.punctuationPart(27 /* LessThanToken */)]); + return { isVariadic: false, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: [ts.punctuationPart(29 /* GreaterThanToken */)], separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; + } + var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; function getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, checker, enclosingDeclaration, sourceFile) { var _a = (isTypeParameterList ? itemInfoForTypeParameters : itemInfoForParameters)(candidateSignature, checker, enclosingDeclaration, sourceFile), isVariadic = _a.isVariadic, parameters = _a.parameters, prefix = _a.prefix, suffix = _a.suffix; var prefixDisplayParts = callTargetDisplayParts.concat(prefix); var suffixDisplayParts = suffix.concat(returnTypeToDisplayParts(candidateSignature, enclosingDeclaration, checker)); - var separatorDisplayParts = [ts.punctuationPart(26 /* CommaToken */), ts.spacePart()]; var documentation = candidateSignature.getDocumentationComment(checker); var tags = candidateSignature.getJsDocTags(); return { isVariadic: isVariadic, prefixDisplayParts: prefixDisplayParts, suffixDisplayParts: suffixDisplayParts, separatorDisplayParts: separatorDisplayParts, parameters: parameters, documentation: documentation, tags: tags }; @@ -100336,7 +102583,7 @@ var ts; var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); - return { name: typeParameter.symbol.name, documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; + return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; } })(SignatureHelp = ts.SignatureHelp || (ts.SignatureHelp = {})); })(ts || (ts = {})); @@ -100460,13 +102707,13 @@ var ts; function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - var checker = program.getDiagnosticsProducingTypeChecker(); + var checker = program.getTypeChecker(); if (sourceFile.commonJsModuleIndicator && (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - var isJsFile = ts.isSourceFileJavaScript(sourceFile); + var isJsFile = ts.isSourceFileJS(sourceFile); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -100489,7 +102736,7 @@ var ts; if (isJsFile) { switch (node.kind) { case 194 /* FunctionExpression */: - var decl = ts.getDeclarationOfJSInitializer(node); + var decl = ts.getDeclarationOfExpando(node); if (decl) { var symbol_2 = decl.symbol; if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { @@ -100533,13 +102780,13 @@ var ts; switch (statement.kind) { case 217 /* VariableStatement */: return statement.declarationList.declarations.some(function (decl) { - return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); - }); // TODO: GH#18217 + return !!decl.initializer && ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); case 219 /* ExpressionStatement */: { var expression = statement.expression; if (!ts.isBinaryExpression(expression)) return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - var kind = ts.getSpecialPropertyAssignmentKind(expression); + var kind = ts.getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } default: @@ -100564,10 +102811,10 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - var functionType = node.type ? checker.getTypeFromTypeNode(node.type) : undefined; - if (ts.isAsyncFunction(node) || !node.body || !functionType) { + if (ts.isAsyncFunction(node) || !node.body) { return; } + var functionType = checker.getTypeAtLocation(node); var callSignatures = checker.getSignaturesOfType(functionType, 0 /* Call */); var returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { @@ -100577,7 +102824,7 @@ var ts; // check that a property access expression exists in there and that it is a handler var returnStatements = getReturnStatementsWithPromiseHandlers(node); if (returnStatements.length > 0) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); } } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { @@ -100596,22 +102843,45 @@ var ts; if (ts.isFunctionLike(child)) { return; } - if (ts.isReturnStatement(child)) { - ts.forEachChild(child, addHandlers); - } - function addHandlers(returnChild) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child); - } + if (ts.isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { + returnStatements.push(child); } ts.forEachChild(child, visit); } return returnStatements; } ts.getReturnStatementsWithPromiseHandlers = getReturnStatementsWithPromiseHandlers; + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node) { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + // ensure all chained calls are valid + var currentNode = node.expression; + while (isPromiseHandler(currentNode) || ts.isPropertyAccessExpression(currentNode)) { + if (ts.isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } function isPromiseHandler(node) { - return (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg) { + switch (arg.kind) { + case 95 /* NullKeyword */: + case 71 /* Identifier */: // identifier includes undefined + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return true; + default: + return false; + } } })(ts || (ts = {})); /* @internal */ @@ -100744,13 +103014,16 @@ var ts; var documentation; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); - var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); + var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isInExpressionContext(location); var type; var printer; var documentationFromAlias; var tagsFromAlias; + if (location.kind === 99 /* ThisKeyword */ && !isThisExpression) { + return { displayParts: [ts.keywordPart(99 /* ThisKeyword */)], documentation: [], symbolKind: "primitive type" /* primitiveType */, tags: undefined }; + } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -100888,7 +103161,7 @@ var ts; addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & 524288 /* TypeAlias */) { + if ((symbolFlags & 524288 /* TypeAlias */) && (semanticMeaning & 2 /* Type */)) { prefixNextMeaning(); displayParts.push(ts.keywordPart(139 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -101118,7 +103391,7 @@ var ts; if (tags.length === 0 && tagsFromAlias) { tags = tagsFromAlias; } - return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { printer = ts.createPrinter({ removeComments: true }); @@ -101190,7 +103463,8 @@ var ts; displayParts.push(ts.textPart(allSignatures.length === 2 ? "overload" : "overloads")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } - documentation = signature.getDocumentationComment(typeChecker); + var docComment = signature.getDocumentationComment(typeChecker); + documentation = docComment.length === 0 ? undefined : docComment; tags = signature.getJsDocTags(); } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -101257,6 +103531,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101330,7 +103605,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_17 = function (opt) { + var _loop_16 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -101349,7 +103624,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_17(opt); + _loop_16(opt); } return options; } @@ -102982,13 +105257,13 @@ var ts; var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { formattingScanner.advance(); - tokenInfo = formattingScanner.readTokenInfo(parent); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one // function (x: function) <-- // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + if (tokenInfo && tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { // consume list end token consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } @@ -104156,11 +106431,11 @@ var ts; }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); + this.replaceRange(sourceFile, ts.createRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, options: options, nodes: newNodes, range: { pos: pos, end: pos } }); + this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); @@ -104175,7 +106450,15 @@ var ts; }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); - this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { suffix: " " }); + }; + ChangeTracker.prototype.insertLastModifierBefore = function (sourceFile, modifier, before) { + if (!before.modifiers) { + this.insertModifierBefore(sourceFile, modifier, before); + return; + } + var pos = before.modifiers.end; + this.insertNodeAt(sourceFile, pos, ts.createToken(modifier), { prefix: " " }); }; ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); @@ -104190,11 +106473,33 @@ var ts; var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; this.insertText(sourceFile, token.getStart(sourceFile), text); }; + ChangeTracker.prototype.insertCommentThenNewline = function (sourceFile, character, position, commentText) { + var token = ts.getTouchingToken(sourceFile, position); + var text = "/**" + commentText + "*/" + this.newLineCharacter + ts.repeatString(" ", character); + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { - this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + this.replaceRangeWithText(sourceFile, ts.createRange(pos), text); + }; + ChangeTracker.prototype.tryInsertJSDocParameters = function (sourceFile, parameters) { + if (parameters.length === 0) { + return; + } + var parent = parameters[0].declaration.parent; + var indent = ts.getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; + var commentText = "\n"; + for (var _i = 0, parameters_3 = parameters; _i < parameters_3.length; _i++) { + var _a = parameters_3[_i], declaration = _a.declaration, typeNode = _a.typeNode, isOptional = _a.isOptional; + if (ts.isIdentifier(declaration.name)) { + var printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; + commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); + } + } + commentText += ts.repeatString(" ", indent + 1); + this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { @@ -104213,6 +106518,25 @@ var ts; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; + ChangeTracker.prototype.tryInsertJSDocType = function (sourceFile, node, type) { + var printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; + var commentText; + if (ts.isGetAccessorDeclaration(node)) { + commentText = " @return {" + printed + "} "; + } + else { + commentText = " @type {" + printed + "} "; + node = node.parent; + } + this.insertCommentThenNewline(sourceFile, ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); + }; + ChangeTracker.prototype.printJSDocParameter = function (indent, printed, name, isOptionalParameter) { + var printName = ts.unescapeLeadingUnderscores(name.escapedText); + if (isOptionalParameter) { + printName = "[" + printName + "]"; + } + return ts.repeatString(" ", indent) + (" * @param {" + printed + "} " + printName + "\n"); + }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter var start = (ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); @@ -104256,30 +106580,37 @@ var ts; }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); - this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, { + this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { + this.insertNodeAtStartWorker(sourceFile, cls, newElement); + }; + ChangeTracker.prototype.insertNodeAtObjectStart = function (sourceFile, obj, newElement) { + this.insertNodeAtStartWorker(sourceFile, obj, newElement); + }; + ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { var clsStart = cls.getStart(sourceFile); var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); }; - ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { - if (cls.members.length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { + var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; + if (getMembersOrProperties(cls).length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { // For `class C {\n}`, don't add the trailing "\n" - var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' - return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassOrObjectBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; } else { - return { prefix: "", suffix: this.newLineCharacter }; + return { prefix: "", suffix: comma + this.newLineCharacter }; } } else { - return { prefix: this.newLineCharacter, suffix: "" }; + return { prefix: this.newLineCharacter, suffix: comma }; } }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { @@ -104302,7 +106633,7 @@ var ts; // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); + this.replaceRange(sourceFile, ts.createRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); @@ -104427,7 +106758,7 @@ var ts; } // write separator and leading trivia of the next element as suffix var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); - this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); + this.replaceRange(sourceFile, ts.createRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -104459,7 +106790,7 @@ var ts; } if (multilineList) { // insert separator immediately following the 'after' node to preserve comments in trailing trivia - this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); + this.replaceRange(sourceFile, ts.createRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -104467,29 +106798,29 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); + this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.classesWithNodesInsertedAtStart.forEach(function (cls) { - var sourceFile = cls.getSourceFile(); - var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + this.classesWithNodesInsertedAtStart.forEach(function (_a) { + var node = _a.node, sourceFile = _a.sourceFile; + var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; // For `class C { }` remove the whitespace inside the braces. if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); } }); }; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_18 = function (sourceFile, node) { + var _loop_17 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -104502,7 +106833,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_18(sourceFile, node); + _loop_17(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -104541,9 +106872,16 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } - function getClassBraceEnds(cls, sourceFile) { + function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; } + function getMembersOrProperties(cls) { + return ts.isObjectLiteralExpression(cls) ? cls.properties : cls.members; + } + function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { + return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); + } + textChanges_3.getNewFileText = getNewFileText; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -104552,14 +106890,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_19 = function (i) { + var _loop_18 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_19(i); + _loop_18(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -104569,14 +106907,18 @@ var ts; } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this - var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); - var changes = ts.formatting.formatDocument(sourceFile, formatContext); - var text = applyChanges(nonFormattedText, changes); + var text = newFileChangesWorker(oldFile, ts.getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; } changesToText.newFileChanges = newFileChanges; + function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + return applyChanges(nonFormattedText, changes); + } + changesToText.newFileChangesWorker = newFileChangesWorker; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; @@ -104614,9 +106956,10 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = new Writer(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } + changesToText.getNonformattedText = getNonformattedText; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { @@ -105399,7 +107742,7 @@ var ts; } default: { // Don't try to declare members in JavaScript files - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { return; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, @@ -105452,57 +107795,63 @@ var ts; (function (codefix) { var fixId = "convertToAsyncFunction"; var errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; + var codeActionSucceeded = true; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + codeActionSucceeded = true; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context); }); - return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_async_function, fixId, ts.Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context); }); }, }); function convertToAsyncFunction(changes, sourceFile, position, checker, context) { // get the function declaration - returns a promise - var functionToConvert = ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)); + var tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); + var functionToConvert; + // if the parent of a FunctionLikeDeclaration is a variable declaration, the convertToAsync diagnostic will be reported on the variable name + if (ts.isIdentifier(tokenAtPosition) && ts.isVariableDeclaration(tokenAtPosition.parent) && + tokenAtPosition.parent.initializer && ts.isFunctionLikeDeclaration(tokenAtPosition.parent.initializer)) { + functionToConvert = tokenAtPosition.parent.initializer; + } + else { + functionToConvert = ts.tryCast(ts.getContainingFunction(ts.getTokenAtPosition(sourceFile, position)), ts.isFunctionLikeDeclaration); + } if (!functionToConvert) { return; } var synthNamesMap = ts.createMap(); var originalTypeMap = ts.createMap(); var allVarNames = []; - var isInJSFile = ts.isInJavaScriptFile(functionToConvert); + var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); var constIdentifiers = getConstIdentifiers(synthNamesMap); var returnStatements = ts.getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJSFile }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword - changes.insertModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); + changes.insertLastModifierBefore(sourceFile, 120 /* AsyncKeyword */, functionToConvert); function startTransformation(node, nodeToReplace) { var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_20 = function (statement) { - if (ts.isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - ts.forEachChild(statement, function visit(node) { - if (ts.isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!ts.isFunctionLike(node)) { - ts.forEachChild(node, visit); - } - }); - } + var _loop_19 = function (statement) { + ts.forEachChild(statement, function visit(node) { + if (ts.isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!ts.isFunctionLike(node)) { + ts.forEachChild(node, visit); + } + }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_20(statement); + _loop_19(statement); } } // Returns the identifiers that are never reassigned in the refactor @@ -105549,7 +107898,7 @@ var ts; */ function isPromiseReturningExpression(node, checker, name) { var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || hasPropertyAccessExpressionWithName(node, name)); + var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } @@ -105563,6 +107912,7 @@ var ts; */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { var identsToRenameMap = ts.createMap(); // key is the symbol id + var collidingSymbolMap = ts.createMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); @@ -105576,19 +107926,25 @@ var ts; var symbolIdString = ts.getSymbolId(symbol).toString(); // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary - if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - var synthName = getNewNameIfConflict(ts.createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { + var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); + var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); + var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent))) { + var originalName = node.text; + var collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(function (ident) { return ident.identifier.text === node.text && ident.symbol !== symbol; })) { - var newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(function (prevSymbol) { return prevSymbol !== symbol; })) { + var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); allVarNames.push({ identifier: newName.identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); @@ -105596,6 +107952,7 @@ var ts; synthNamesMap.set(symbolIdString, { identifier: identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/ }); if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { allVarNames.push({ identifier: identifier, symbol: symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -105618,9 +107975,7 @@ var ts; var renameInfo = symbol && synthNamesMap.get(symboldIdString); if (renameInfo) { var type = checker.getTypeAtLocation(node); - if (type) { - originalType.set(ts.getNodeId(clone).toString(), type); - } + originalType.set(ts.getNodeId(clone).toString(), type); } } var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); @@ -105630,23 +107985,32 @@ var ts; } } } - function getNewNameIfConflict(name, allVarNames) { - var numVarsSameName = allVarNames.filter(function (elem) { return elem.identifier.text === name.text; }).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName).push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + function getNewNameIfConflict(name, originalNames) { + var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); return { identifier: identifier, types: [], numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node, transformer, outermostParent, prevArgName) { if (!node) { - return []; + return ts.emptyArray; } var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformThen(node, transformer, outermostParent, prevArgName); } - else if (ts.isCallExpression(node) && hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformCatch(node, transformer, prevArgName); } else if (ts.isPropertyAccessExpression(node)) { @@ -105655,7 +108019,8 @@ var ts; else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { return transformPromiseCall(node, transformer, prevArgName); } - return []; + codeActionSucceeded = false; + return ts.emptyArray; } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; @@ -105670,17 +108035,18 @@ var ts; prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach(function (val, key) { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + var newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(function (elem) { return elem.text === prevArgName.identifier.text; })) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, prevArgName)); var transformationBody = getTransformationBody(func, prevArgName, argName, node, transformer); - var catchArg = argName.identifier.text.length > 0 ? argName.identifier.text : "e"; + var catchArg = argName ? argName.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody)); /* In order to avoid an implicit any, we will synthesize a type for the declaration using the unions of the types of both paths (try block and catch block) @@ -105696,6 +108062,11 @@ var ts; var tryStatement = ts.createTry(tryBlock, catchClause, /*finallyBlock*/ undefined); return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName) { + var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); + var newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } function transformThen(node, transformer, outermostParent, prevArgName) { var _a = node.arguments, res = _a[0], rej = _a[1]; if (!res) { @@ -105707,14 +108078,11 @@ var ts; var argNameRej = getArgName(rej, transformer); var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej.identifier.text.length > 0 ? argNameRej.identifier.text : "e"; + var catchArg = argNameRej ? argNameRej.identifier.text : "e"; var catchClause = ts.createCatchClause(catchArg, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node, constIdentifiers) { var inArr = constIdentifiers.some(function (elem) { return elem.text === node.text; }); @@ -105723,50 +108091,67 @@ var ts; function transformPromiseCall(node, transformer, prevArgName) { var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; var originalNodeParent = node.original ? node.original.parent : node.parent; - if (hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(node), transformer).concat(); // hack to make the types match + if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); } - else if (!hasPrevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { + else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { return [ts.createStatement(ts.createAwait(node))]; } return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - function createVariableDeclarationOrAssignment(prevArgName, rightHandSide, transformer) { - if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { - return ts.createNodeArray([ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]); + function createTransformedStatement(prevArgName, rightHandSide, transformer) { + if (!prevArgName || prevArgName.identifier.text.length === 0) { + // if there's no argName to assign to, there still might be side effects + return [ts.createStatement(rightHandSide)]; } - return ts.createNodeArray([ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); + if (prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + // if the variable has already been declared, we don't need "let" or "const" + return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + } + return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]; } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; - var hasArgName = argName && argName.identifier.text.length > 0; var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); switch (func.kind) { - case 71 /* Identifier */: - if (!hasArgName) + case 95 /* NullKeyword */: + // do not produce a transformed statement for a null argument + break; + case 71 /* Identifier */: // identifier includes undefined + if (!argName) { + // undefined was argument passed to promise handler break; + } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, [argName.identifier]); if (shouldReturn) { - return ts.createNodeArray([ts.createReturn(synthCall)]); + return [ts.createReturn(synthCall)]; } - if (!hasPrevArgName) + var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); + if (!callSignatures.length) { + // if identifier in handler has no call signatures, it's invalid + codeActionSucceeded = false; break; - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()); - var callSignatures = type && transformer.checker.getSignaturesOfType(type, 0 /* Call */); - var returnType = callSignatures && callSignatures[0].getReturnType(); - var varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName, ts.createAwait(synthCall), transformer); - prevArgName.types.push(returnType); + } + var returnType = callSignatures[0].getReturnType(); + var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + if (prevArgName) { + prevArgName.types.push(returnType); + } return varDeclOrAssignment; - case 237 /* FunctionDeclaration */: case 194 /* FunctionExpression */: - case 195 /* ArrowFunction */: + case 195 /* ArrowFunction */: { + var funcBody = func.body; // Arrow functions with block bodies { } will enter this control flow - if (ts.isFunctionLikeDeclaration(func) && func.body && ts.isBlock(func.body) && func.body.statements) { + if (ts.isBlock(funcBody)) { var refactoredStmts = []; - for (var _i = 0, _a = func.body.statements; _i < _a.length; _i++) { + var seenReturnStatement = false; + for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { var statement = _a[_i]; + if (ts.isReturnStatement(statement)) { + seenReturnStatement = true; + } if (ts.getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -105774,49 +108159,66 @@ var ts; refactoredStmts.push(statement); } } - return shouldReturn ? ts.getSynthesizedDeepClones(ts.createNodeArray(refactoredStmts)) : - removeReturns(ts.createNodeArray(refactoredStmts), prevArgName.identifier, transformer.constIdentifiers); + return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : + removeReturns(refactoredStmts, prevArgName === undefined ? undefined : prevArgName.identifier, transformer, seenReturnStatement); } else { - var funcBody = func.body; var innerRetStmts = ts.getReturnStatementsWithPromiseHandlers(ts.createReturn(funcBody)); var innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { - return ts.createNodeArray(innerCbBody); + return innerCbBody; } - if (hasPrevArgName && !shouldReturn) { - var type_3 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_3, transformer.checker).getReturnType(); - var varDeclOrAssignment_1 = createVariableDeclarationOrAssignment(prevArgName, ts.getSynthesizedDeepClone(funcBody), transformer); - prevArgName.types.push(returnType_1); - return varDeclOrAssignment_1; + var type_6 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var rightHandSide = ts.getSynthesizedDeepClone(funcBody); + var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; + if (!shouldReturn) { + var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (prevArgName) { + prevArgName.types.push(returnType_1); + } + return transformedStatement; } else { - return ts.createNodeArray([ts.createReturn(ts.getSynthesizedDeepClone(funcBody))]); + return [ts.createReturn(possiblyAwaitedRightHandSide)]; } } + } + default: + // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } - return ts.createNodeArray([]); + return ts.emptyArray; } function getLastCallSignature(type, checker) { - var callSignatures = type && checker.getSignaturesOfType(type, 0 /* Call */); - return callSignatures && callSignatures[callSignatures.length - 1]; + var callSignatures = checker.getSignaturesOfType(type, 0 /* Call */); + return ts.lastOrUndefined(callSignatures); } - function removeReturns(stmts, prevArgName, constIdentifiers) { + function removeReturns(stmts, prevArgName, transformer, seenReturnStatement) { var ret = []; for (var _i = 0, stmts_1 = stmts; _i < stmts_1.length; _i++) { var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, stmt.expression)], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + if (prevArgName === undefined) { + ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); + } + else { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } } } else { ret.push(ts.getSynthesizedDeepClone(stmt)); } } - return ts.createNodeArray(ret); + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement && prevArgName !== undefined) { + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(prevArgName, /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, transformer.constIdentifiers))))); + } + return ret; } function getInnerTransformationBody(transformer, innerRetStmts, prevArgName) { var innerCbBody = []; @@ -105837,12 +108239,6 @@ var ts; } return innerCbBody; } - function hasPropertyAccessExpressionWithName(node, funcName) { - if (!ts.isPropertyAccessExpression(node.expression)) { - return false; - } - return node.expression.name.text === funcName; - } function getArgName(funcNode, transformer) { var numberOfAssignmentsOriginal = 0; var types = []; @@ -105850,20 +108246,18 @@ var ts; if (ts.isFunctionLikeDeclaration(funcNode)) { if (funcNode.parameters.length > 0) { var param = funcNode.parameters[0].name; - name = getMapEntryIfExists(param); + name = getMapEntryOrDefault(param); } } - else if (ts.isCallExpression(funcNode) && funcNode.arguments.length > 0 && ts.isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0], types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; - } else if (ts.isIdentifier(funcNode)) { - name = getMapEntryIfExists(funcNode); + name = getMapEntryOrDefault(funcNode); } - if (!name || name.identifier === undefined || name.identifier.text === "_" || name.identifier.text === "undefined") { - return { identifier: ts.createIdentifier(""), types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + // return undefined argName when arg is null or undefined + if (!name || name.identifier.text === "undefined") { + return undefined; } return name; - function getMapEntryIfExists(identifier) { + function getMapEntryOrDefault(identifier) { var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { @@ -105941,7 +108335,7 @@ var ts; forEachExportReference(sourceFile, function (node) { var _a = node.name, text = _a.text, originalKeywordKind = _a.originalKeywordKind; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) - || checker.resolveName(node.name.text, node, 67216319 /* Value */, /*excludeGlobals*/ true))) { + || checker.resolveName(node.name.text, node, 67220415 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. res.set(text, makeUniqueName("_" + text, identifiers)); } @@ -106058,7 +108452,7 @@ var ts; return replacement[1]; } else { - changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + changes.replaceRangeWithText(sourceFile, ts.createRange(left.getStart(sourceFile), right.pos), "export default"); return true; } } @@ -106544,33 +108938,40 @@ var ts; ImportKind[ImportKind["Equals"] = 3] = "Equals"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getTypeChecker(), program.getSourceFiles()); + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); // We sort the best codefixes first, so taking `first` is best for completions. var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); - return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + function codeFixActionToCodeAction(_a) { + var description = _a.description, changes = _a.changes, commands = _a.commands; + return { description: description, changes: changes, commands: commands }; + } + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, compilerOptions, checker, allSourceFiles) { var result = []; forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { // Don't import from a re-export when looking "up" like to `./index` or `../index`. if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { return; } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); + } for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; - if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported) }); + if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { + result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); } } }); return result; } - function isTypeOnlySymbol(s) { - return !(s.flags & 67216319 /* Value */); + function isTypeOnlySymbol(s, checker) { + return !(ts.skipAlias(s, checker).flags & 67220415 /* Value */); } function getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); @@ -106631,24 +109032,24 @@ var ts; function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && ts.isSourceFileJavaScript(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { + return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; }); } function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position) } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; - }); }); + }); }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + // Sort to keep the shortest paths first + return choicesForEachExportingModule.sort(function (a, b) { return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); @@ -106690,7 +109091,7 @@ var ts; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. var parent = token.parent; return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) - ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67220415 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) : undefined; } function getUmdImportKind(compilerOptions) { @@ -106738,17 +109139,13 @@ var ts; // Maps symbol id to info for modules providing that symbol (original export + re-exports). var originalSymbolToExportInfos = ts.createMultiMap(); function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol) }); + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exportedSymbol, checker) }); } forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); - if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { - addSymbol(moduleSymbol, defaultExport, 1 /* Default */); - } + var defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, program.getCompilerOptions()); + if (defaultInfo && defaultInfo.name === symbolName && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultInfo.symbol, defaultInfo.kind); } // check exports with the same name var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); @@ -106758,7 +109155,22 @@ var ts; }); return originalSymbolToExportInfos; } - function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { + var exported = getDefaultLikeExportWorker(moduleSymbol, checker); + if (!exported) + return undefined; + var symbol = exported.symbol, kind = exported.kind; + var info = getDefaultExportInfoWorker(symbol, moduleSymbol, checker, compilerOptions); + return info && __assign({ symbol: symbol, kind: kind }, info); + } + function getDefaultLikeExportWorker(moduleSymbol, checker) { + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) + return { symbol: defaultExport, kind: 1 /* Default */ }; + var exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + return exportEquals === moduleSymbol ? undefined : { symbol: exportEquals, kind: 3 /* Equals */ }; + } + function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; @@ -106766,11 +109178,11 @@ var ts; if (name !== undefined) return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { - var aliased = program.getTypeChecker().getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + var aliased = checker.getImmediateAliasedSymbol(defaultExport); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent), checker, compilerOptions); } else { - return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target) }; + return { symbolForMeaning: defaultExport, name: moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) }; } } function getNameForExportDefault(symbol) { @@ -107009,10 +109421,10 @@ var ts; flags |= 1920 /* Namespace */; } if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; + flags |= 67897832 /* Type */; } if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; + flags |= 67220415 /* Value */; } return flags; } @@ -107051,7 +109463,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, @@ -107080,7 +109492,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_21 = function (info) { + var _loop_20 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -107107,7 +109519,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_21(info); + _loop_20(info); } }); })); @@ -107151,7 +109563,7 @@ var ts; if (classOrInterface) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); var declSourceFile = classOrInterface.getSourceFile(); - var inJs = ts.isSourceFileJavaScript(declSourceFile); + var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); return { kind: 1 /* ClassOrInterface */, token: token, parentDeclaration: classOrInterface, makeStatic: makeStatic, declSourceFile: declSourceFile, inJs: inJs, call: call }; } @@ -107161,7 +109573,7 @@ var ts; } return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { + function getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); @@ -107281,7 +109693,9 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixId = "fixCannotFindModule"; + var fixName = "fixCannotFindModule"; + var fixIdInstallTypesPackage = "installTypesPackage"; + var fixIdGenerateTypes = "generateTypes"; var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; var errorCodes = [ errorCodeCannotFindModule, @@ -107291,24 +109705,134 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; - var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); - return packageName === undefined ? [] - : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; + var packageName = tryGetImportedPackageName(sourceFile, start); + if (packageName === undefined) + return undefined; + var typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + return typesPackageName === undefined + ? ts.singleElementArray(tryGetGenerateTypesAction(context, packageName)) + : [codefix.createCodeFixAction(fixName, /*changes*/ [], [ts.Diagnostics.Install_0, typesPackageName], fixIdInstallTypesPackage, ts.Diagnostics.Install_all_missing_types_packages, getInstallCommand(sourceFile.fileName, typesPackageName))]; + }, + fixIds: [fixIdInstallTypesPackage, fixIdGenerateTypes], + getAllCodeActions: function (context) { + var savedTypesDir = null; // tslint:disable-line no-null-keyword + return codefix.codeFixAll(context, errorCodes, function (changes, diag, commands) { + var packageName = tryGetImportedPackageName(diag.file, diag.start); + if (packageName === undefined) + return undefined; + switch (context.fixId) { + case fixIdInstallTypesPackage: { + var pkg = getTypesPackageNameToInstall(packageName, context.host, diag.code); + if (pkg) { + commands.push(getInstallCommand(diag.file.fileName, pkg)); + } + break; + } + case fixIdGenerateTypes: { + var typesDir = savedTypesDir !== null ? savedTypesDir : savedTypesDir = getOrCreateTypesDirectory(changes, context); + var command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + if (command) + commands.push(command); + break; + } + default: + ts.Debug.fail("Bad fixId: " + context.fixId); + } + }); }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); - if (pkg) { - commands.push(getCommand(diag.file.fileName, pkg)); - } - }); }, }); - function getCommand(fileName, packageName) { + function tryGetGenerateTypesAction(context, packageName) { + var command; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var typesDir = getOrCreateTypesDirectory(t, context); + command = typesDir === undefined ? undefined : tryGenerateTypes(typesDir, packageName, context); + }); + return command && codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Generate_types_for_0, packageName], fixIdGenerateTypes, ts.Diagnostics.Generate_types_for_all_packages_without_types, command); + } + function tryGenerateTypes(typesDir, packageName, context) { + var file = context.sourceFile.fileName; + var fileToGenerateTypesFor = ts.tryResolveJSModule(packageName, ts.getDirectoryPath(file), context.host); // TODO: GH#18217 + if (fileToGenerateTypesFor === undefined) + return undefined; + var outputFileName = ts.resolvePath(ts.getDirectoryPath(context.program.getCompilerOptions().configFile.fileName), typesDir, packageName + ".d.ts"); + if (context.host.fileExists(outputFileName)) + return undefined; + return { type: "generate types", file: file, fileToGenerateTypesFor: fileToGenerateTypesFor, outputFileName: outputFileName }; + } + // If no types directory exists yet, adds it to tsconfig.json + function getOrCreateTypesDirectory(changes, context) { + var configFile = context.program.getCompilerOptions().configFile; + if (!configFile) + return undefined; + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + if (!compilerOptionsProperty) { + var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + return defaultTypesDirectoryName; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) + return defaultTypesDirectoryName; + var baseUrl = getOrAddBaseUrl(changes, configFile, compilerOptions); + var typesDirectoryFromPathMapping = getOrAddPathMapping(changes, configFile, compilerOptions); + return ts.combinePaths(baseUrl, typesDirectoryFromPathMapping); + } + var defaultBaseUrl = "."; + function makeDefaultBaseUrl() { + return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + } + function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { + var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + if (baseUrlProp) { + return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; + } + else { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultBaseUrl()); + return defaultBaseUrl; + } + } + var defaultTypesDirectoryName = "types"; + function makeDefaultPathMapping() { + return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + } + function makeDefaultPaths() { + return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + } + function getOrAddPathMapping(changes, tsconfig, compilerOptions) { + var paths = findProperty(compilerOptions, "paths"); + if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { + changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); + return defaultTypesDirectoryName; + } + // Look for an existing path mapping. Should look like `"*": "foo/*"`. + var existing = ts.firstDefined(paths.initializer.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "*" && ts.isArrayLiteralExpression(prop.initializer) + ? ts.firstDefined(prop.initializer.elements, function (value) { return ts.isStringLiteral(value) ? ts.tryRemoveSuffix(value.text, "/*") : undefined; }) + : undefined; + }); + if (existing) + return existing; + changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); + return defaultTypesDirectoryName; + } + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + function findProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + function tryGetImportedPackageName(sourceFile, pos) { var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; - var packageName = ts.getPackageName(moduleName).packageName; + var packageName = ts.parsePackageName(moduleName).packageName; + return ts.isExternalModuleNameRelative(packageName) ? undefined : packageName; + } + function getTypesPackageNameToInstall(packageName, host, diagCode) { return diagCode === errorCodeCannotFindModule ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 @@ -108045,7 +110569,7 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; - if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } var fixes = [ @@ -108177,22 +110701,19 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences, body) { - var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); var types = ts.map(args, function (arg) { - var type = checker.getTypeAtLocation(arg); - if (type === undefined) { - return undefined; - } // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - type = checker.getBaseTypeOfLiteralType(type); - return checker.typeToTypeNode(type); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); + var contextualType = checker.getContextualType(call); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(119 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, @@ -108202,7 +110723,7 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { @@ -108300,38 +110821,35 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken; - if (ts.isSourceFileJavaScript(sourceFile)) { - return undefined; // TODO: GH#20113 - } + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */ && token.kind !== 99 /* ThisKeyword */) { return undefined; } var parent = token.parent; @@ -108340,14 +110858,22 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + var typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + if (typeNode) { + changes.tryInsertJSDocType(sourceFile, parent, typeNode); + } return parent; } return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); return symbol.valueDeclaration; } return undefined; @@ -108360,30 +110886,30 @@ var ts; switch (errorCode) { // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); + annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); return param; } return undefined; // Get Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessor(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program); + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessor(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, cancellationToken); + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); return containingFunction; } return undefined; @@ -108391,9 +110917,9 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } function isApplicableFunctionForInference(declaration) { @@ -108407,36 +110933,62 @@ var ts; } return false; } - function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, cancellationToken) { + function annotateParameters(changes, parameterDeclaration, containingFunction, sourceFile, program, host, cancellationToken) { if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - var types = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || - containingFunction.parameters.map(function (p) { return ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined; }); - // We didn't actually find a set of type inference positions matching each parameter position - if (!types || containingFunction.parameters.length !== types.length) { - return; + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || + containingFunction.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + }); }); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } - ts.zipWith(containingFunction.parameters, types, function (parameter, type) { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + else { + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || inferTypeForVariableFromUsage(param.name, program, cancellationToken); - annotate(changes, sourceFile, param, type, program); + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, sourceFile, param, type, program, host); + } } } - function annotate(changes, sourceFile, declaration, type, program) { - var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); - if (typeNode) - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + function annotate(changes, sourceFile, declaration, type, program, host) { + var typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 151 /* PropertySignature */) { + changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + } + else { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } } - function getTypeNodeIfAccessible(type, enclosingScope, checker) { + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var result = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + return typeNode && !param.initializer && !ts.getJSDocType(param) ? __assign({}, inference, { typeNode: typeNode }) : undefined; + }); + changes.tryInsertJSDocParameters(sourceFile, result); + } + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { @@ -108447,13 +110999,21 @@ var ts; reportInaccessibleThisError: notAccessible, reportPrivateInBaseOfClassExpression: notAccessible, reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } }); return typeIsAccessible ? res : undefined; } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { - return entry.type === "node" ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; }); } function inferTypeForVariableFromUsage(token, program, cancellationToken) { @@ -108504,9 +111064,11 @@ var ts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; var isRest = ts.isRestParameter(parameter); + var isOptional = false; for (var _i = 0, callContexts_1 = callContexts; _i < callContexts_1.length; _i++) { var callContext = callContexts_1[_i]; if (callContext.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); continue; } if (isRest) { @@ -108519,10 +111081,14 @@ var ts; } } if (!types.length) { - return undefined; + return { declaration: parameter }; } var type = checker.getWidenedType(checker.getUnionType(types, 2 /* Subtype */)); - return isRest ? checker.createArrayType(type) : type; + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; }); } InferFromReference.inferTypeForParametersFromReferences = inferTypeForParametersFromReferences; @@ -108750,16 +111316,18 @@ var ts; else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } - else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { + else if (usageContext.numberIndexContext) { + return checker.createArrayType(recur(usageContext.numberIndexContext)); + } + else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; - var numberIndexInfo = void 0; if (usageContext.properties) { usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); + symbol.type = recur(context); members_6.set(name, symbol); }); } @@ -108775,17 +111343,17 @@ var ts; constructSignatures.push(getSignatureFromCallContext(constructContext, checker)); } } - if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); - } if (usageContext.stringIndexContext) { - stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker) || checker.getAnyType(), /*isReadonly*/ false); + stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 } else { return undefined; } + function recur(innerContext) { + return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + } } function getParameterTypeFromCallContexts(parameterIndex, callContexts, isRestParameter, checker) { var types = []; @@ -109005,7 +111573,7 @@ var ts; } function getDefaultValueFromType(checker, type) { if (type.flags & 256 /* BooleanLiteral */) { - return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); + return (type === checker.getFalseType() || type === checker.getFalseType(/*fresh*/ true)) ? ts.createFalse() : ts.createTrue(); } else if (type.isLiteral()) { return ts.createLiteral(type.value); @@ -109031,6 +111599,206 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function generateTypesForModule(name, moduleValue, formatSettings) { + return valueInfoToDeclarationFileText(ts.inspectValue(name, moduleValue), formatSettings); + } + ts.generateTypesForModule = generateTypesForModule; + function valueInfoToDeclarationFileText(valueInfo, formatSettings) { + return ts.textChanges.getNewFileText(toStatements(valueInfo, 0 /* ExportEquals */), 3 /* TS */, "\n", ts.formatting.getFormatContext(formatSettings)); + } + ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + var OutputKind; + (function (OutputKind) { + OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; + OutputKind[OutputKind["NamedExport"] = 1] = "NamedExport"; + OutputKind[OutputKind["NamespaceMember"] = 2] = "NamespaceMember"; + })(OutputKind || (OutputKind = {})); + function toNamespaceMemberStatements(info) { + return toStatements(info, 2 /* NamespaceMember */); + } + function toStatements(info, kind) { + var isDefault = info.name === "default" /* Default */; + var name = isDefault ? "_default" : info.name; + if (!isValidIdentifier(name) || isDefault && kind !== 1 /* NamedExport */) + return ts.emptyArray; + var modifiers = isDefault && info.kind === 2 /* FunctionOrClass */ ? [ts.createModifier(84 /* ExportKeyword */), ts.createModifier(79 /* DefaultKeyword */)] + : kind === 0 /* ExportEquals */ ? [ts.createModifier(124 /* DeclareKeyword */)] + : kind === 1 /* NamedExport */ ? [ts.createModifier(84 /* ExportKeyword */)] + : undefined; + var exportEquals = function () { return kind === 0 /* ExportEquals */ ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : ts.emptyArray; }; + var exportDefault = function () { return isDefault ? [exportEqualsOrDefault("_default", /*isExportEquals*/ false)] : ts.emptyArray; }; + switch (info.kind) { + case 2 /* FunctionOrClass */: + return exportEquals().concat(functionOrClassToStatements(modifiers, name, info)); + case 3 /* Object */: + var members = info.members; + if (kind === 0 /* ExportEquals */) { + return ts.flatMap(members, function (v) { return toStatements(v, 1 /* NamedExport */); }); + } + if (members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + // If some member is a function, use a namespace so it gets a FunctionDeclaration or ClassDeclaration. + return exportDefault().concat([createNamespace(modifiers, name, ts.flatMap(members, toNamespaceMemberStatements))]); + } + // falls through + case 0 /* Const */: + case 1 /* Array */: { + var comment = info.kind === 0 /* Const */ ? info.comment : undefined; + var constVar = ts.createVariableStatement(modifiers, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, toType(info))], 2 /* Const */)); + return exportEquals().concat(exportDefault(), [addComment(constVar, comment)]); + } + default: + return ts.Debug.assertNever(info); + } + } + function exportEqualsOrDefault(name, isExportEquals) { + return ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(name)); + } + function functionOrClassToStatements(modifiers, name, _a) { + var source = _a.source, prototypeMembers = _a.prototypeMembers, namespaceMembers = _a.namespaceMembers; + var fnAst = parseClassOrFunctionBody(source); + var _b = fnAst === undefined ? { parameters: ts.emptyArray, returnType: anyType() } : getParametersAndReturnType(fnAst), parameters = _b.parameters, returnType = _b.returnType; + var instanceProperties = typeof fnAst === "object" ? getConstructorFunctionInstanceProperties(fnAst) : ts.emptyArray; + var classStaticMembers = instanceProperties.length !== 0 || prototypeMembers.length !== 0 || fnAst === undefined || typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */ ? [] : undefined; + var namespaceStatements = ts.flatMap(namespaceMembers, function (info) { + if (!isValidIdentifier(info.name)) + return undefined; + if (classStaticMembers) { + switch (info.kind) { + case 3 /* Object */: + if (info.members.some(function (m) { return m.kind === 2 /* FunctionOrClass */; })) { + break; + } + // falls through + case 1 /* Array */: + case 0 /* Const */: + classStaticMembers.push(addComment(ts.createProperty(/*decorators*/ undefined, [ts.createModifier(115 /* StaticKeyword */)], info.name, /*questionOrExclamationToken*/ undefined, toType(info), /*initializer*/ undefined), info.kind === 0 /* Const */ ? info.comment : undefined)); + return undefined; + case 2 /* FunctionOrClass */: + if (!info.namespaceMembers.length) { // Else, can't merge a static method with a namespace. Must make it a function on the namespace. + var sig = tryGetMethod(info, [ts.createModifier(115 /* StaticKeyword */)]); + if (sig) { + classStaticMembers.push(sig); + return undefined; + } + } + } + } + return toStatements(info, 2 /* NamespaceMember */); + }); + var decl = classStaticMembers + ? ts.createClassDeclaration( + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, + /*heritageClauses*/ undefined, classStaticMembers.concat((parameters.length ? [ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, parameters, /*body*/ undefined)] : ts.emptyArray), instanceProperties, ts.mapDefined(prototypeMembers, function (info) { return info.kind === 2 /* FunctionOrClass */ ? tryGetMethod(info) : undefined; }))) + : ts.createFunctionDeclaration(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, parameters, returnType, /*body*/ undefined); + return [decl].concat((namespaceStatements.length === 0 ? ts.emptyArray : [createNamespace(modifiers && modifiers.map(function (m) { return ts.getSynthesizedDeepClone(m); }), name, namespaceStatements)])); + } + function tryGetMethod(_a, modifiers) { + var name = _a.name, source = _a.source; + if (!isValidIdentifier(name)) + return undefined; + var fnAst = parseClassOrFunctionBody(source); + if (fnAst === undefined || (typeof fnAst !== "number" && fnAst.kind === 155 /* Constructor */)) + return undefined; + var sig = getParametersAndReturnType(fnAst); + return sig && ts.createMethod( + /*decorators*/ undefined, modifiers, + /*asteriskToken*/ undefined, name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, sig.parameters, sig.returnType, + /*body*/ undefined); + } + function toType(info) { + switch (info.kind) { + case 0 /* Const */: + return ts.createTypeReferenceNode(info.typeName, /*typeArguments*/ undefined); + case 1 /* Array */: + return ts.createArrayTypeNode(toType(info.inner)); + case 2 /* FunctionOrClass */: + return ts.createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. + case 3 /* Object */: + return ts.createTypeLiteralNode(info.members.map(function (m) { return ts.createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined); })); + default: + return ts.Debug.assertNever(info); + } + } + // Parses assignments to "this.x" in the constructor into class property declarations + function getConstructorFunctionInstanceProperties(fnAst) { + var members = []; + forEachOwnNodeOfFunction(fnAst, function (node) { + if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 99 /* ThisKeyword */) { + var name = node.left.name.text; + if (!ts.isJsPrivate(name)) + members.push(ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined)); + } + }); + return members; + } + function getParametersAndReturnType(fnAst) { + if (typeof fnAst === "number") { + return { parameters: ts.fill(fnAst, function (i) { return makeParameter("p" + i, anyType()); }), returnType: anyType() }; + } + var usedArguments = false, hasReturn = false; + forEachOwnNodeOfFunction(fnAst, function (node) { + usedArguments = usedArguments || ts.isIdentifier(node) && node.text === "arguments"; + hasReturn = hasReturn || ts.isReturnStatement(node) && !!node.expression && node.expression.kind !== 198 /* VoidExpression */; + }); + var parameters = fnAst.parameters.map(function (p) { return makeParameter("" + p.name.getText(), inferParameterType(fnAst, p)); }).concat((usedArguments ? [makeRestParameter()] : ts.emptyArray)); + return { parameters: parameters, returnType: hasReturn ? anyType() : ts.createKeywordTypeNode(105 /* VoidKeyword */) }; + } + function makeParameter(name, type) { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type); + } + function makeRestParameter() { + return ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createToken(24 /* DotDotDotToken */), "args", /*questionToken*/ undefined, ts.createArrayTypeNode(anyType())); + } + /** Returns 'undefined' for class with no declared constructor */ + function parseClassOrFunctionBody(source) { + if (typeof source === "number") + return source; + var classOrFunction = ts.tryCast(parseExpression(source), function (node) { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isClassExpression(node); }); + return classOrFunction + ? ts.isClassExpression(classOrFunction) ? ts.find(classOrFunction.members, ts.isConstructorDeclaration) : classOrFunction + // If that didn't parse, it's a method `m() {}`. Parse again inside of an object literal. + : ts.cast(ts.first(ts.cast(parseExpression("{ " + source + " }"), ts.isObjectLiteralExpression).properties), ts.isMethodDeclaration); + } + function parseExpression(expr) { + var text = "const _ = " + expr; + var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; + } + function inferParameterType(_fn, _param) { + // TODO: Inspect function body for clues (see inferFromUsage.ts) + return anyType(); + } + // Descends through all nodes in a function, but not in nested functions. + function forEachOwnNodeOfFunction(fnAst, cb) { + fnAst.body.forEachChild(function recur(node) { + cb(node); + if (!ts.isFunctionLike(node)) + node.forEachChild(recur); + }); + } + function isValidIdentifier(name) { + var keyword = ts.stringToToken(name); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + } + function addComment(node, comment) { + if (comment !== undefined) + ts.addSyntheticLeadingComment(node, 2 /* SingleLineCommentTrivia */, comment); + return node; + } + function anyType() { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + function createNamespace(modifiers, name, statements) { + return ts.createModuleDeclaration(/*decorators*/ undefined, modifiers, ts.createIdentifier(name), ts.createModuleBlock(statements), 16 /* Namespace */); + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109481,7 +112249,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_22 = function (element) { + var _loop_21 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -109500,7 +112268,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_22(element); + _loop_21(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -110126,7 +112894,7 @@ var ts; // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; var parameters = []; @@ -110342,7 +113110,7 @@ var ts; // Make a unique name for the extracted variable var file = scope.getSourceFile(); var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); - var isJS = ts.isInJavaScriptFile(scope); + var isJS = ts.isInJSFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 @@ -110676,7 +113444,7 @@ var ts; if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (ts.isClassLike(scope) && ts.isInJavaScriptFile(scope)) { + if (ts.isClassLike(scope) && ts.isInJSFile(scope)) { constantErrors.push(ts.createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (ts.isArrowFunction(scope) && !ts.isBlock(scope.body)) { @@ -110732,7 +113500,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_23 = function (i) { + var _loop_22 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -110772,7 +113540,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_23(i); + _loop_22(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -111046,7 +113814,7 @@ var ts; var fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - var isJS = ts.isSourceFileJavaScript(file); + var isJS = ts.isSourceFileJS(file); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); @@ -111178,7 +113946,7 @@ var ts; return; var file = context.file, program = context.program, cancellationToken = context.cancellationToken; var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { - return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + return (entry.kind !== 0 /* Span */ && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; }); ts.forEach(referenceEntries, function (entry) { var parent = entry.parent; @@ -111322,10 +114090,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_24 = function (sourceFile) { + var _loop_23 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_25 = function (statement) { + var _loop_24 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -111347,12 +114115,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_25(statement); + _loop_24(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_24(sourceFile); + _loop_23(sourceFile); } } function getNamespaceLikeImport(node) { @@ -111770,7 +114538,7 @@ var ts; return ts.forEach(statement.declarationList.declarations, cb); case 219 /* ExpressionStatement */: { var expression = statement.expression; - return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + return ts.isBinaryExpression(expression) && ts.getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : undefined; } @@ -112344,8 +115112,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -112523,7 +115291,7 @@ var ts; } break; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { + if (ts.getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } // falls through @@ -112865,8 +115633,9 @@ var ts; var hostCache = new HostCache(host, getCanonicalFileName); var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -112903,6 +115672,10 @@ var ts; getDirectories: function (path) { return host.getDirectories ? host.getDirectories(path) : []; }, + readDirectory: function (path, extensions, exclude, include, depth) { + ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(path, extensions, exclude, include, depth); + }, onReleaseOldSourceFile: onReleaseOldSourceFile, hasInvalidatedResolution: hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: host.hasChangedAutomaticTypeDirectiveNames @@ -112924,7 +115697,7 @@ var ts; options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences: projectReferences }; program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. @@ -113039,7 +115812,7 @@ var ts; // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. // Therefore only get diagnostics for given file. var semanticDiagnostics = program.getSemanticDiagnostics(targetSourceFile, cancellationToken); - if (!program.getCompilerOptions().declaration) { + if (!ts.getEmitDeclarations(program.getCompilerOptions())) { return semanticDiagnostics.slice(); } // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface @@ -113082,14 +115855,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_4 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_4 && { + var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_7 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), - documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), + documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -113162,27 +115935,25 @@ var ts; var node = ts.getTouchingPropertyName(sourceFile, position); if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; - return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); + return [openingElement, closingElement].map(function (node) { + return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); + }); } else { - var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - return refs && refs.map(function (_a) { - var fileName = _a.fileName, textSpan = _a.textSpan; - return ({ fileName: fileName, textSpan: textSpan }); - }); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + return getReferencesWorker(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position, {}, ts.FindAllReferences.toReferenceEntry); } - function getReferences(node, position, options) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); // Exclude default library when renaming as commonly user don't want to change that file. var sourceFiles = options && options.isForRename ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) : program.getSourceFiles(); - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); + return ts.FindAllReferences.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); } function findReferences(fileName, position) { synchronizeHostData(); @@ -113389,19 +116160,31 @@ var ts; if (preferences === void 0) { preferences = ts.emptyOptions; } return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } - function applyCodeActionCommand(fileName, actionOrUndefined) { - var action = typeof fileName === "string" ? actionOrUndefined : fileName; - return ts.isArray(action) ? Promise.all(action.map(applySingleCodeActionCommand)) : applySingleCodeActionCommand(action); + function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { + var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; + var formatSettings = typeof fileName !== "string" ? actionOrFormatSettingsOrUndefined : undefined; + return ts.isArray(action) ? Promise.all(action.map(function (a) { return applySingleCodeActionCommand(a, formatSettings); })) : applySingleCodeActionCommand(action, formatSettings); } - function applySingleCodeActionCommand(action) { + function applySingleCodeActionCommand(action, formatSettings) { + var getPath = function (path) { return ts.toPath(path, currentDirectory, getCanonicalFileName); }; switch (action.type) { case "install package": return host.installPackage - ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) + ? host.installPackage({ fileName: getPath(action.file), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); + case "generate types": { + var fileToGenerateTypesFor = action.fileToGenerateTypesFor, outputFileName_1 = action.outputFileName; + if (!host.inspectValue) + return Promise.reject("Host does not implement `installPackage`"); + var valueInfoPromise = host.inspectValue({ fileNameToRequire: fileToGenerateTypesFor }); + return valueInfoPromise.then(function (valueInfo) { + var fullOut = getPath(outputFileName_1); + host.writeFile(fullOut, ts.valueInfoToDeclarationFileText(valueInfo, formatSettings || ts.testFormatSettings)); // TODO: GH#18217 + return { successMessage: "Wrote types to '" + fullOut + "'" }; + }); + } default: - return ts.Debug.fail(); - // TODO: Debug.assertNever(action); will only work if there is more than one type. + return ts.Debug.assertNever(action); } } function getDocCommentTemplateAtPosition(fileName, position) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index d7092a51b28..28b6a13abb5 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -86,7 +86,7 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); @@ -101,6 +101,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -729,17 +730,23 @@ var ts; } return result; } + /** + * Deduplicates an unsorted array. + * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param comparer An optional `Comparer` used to sort entries before comparison, though the + * result will remain in the original order in `array`. + */ function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); + return array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); } ts.deduplicate = deduplicate; + /** + * Deduplicates an array that has already been sorted. + */ function deduplicateSorted(array, comparer) { - if (!array) - return undefined; if (array.length === 0) return []; var last = array[0]; @@ -784,7 +791,7 @@ var ts; return false; } for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { + if (!equalityComparer(array1[i], array2[i], i)) { return false; } } @@ -1161,7 +1168,7 @@ var ts; return false; for (var key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) + if (!hasOwnProperty.call(right, key)) return false; if (!equalityComparer(left[key], right[key])) return false; @@ -1281,6 +1288,10 @@ var ts; return typeof text === "string"; } ts.isString = isString; + function isNumber(x) { + return typeof x === "number"; + } + ts.isNumber = isNumber; function tryCast(value, test) { return value !== undefined && test(value) ? value : undefined; } @@ -1445,7 +1456,9 @@ var ts; } Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + if (message === void 0) { message = "Illegal value:"; } + var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function getFunctionName(func) { @@ -1948,6 +1961,10 @@ var ts; } } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; + function fill(length, cb) { + return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + } + ts.fill = fill; })(ts || (ts = {})); /*@internal*/ var ts; @@ -2042,6 +2059,366 @@ var ts; performance.disable = disable; })(performance = ts.performance || (ts.performance = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + // https://semver.org/#spec-item-2 + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://semver.org/#spec-item-9 + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + // https://semver.org/#spec-item-10 + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + // https://semver.org/#spec-item-9 + // > Numeric identifiers MUST NOT include leading zeroes. + var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + /** + * Describes a precise semantic version number, https://semver.org + */ + var Version = /** @class */ (function () { + function Version(major, minor, patch, prerelease, build) { + if (minor === void 0) { minor = 0; } + if (patch === void 0) { patch = 0; } + if (prerelease === void 0) { prerelease = ""; } + if (build === void 0) { build = ""; } + if (typeof major === "string") { + var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); + } + ts.Debug.assert(major >= 0, "Invalid argument: major"); + ts.Debug.assert(minor >= 0, "Invalid argument: minor"); + ts.Debug.assert(patch >= 0, "Invalid argument: patch"); + ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; + this.build = build ? build.split(".") : ts.emptyArray; + } + Version.tryParse = function (text) { + var result = tryParseComponents(text); + if (!result) + return undefined; + var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build; + return new Version(major, minor, patch, prerelease, build); + }; + Version.prototype.compareTo = function (other) { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + // + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) + return 0 /* EqualTo */; + if (other === undefined) + return 1 /* GreaterThan */; + return ts.compareValues(this.major, other.major) + || ts.compareValues(this.minor, other.minor) + || ts.compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); + }; + Version.prototype.increment = function (field) { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return ts.Debug.assertNever(field); + } + }; + Version.prototype.toString = function () { + var result = this.major + "." + this.minor + "." + this.patch; + if (ts.some(this.prerelease)) + result += "-" + this.prerelease.join("."); + if (ts.some(this.build)) + result += "+" + this.build.join("."); + return result; + }; + Version.zero = new Version(0, 0, 0); + return Version; + }()); + ts.Version = Version; + function tryParseComponents(text) { + var match = versionRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "0" : _a, _b = match[3], patch = _b === void 0 ? "0" : _b, _c = match[4], prerelease = _c === void 0 ? "" : _c, _d = match[5], build = _d === void 0 ? "" : _d; + if (prerelease && !prereleaseRegExp.test(prerelease)) + return undefined; + if (build && !buildRegExp.test(build)) + return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease: prerelease, + build: build + }; + } + function comparePrerelaseIdentifiers(left, right) { + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) + return 0 /* EqualTo */; + if (left.length === 0) + return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) + return -1 /* LessThan */; + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + var length = Math.min(left.length, right.length); + for (var i = 0; i < length; i++) { + var leftIdentifier = left[i]; + var rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) + continue; + var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) + return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + var result = ts.compareValues(+leftIdentifier, +rightIdentifier); + if (result) + return result; + } + else { + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) + return result; + } + } + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return ts.compareValues(left.length, right.length); + } + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + var VersionRange = /** @class */ (function () { + function VersionRange(spec) { + this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + } + VersionRange.tryParse = function (text) { + var sets = parseRange(text); + if (sets) { + var range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + }; + VersionRange.prototype.test = function (version) { + if (typeof version === "string") + version = new Version(version); + return testDisjunction(version, this._alternatives); + }; + VersionRange.prototype.toString = function () { + return formatDisjunction(this._alternatives); + }; + return VersionRange; + }()); + ts.VersionRange = VersionRange; + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + var logicalOrRegExp = /\s*\|\|\s*/g; + var whitespaceRegExp = /\s+/g; + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + function parseRange(text) { + var alternatives = []; + for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) { + var range = _a[_i]; + if (!range) + continue; + var comparators = []; + var match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) + return undefined; + } + else { + for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) { + var simple = _c[_b]; + var match_1 = rangeRegExp.exec(simple); + if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators)) + return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + function parsePartial(text) { + var match = partialRegExp.exec(text); + if (!match) + return undefined; + var major = match[1], _a = match[2], minor = _a === void 0 ? "*" : _a, _b = match[3], patch = _b === void 0 ? "*" : _b, prerelease = match[4], build = match[5]; + var version = new Version(isWildcard(major) ? 0 : parseInt(major, 10), isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), prerelease, build); + return { version: version, major: major, minor: minor, patch: patch }; + } + function parseHyphen(left, right, comparators) { + var leftResult = parsePartial(left); + if (!leftResult) + return false; + var rightResult = parsePartial(right); + if (!rightResult) + return false; + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + if (!isWildcard(rightResult.major)) { + comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + return true; + } + function parseComparator(operator, text, comparators) { + var result = parsePartial(text); + if (!result) + return false; + var version = result.version, major = result.major, minor = result.minor, patch = result.patch; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + return true; + } + function isWildcard(part) { + return part === "*" || part === "x" || part === "X"; + } + function createComparator(operator, operand) { + return { operator: operator, operand: operand }; + } + function testDisjunction(version, alternatives) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) + return true; + for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { + var alternative = alternatives_1[_i]; + if (testAlternative(version, alternative)) + return true; + } + return false; + } + function testAlternative(version, comparators) { + for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) { + var comparator = comparators_1[_i]; + if (!testComparator(version, comparator.operator, comparator.operand)) + return false; + } + return true; + } + function testComparator(version, operator, operand) { + var cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return ts.Debug.assertNever(operator); + } + } + function formatDisjunction(alternatives) { + return ts.map(alternatives, formatAlternative).join(" || ") || "*"; + } + function formatAlternative(comparators) { + return ts.map(comparators, formatComparator).join(" "); + } + function formatComparator(comparator) { + return "" + comparator.operator + comparator.operand; + } +})(ts || (ts = {})); var ts; (function (ts) { // token > SyntaxKind.Identifier => token is a keyword @@ -2628,6 +3005,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3056,8 @@ var ts; SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; // Prefer aliases which are not directly visible SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope"; + // Skip building an accessible symbol chain + /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -2747,38 +3127,38 @@ var ts; SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; - SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer"; + SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment"; SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports"; /* @internal */ SymbolFlags[SymbolFlags["All"] = 67108863] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type"; + SymbolFlags[SymbolFlags["Value"] = 67220415] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 67897832] = "Type"; SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67220414] = "FunctionScopedVariableExcludes"; // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67220415] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 67220415] = "ParameterExcludes"; SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes"; SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 67219887] = "FunctionExcludes"; SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67897736] = "InterfaceExcludes"; SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes"; SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 67212223] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67154879] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67187647] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67635688] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67897832] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; @@ -2853,14 +3233,15 @@ var ts; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding"; - NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop"; - NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding"; - NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter"; - NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked"; - NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference"; - NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass"; + NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding"; + NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop"; + NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding"; + NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter"; + NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked"; + NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference"; + NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -3006,9 +3387,8 @@ var ts; var InferenceFlags; (function (InferenceFlags) { InferenceFlags[InferenceFlags["None"] = 0] = "None"; - InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; - InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; - InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3027,22 +3407,22 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(Ternary = ts.Ternary || (ts.Ternary = {})); /* @internal */ - var SpecialPropertyAssignmentKind; - (function (SpecialPropertyAssignmentKind) { - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; + var AssignmentDeclarationKind; + (function (AssignmentDeclarationKind) { + AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None"; /// exports.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty"; /// module.exports = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports"; /// className.prototype.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty"; /// this.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty"; + AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty"; // F.name = expr - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property"; + AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property"; // F.prototype = { ... } - SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype"; - })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {})); + AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype"; + })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {})); var DiagnosticCategory; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; @@ -3279,25 +3659,21 @@ var ts; TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators"; - TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments"; - TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread"; - TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread"; - TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest"; - TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 134217728] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; + TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; + TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; + TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; + TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -3316,25 +3692,24 @@ var ts; // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask"; + TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3578,20 +3953,6 @@ var ts; PollingInterval[PollingInterval["Medium"] = 500] = "Medium"; PollingInterval[PollingInterval["Low"] = 250] = "Low"; })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {})); - function getPriorityValues(highPriorityValue) { - var mediumPriorityValue = highPriorityValue * 2; - var lowPriorityValue = mediumPriorityValue * 4; - return [highPriorityValue, mediumPriorityValue, lowPriorityValue]; - } - function pollingInterval(watchPriority) { - return pollingIntervalsForPriority[watchPriority]; - } - var pollingIntervalsForPriority = getPriorityValues(250); - /* @internal */ - function watchFileUsingPriorityPollingInterval(host, fileName, callback, watchPriority) { - return host.watchFile(fileName, callback, pollingInterval(watchPriority)); - } - ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { @@ -3809,17 +4170,21 @@ var ts; var newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - var eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } ts.onWatchedFileStat = onWatchedFileStat; + /*@internal*/ + function getFileWatcherEventKind(oldTime, newTime) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + ts.getFileWatcherEventKind = getFileWatcherEventKind; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4140,11 +4505,12 @@ var ts; function createDirectoryWatcher(dirName, dirPath) { var watcher = fsWatchDirectory(dirName, function (_eventName, relativeFileName) { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" - var fileName = !ts.isString(relativeFileName) - ? undefined // TODO: GH#18217 - : ts.getNormalizedAbsolutePath(relativeFileName, dirName); + if (!ts.isString(relativeFileName)) { + return; + } + var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName); // Some applications save a working file via rename operations - var callbacks = fileWatcherCallbacks.get(toCanonicalName(fileName)); + var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName)); if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; @@ -4755,7 +5121,7 @@ var ts; Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254", "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), @@ -4794,6 +5160,10 @@ var ts; The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."), An_expression_of_type_void_cannot_be_tested_for_truthiness: diag(1345, ts.DiagnosticCategory.Error, "An_expression_of_type_void_cannot_be_tested_for_truthiness_1345", "An expression of type 'void' cannot be tested for truthiness"), + This_parameter_is_not_allowed_with_use_strict_directive: diag(1346, ts.DiagnosticCategory.Error, "This_parameter_is_not_allowed_with_use_strict_directive_1346", "This parameter is not allowed with 'use strict' directive."), + use_strict_directive_cannot_be_used_with_non_simple_parameter_list: diag(1347, ts.DiagnosticCategory.Error, "use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347", "'use strict' directive cannot be used with non-simple parameter list."), + Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), + use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5037,7 +5407,6 @@ var ts; The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), - Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), @@ -5065,6 +5434,14 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), + Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), + JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5156,6 +5533,7 @@ var ts; An_arrow_function_cannot_have_a_this_parameter: diag(2730, ts.DiagnosticCategory.Error, "An_arrow_function_cannot_have_a_this_parameter_2730", "An arrow function cannot have a 'this' parameter."), Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), + It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5269,7 +5647,9 @@ var ts; Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), - Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."), + Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."), + Build_option_0_requires_a_value_of_type_1: diag(5073, ts.DiagnosticCategory.Error, "Build_option_0_requires_a_value_of_type_1_5073", "Build option '{0}' requires a value of type {1}."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5363,7 +5743,7 @@ var ts; Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), - Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + Expected_type_of_0_field_in_package_json_to_be_1_got_2: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105", "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."), baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), @@ -5461,6 +5841,15 @@ var ts; _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"), + package_json_has_a_typesVersions_field_with_version_specific_path_mappings: diag(6206, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206", "'package.json' has a 'typesVersions' field with version-specific path mappings."), + package_json_does_not_have_a_typesVersions_entry_that_matches_version_0: diag(6207, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207", "'package.json' does not have a 'typesVersions' entry that matches version '{0}'."), + package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2: diag(6208, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208", "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."), + package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range: diag(6209, ts.DiagnosticCategory.Message, "package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209", "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."), + An_argument_for_0_was_not_provided: diag(6210, ts.DiagnosticCategory.Message, "An_argument_for_0_was_not_provided_6210", "An argument for '{0}' was not provided."), + An_argument_matching_this_binding_pattern_was_not_provided: diag(6211, ts.DiagnosticCategory.Message, "An_argument_matching_this_binding_pattern_was_not_provided_6211", "An argument matching this binding pattern was not provided."), + Did_you_mean_to_call_this_expression: diag(6212, ts.DiagnosticCategory.Message, "Did_you_mean_to_call_this_expression_6212", "Did you mean to call this expression?"), + Did_you_mean_to_use_new_with_this_expression: diag(6213, ts.DiagnosticCategory.Message, "Did_you_mean_to_use_new_with_this_expression_6213", "Did you mean to use 'new' with this expression?"), + Enable_strict_bind_call_and_apply_methods_on_functions: diag(6214, ts.DiagnosticCategory.Message, "Enable_strict_bind_call_and_apply_methods_on_functions_6214", "Enable strict 'bind', 'call', and 'apply' methods on functions."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), @@ -5491,9 +5880,9 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), - Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), + The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5558,6 +5947,7 @@ var ts; JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), + You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5686,10 +6076,13 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Generate_types_for_0: diag(95067, ts.DiagnosticCategory.Message, "Generate_types_for_0_95067", "Generate types for '{0}'"), + Generate_types_for_all_packages_without_types: diag(95068, ts.DiagnosticCategory.Message, "Generate_types_for_all_packages_without_types_95068", "Generate types for all packages without types"), }; })(ts || (ts = {})); var ts; (function (ts) { + var _a; /* @internal */ function tokenIsIdentifierOrKeyword(token) { return token >= 71 /* Identifier */; @@ -5700,136 +6093,85 @@ var ts; return token === 29 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token); } ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan; - var textToToken = ts.createMapFromTemplate({ - "abstract": 117 /* AbstractKeyword */, - "any": 119 /* AnyKeyword */, - "as": 118 /* AsKeyword */, - "boolean": 122 /* BooleanKeyword */, - "break": 72 /* BreakKeyword */, - "case": 73 /* CaseKeyword */, - "catch": 74 /* CatchKeyword */, - "class": 75 /* ClassKeyword */, - "continue": 77 /* ContinueKeyword */, - "const": 76 /* ConstKeyword */, - "constructor": 123 /* ConstructorKeyword */, - "debugger": 78 /* DebuggerKeyword */, - "declare": 124 /* DeclareKeyword */, - "default": 79 /* DefaultKeyword */, - "delete": 80 /* DeleteKeyword */, - "do": 81 /* DoKeyword */, - "else": 82 /* ElseKeyword */, - "enum": 83 /* EnumKeyword */, - "export": 84 /* ExportKeyword */, - "extends": 85 /* ExtendsKeyword */, - "false": 86 /* FalseKeyword */, - "finally": 87 /* FinallyKeyword */, - "for": 88 /* ForKeyword */, - "from": 143 /* FromKeyword */, - "function": 89 /* FunctionKeyword */, - "get": 125 /* GetKeyword */, - "if": 90 /* IfKeyword */, - "implements": 108 /* ImplementsKeyword */, - "import": 91 /* ImportKeyword */, - "in": 92 /* InKeyword */, - "infer": 126 /* InferKeyword */, - "instanceof": 93 /* InstanceOfKeyword */, - "interface": 109 /* InterfaceKeyword */, - "is": 127 /* IsKeyword */, - "keyof": 128 /* KeyOfKeyword */, - "let": 110 /* LetKeyword */, - "module": 129 /* ModuleKeyword */, - "namespace": 130 /* NamespaceKeyword */, - "never": 131 /* NeverKeyword */, - "new": 94 /* NewKeyword */, - "null": 95 /* NullKeyword */, - "number": 134 /* NumberKeyword */, - "object": 135 /* ObjectKeyword */, - "package": 111 /* PackageKeyword */, - "private": 112 /* PrivateKeyword */, - "protected": 113 /* ProtectedKeyword */, - "public": 114 /* PublicKeyword */, - "readonly": 132 /* ReadonlyKeyword */, - "require": 133 /* RequireKeyword */, - "global": 144 /* GlobalKeyword */, - "return": 96 /* ReturnKeyword */, - "set": 136 /* SetKeyword */, - "static": 115 /* StaticKeyword */, - "string": 137 /* StringKeyword */, - "super": 97 /* SuperKeyword */, - "switch": 98 /* SwitchKeyword */, - "symbol": 138 /* SymbolKeyword */, - "this": 99 /* ThisKeyword */, - "throw": 100 /* ThrowKeyword */, - "true": 101 /* TrueKeyword */, - "try": 102 /* TryKeyword */, - "type": 139 /* TypeKeyword */, - "typeof": 103 /* TypeOfKeyword */, - "undefined": 140 /* UndefinedKeyword */, - "unique": 141 /* UniqueKeyword */, - "unknown": 142 /* UnknownKeyword */, - "var": 104 /* VarKeyword */, - "void": 105 /* VoidKeyword */, - "while": 106 /* WhileKeyword */, - "with": 107 /* WithKeyword */, - "yield": 116 /* YieldKeyword */, - "async": 120 /* AsyncKeyword */, - "await": 121 /* AwaitKeyword */, - "of": 145 /* OfKeyword */, - "{": 17 /* OpenBraceToken */, - "}": 18 /* CloseBraceToken */, - "(": 19 /* OpenParenToken */, - ")": 20 /* CloseParenToken */, - "[": 21 /* OpenBracketToken */, - "]": 22 /* CloseBracketToken */, - ".": 23 /* DotToken */, - "...": 24 /* DotDotDotToken */, - ";": 25 /* SemicolonToken */, - ",": 26 /* CommaToken */, - "<": 27 /* LessThanToken */, - ">": 29 /* GreaterThanToken */, - "<=": 30 /* LessThanEqualsToken */, - ">=": 31 /* GreaterThanEqualsToken */, - "==": 32 /* EqualsEqualsToken */, - "!=": 33 /* ExclamationEqualsToken */, - "===": 34 /* EqualsEqualsEqualsToken */, - "!==": 35 /* ExclamationEqualsEqualsToken */, - "=>": 36 /* EqualsGreaterThanToken */, - "+": 37 /* PlusToken */, - "-": 38 /* MinusToken */, - "**": 40 /* AsteriskAsteriskToken */, - "*": 39 /* AsteriskToken */, - "/": 41 /* SlashToken */, - "%": 42 /* PercentToken */, - "++": 43 /* PlusPlusToken */, - "--": 44 /* MinusMinusToken */, - "<<": 45 /* LessThanLessThanToken */, - ">": 46 /* GreaterThanGreaterThanToken */, - ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, - "&": 48 /* AmpersandToken */, - "|": 49 /* BarToken */, - "^": 50 /* CaretToken */, - "!": 51 /* ExclamationToken */, - "~": 52 /* TildeToken */, - "&&": 53 /* AmpersandAmpersandToken */, - "||": 54 /* BarBarToken */, - "?": 55 /* QuestionToken */, - ":": 56 /* ColonToken */, - "=": 58 /* EqualsToken */, - "+=": 59 /* PlusEqualsToken */, - "-=": 60 /* MinusEqualsToken */, - "*=": 61 /* AsteriskEqualsToken */, - "**=": 62 /* AsteriskAsteriskEqualsToken */, - "/=": 63 /* SlashEqualsToken */, - "%=": 64 /* PercentEqualsToken */, - "<<=": 65 /* LessThanLessThanEqualsToken */, - ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, - ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, - "&=": 68 /* AmpersandEqualsToken */, - "|=": 69 /* BarEqualsToken */, - "^=": 70 /* CaretEqualsToken */, - "@": 57 /* AtToken */, - }); + var textToKeywordObj = (_a = { + abstract: 117 /* AbstractKeyword */, + any: 119 /* AnyKeyword */, + as: 118 /* AsKeyword */, + boolean: 122 /* BooleanKeyword */, + break: 72 /* BreakKeyword */, + case: 73 /* CaseKeyword */, + catch: 74 /* CatchKeyword */, + class: 75 /* ClassKeyword */, + continue: 77 /* ContinueKeyword */, + const: 76 /* ConstKeyword */ + }, + _a["" + "constructor"] = 123 /* ConstructorKeyword */, + _a.debugger = 78 /* DebuggerKeyword */, + _a.declare = 124 /* DeclareKeyword */, + _a.default = 79 /* DefaultKeyword */, + _a.delete = 80 /* DeleteKeyword */, + _a.do = 81 /* DoKeyword */, + _a.else = 82 /* ElseKeyword */, + _a.enum = 83 /* EnumKeyword */, + _a.export = 84 /* ExportKeyword */, + _a.extends = 85 /* ExtendsKeyword */, + _a.false = 86 /* FalseKeyword */, + _a.finally = 87 /* FinallyKeyword */, + _a.for = 88 /* ForKeyword */, + _a.from = 143 /* FromKeyword */, + _a.function = 89 /* FunctionKeyword */, + _a.get = 125 /* GetKeyword */, + _a.if = 90 /* IfKeyword */, + _a.implements = 108 /* ImplementsKeyword */, + _a.import = 91 /* ImportKeyword */, + _a.in = 92 /* InKeyword */, + _a.infer = 126 /* InferKeyword */, + _a.instanceof = 93 /* InstanceOfKeyword */, + _a.interface = 109 /* InterfaceKeyword */, + _a.is = 127 /* IsKeyword */, + _a.keyof = 128 /* KeyOfKeyword */, + _a.let = 110 /* LetKeyword */, + _a.module = 129 /* ModuleKeyword */, + _a.namespace = 130 /* NamespaceKeyword */, + _a.never = 131 /* NeverKeyword */, + _a.new = 94 /* NewKeyword */, + _a.null = 95 /* NullKeyword */, + _a.number = 134 /* NumberKeyword */, + _a.object = 135 /* ObjectKeyword */, + _a.package = 111 /* PackageKeyword */, + _a.private = 112 /* PrivateKeyword */, + _a.protected = 113 /* ProtectedKeyword */, + _a.public = 114 /* PublicKeyword */, + _a.readonly = 132 /* ReadonlyKeyword */, + _a.require = 133 /* RequireKeyword */, + _a.global = 144 /* GlobalKeyword */, + _a.return = 96 /* ReturnKeyword */, + _a.set = 136 /* SetKeyword */, + _a.static = 115 /* StaticKeyword */, + _a.string = 137 /* StringKeyword */, + _a.super = 97 /* SuperKeyword */, + _a.switch = 98 /* SwitchKeyword */, + _a.symbol = 138 /* SymbolKeyword */, + _a.this = 99 /* ThisKeyword */, + _a.throw = 100 /* ThrowKeyword */, + _a.true = 101 /* TrueKeyword */, + _a.try = 102 /* TryKeyword */, + _a.type = 139 /* TypeKeyword */, + _a.typeof = 103 /* TypeOfKeyword */, + _a.undefined = 140 /* UndefinedKeyword */, + _a.unique = 141 /* UniqueKeyword */, + _a.unknown = 142 /* UnknownKeyword */, + _a.var = 104 /* VarKeyword */, + _a.void = 105 /* VoidKeyword */, + _a.while = 106 /* WhileKeyword */, + _a.with = 107 /* WithKeyword */, + _a.yield = 116 /* YieldKeyword */, + _a.async = 120 /* AsyncKeyword */, + _a.await = 121 /* AwaitKeyword */, + _a.of = 145 /* OfKeyword */, + _a); + var textToKeyword = ts.createMapFromTemplate(textToKeywordObj); + var textToToken = ts.createMapFromTemplate(__assign({}, textToKeywordObj, { "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, ")": 20 /* CloseParenToken */, "[": 21 /* OpenBracketToken */, "]": 22 /* CloseBracketToken */, ".": 23 /* DotToken */, "...": 24 /* DotDotDotToken */, ";": 25 /* SemicolonToken */, ",": 26 /* CommaToken */, "<": 27 /* LessThanToken */, ">": 29 /* GreaterThanToken */, "<=": 30 /* LessThanEqualsToken */, ">=": 31 /* GreaterThanEqualsToken */, "==": 32 /* EqualsEqualsToken */, "!=": 33 /* ExclamationEqualsToken */, "===": 34 /* EqualsEqualsEqualsToken */, "!==": 35 /* ExclamationEqualsEqualsToken */, "=>": 36 /* EqualsGreaterThanToken */, "+": 37 /* PlusToken */, "-": 38 /* MinusToken */, "**": 40 /* AsteriskAsteriskToken */, "*": 39 /* AsteriskToken */, "/": 41 /* SlashToken */, "%": 42 /* PercentToken */, "++": 43 /* PlusPlusToken */, "--": 44 /* MinusMinusToken */, "<<": 45 /* LessThanLessThanToken */, ">": 46 /* GreaterThanGreaterThanToken */, ">>>": 47 /* GreaterThanGreaterThanGreaterThanToken */, "&": 48 /* AmpersandToken */, "|": 49 /* BarToken */, "^": 50 /* CaretToken */, "!": 51 /* ExclamationToken */, "~": 52 /* TildeToken */, "&&": 53 /* AmpersandAmpersandToken */, "||": 54 /* BarBarToken */, "?": 55 /* QuestionToken */, ":": 56 /* ColonToken */, "=": 58 /* EqualsToken */, "+=": 59 /* PlusEqualsToken */, "-=": 60 /* MinusEqualsToken */, "*=": 61 /* AsteriskEqualsToken */, "**=": 62 /* AsteriskAsteriskEqualsToken */, "/=": 63 /* SlashEqualsToken */, "%=": 64 /* PercentEqualsToken */, "<<=": 65 /* LessThanLessThanEqualsToken */, ">>=": 66 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 68 /* AmpersandEqualsToken */, "|=": 69 /* BarEqualsToken */, "^=": 70 /* CaretEqualsToken */, "@": 57 /* AtToken */ })); /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: @@ -6407,6 +6749,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6436,6 +6779,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6833,9 +7177,9 @@ var ts; if (len >= 2 && len <= 11) { var ch = tokenValue.charCodeAt(0); if (ch >= 97 /* a */ && ch <= 122 /* z */) { - token = textToToken.get(tokenValue); - if (token !== undefined) { - return token; + var keyword = textToKeyword.get(tokenValue); + if (keyword !== undefined) { + return token = keyword; } } } @@ -6891,6 +7235,7 @@ var ts; function scan() { startPos = pos; tokenFlags = 0; + var asteriskSeen = false; while (true) { tokenPos = pos; if (pos >= end) { @@ -6929,6 +7274,24 @@ var ts; case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: + case 160 /* nonBreakingSpace */: + case 5760 /* ogham */: + case 8192 /* enQuad */: + case 8193 /* emQuad */: + case 8194 /* enSpace */: + case 8195 /* emSpace */: + case 8196 /* threePerEmSpace */: + case 8197 /* fourPerEmSpace */: + case 8198 /* sixPerEmSpace */: + case 8199 /* figureSpace */: + case 8200 /* punctuationSpace */: + case 8201 /* thinSpace */: + case 8202 /* hairSpace */: + case 8203 /* zeroWidthSpace */: + case 8239 /* narrowNoBreakSpace */: + case 8287 /* mathematicalSpace */: + case 12288 /* ideographicSpace */: + case 65279 /* byteOrderMark */: if (skipTrivia) { pos++; continue; @@ -6986,6 +7349,11 @@ var ts; return pos += 2, token = 40 /* AsteriskAsteriskToken */; } pos++; + if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) { + // decoration at the start of a JSDoc comment line + asteriskSeen = true; + continue; + } return token = 39 /* AsteriskToken */; case 43 /* plus */: if (text.charCodeAt(pos + 1) === 43 /* plus */) { @@ -7491,7 +7859,7 @@ var ts; pos++; } tokenValue = text.substring(tokenPos, pos); - return token = 71 /* Identifier */; + return token = getIdentifierToken(); } else { return token = 0 /* Unknown */; @@ -7568,6 +7936,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +7959,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7670,22 +8040,9 @@ var ts; } ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + return oldOptions.configFilePath !== newOptions.configFilePath || ts.moduleResolutionOptionDeclarations.some(function (o) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, o), ts.getCompilerOptionValue(newOptions, o)); + }); } ts.changesAffectModuleResolution = changesAffectModuleResolution; function findAncestor(node, callback) { @@ -7790,6 +8147,12 @@ var ts; sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function projectReferenceIsEqualTo(oldRef, newRef) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo; function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -8014,12 +8377,20 @@ var ts; return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function isJSDocTypeExpressionOrChild(node) { + return node.kind === 281 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } if (nodeIsMissing(node)) { return ""; } - return sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end); + if (isJSDocTypeExpressionOrChild(node)) { + // strip space + asterisk at line start + text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1"); + } + return text; } ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; function getTextOfNode(node, includeTrivia) { @@ -8046,13 +8417,13 @@ var ts; return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; - function getLiteralText(node, sourceFile) { + function getLiteralText(node, sourceFile, neverAsciiEscape) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent && !(ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */)) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -8421,6 +8792,10 @@ var ts; return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } ts.isEnumConst = isEnumConst; + function isDeclarationReadonly(declaration) { + return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)); + } + ts.isDeclarationReadonly = isDeclarationReadonly; function isVarConst(node) { return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); } @@ -8481,6 +8856,7 @@ var ts; case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: case 138 /* SymbolKeyword */: + case 135 /* ObjectKeyword */: case 140 /* UndefinedKeyword */: case 131 /* NeverKeyword */: return true; @@ -9148,18 +9524,18 @@ var ts; return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); + function isSourceFileJS(file) { + return isInJSFile(file); } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isSourceFileNotJavaScript(file) { - return !isInJavaScriptFile(file); + ts.isSourceFileJS = isSourceFileJS; + function isSourceFileNotJS(file) { + return !isInJSFile(file); } - ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; - function isInJavaScriptFile(node) { + ts.isSourceFileNotJS = isSourceFileNotJS; + function isInJSFile(node) { return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } - ts.isInJavaScriptFile = isInJavaScriptFile; + ts.isInJSFile = isInJSFile; function isInJsonFile(node) { return !!node && !!(node.flags & 16777216 /* JsonFile */); } @@ -9199,14 +9575,14 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - function getDeclarationOfJSInitializer(node) { + function getDeclarationOfExpando(node) { if (!node.parent) { return undefined; } var name; var decl; if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -9229,15 +9605,19 @@ var ts; return undefined; } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; } - ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + ts.getDeclarationOfExpando = getDeclarationOfExpando; + function isAssignmentDeclaration(decl) { + return ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl) || ts.isIdentifier(decl); + } + ts.isAssignmentDeclaration = isAssignmentDeclaration; /** Get the initializer, taking into account defaulted Javascript initializers */ function getEffectiveInitializer(node) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -9245,26 +9625,26 @@ var ts; return node.initializer; } ts.getEffectiveInitializer = getEffectiveInitializer; - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - function getDeclaredJavascriptInitializer(node) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + function getDeclaredExpandoInitializer(node) { var init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } - ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; + ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer; /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - function getAssignedJavascriptInitializer(node) { + function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { var isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } } - ts.getAssignedJavascriptInitializer = getAssignedJavascriptInitializer; + ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer; /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -9273,7 +9653,7 @@ var ts; * * This function returns the provided initializer, or undefined if it is not valid. */ - function getJavascriptInitializer(initializer, isPrototypeAssignment) { + function getExpandoInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; @@ -9287,30 +9667,30 @@ var ts; return initializer; } } - ts.getJavascriptInitializer = getJavascriptInitializer; + ts.getExpandoInitializer = getExpandoInitializer; /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name, initializer, isPrototypeAssignment) { - var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) { + var e = ts.isBinaryExpression(initializer) && initializer.operatorToken.kind === 54 /* BarBarToken */ && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, initializer.left)) { return e; } } - function isDefaultedJavascriptInitializer(node) { + function isDefaultedExpandoInitializer(node) { var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - function getOuterNameOfJsInitializer(node) { + ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer; + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + function getNameOfExpando(node) { if (ts.isBinaryExpression(node.parent)) { var parent = (node.parent.operatorToken.kind === 54 /* BarBarToken */ && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === 58 /* EqualsToken */ && ts.isIdentifier(parent.left)) { @@ -9321,7 +9701,7 @@ var ts; return node.parent.name; } } - ts.getOuterNameOfJsInitializer = getOuterNameOfJsInitializer; + ts.getNameOfExpando = getNameOfExpando; /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -9365,12 +9745,12 @@ var ts; ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - function getSpecialPropertyAssignmentKind(expr) { - var special = getSpecialPropertyAssignmentKindWorker(expr); - return special === 5 /* Property */ || isInJavaScriptFile(expr) ? special : 0 /* None */; + function getAssignmentDeclarationKind(expr) { + var special = getAssignmentDeclarationKindWorker(expr); + return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getSpecialPropertyAssignmentKindWorker(expr) { + ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind; + function getAssignmentDeclarationKindWorker(expr) { if (expr.operatorToken.kind !== 58 /* EqualsToken */ || !ts.isPropertyAccessExpression(expr.left)) { return 0 /* None */; @@ -9380,9 +9760,9 @@ var ts; // F.prototype = { ... } return 6 /* Prototype */; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - function getSpecialPropertyAccessKind(lhs) { + function getAssignmentDeclarationPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9411,7 +9791,7 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -9420,11 +9800,11 @@ var ts; } ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; function isPrototypePropertyAssignment(node) { - return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */; } ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } @@ -9530,7 +9910,7 @@ var ts; function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && + getAssignmentDeclarationKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === 54 /* BarBarToken */ ? node.expression.right.right @@ -9572,6 +9952,10 @@ var ts; result = ts.addRange(result, ts.getJSDocParameterTags(node)); break; } + if (node.kind === 148 /* TypeParameter */) { + result = ts.addRange(result, ts.getJSDocTypeParameterTags(node)); + break; + } node = getNextJSDocCommentLocation(node); } return result || ts.emptyArray; @@ -9762,6 +10146,12 @@ var ts; return node; } ts.skipParentheses = skipParentheses; + function skipParenthesesUp(node) { + while (node.kind === 193 /* ParenthesizedExpression */) { + node = node.parent; + } + return node; + } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { @@ -9786,32 +10176,36 @@ var ts; } ts.isDeclarationName = isDeclarationName; // See GH#16030 - function isAnyDeclarationName(name) { + function getDeclarationFromName(name) { + var parent = name.parent; switch (name.kind) { - case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: { - var parent = name.parent; + case 8 /* NumericLiteral */: + if (ts.isComputedPropertyName(parent)) + return parent.parent; + // falls through + case 71 /* Identifier */: if (ts.isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (ts.isQualifiedName(name.parent)) { - var tag = name.parent.parent; - return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + else if (ts.isQualifiedName(parent)) { + var tag = parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - var binExp = name.parent.parent; + var binExp = parent.parent; return ts.isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && + getAssignmentDeclarationKind(binExp) !== 0 /* None */ && (binExp.left.symbol || binExp.symbol) && - ts.getNameOfDeclaration(binExp) === name; + ts.getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } - ts.isAnyDeclarationName = isAnyDeclarationName; + ts.getDeclarationFromName = getDeclarationFromName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 147 /* ComputedPropertyName */ && @@ -9870,7 +10264,7 @@ var ts; node.kind === 251 /* ImportSpecifier */ || node.kind === 255 /* ExportSpecifier */ || node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || - ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; + ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { @@ -9879,7 +10273,7 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { @@ -10613,7 +11007,7 @@ var ts; var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); @@ -10627,7 +11021,7 @@ var ts; ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -10748,7 +11142,7 @@ var ts; */ function getEffectiveTypeAnnotationNode(node) { var type = node.type; - if (type || !isInJavaScriptFile(node)) + if (type || !isInJSFile(node)) return type; return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } @@ -10764,7 +11158,7 @@ var ts; function getEffectiveReturnTypeNode(node) { return ts.isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; function getJSDocTypeParameterDeclarations(node) { @@ -11048,13 +11442,18 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (ts.isExpressionWithTypeArguments(node) && - node.parent.token === 85 /* ExtendsKeyword */ && - ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } + var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + return cls && !cls.isImplements ? cls.class : undefined; } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { + return ts.isExpressionWithTypeArguments(node) + && ts.isHeritageClause(node.parent) + && ts.isClassLike(node.parent.parent) + ? { class: node.parent.parent, isImplements: node.parent.token === 108 /* ImplementsKeyword */ } + : undefined; + } + ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -11076,15 +11475,6 @@ var ts; return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 209 /* ExpressionWithTypeArguments */ - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 /* ImplementsKeyword */ - && node.parent.parent - && ts.isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } @@ -11120,10 +11510,10 @@ var ts; return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function tryExtractTSExtension(fileName) { + return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + ts.tryExtractTSExtension = tryExtractTSExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -11262,6 +11652,28 @@ var ts; return getStringFromExpandedCharCodes(expandedCharCodes); } ts.base64decode = base64decode; + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + ts.readJson = readJson; + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11352,6 +11764,8 @@ var ts; * @param end The end position. */ function createRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos || end === -1); return { pos: pos, end: end }; } ts.createRange = createRange; @@ -11527,6 +11941,8 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { + case 193 /* ParenthesizedExpression */: + return accessKind(parent); case 201 /* PostfixUnaryExpression */: case 200 /* PrefixUnaryExpression */: var operator = parent.operator; @@ -11538,12 +11954,34 @@ var ts; : 0 /* Read */; case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); + case 273 /* PropertyAssignment */: { + var parentAccess = accessKind(parent.parent); + // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; + } + case 274 /* ShorthandPropertyAssignment */: + // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. + return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent); + case 185 /* ArrayLiteralExpression */: + return accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && skipParenthesesUp(parent.parent).kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + } + } + function reverseAccessKind(a) { + switch (a) { + case 0 /* Read */: + return 1 /* Write */; + case 1 /* Write */: + return 0 /* Read */; + case 2 /* ReadWrite */: + return 2 /* ReadWrite */; + default: + return ts.Debug.assertNever(a); } } function compareDataObjects(dst, src) { @@ -11769,13 +12207,6 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; - /* @internal */ - function createTextRange(pos, end) { - if (end === void 0) { end = pos; } - ts.Debug.assert(end >= pos); - return { pos: pos, end: end }; - } - ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -12103,13 +12534,13 @@ var ts; if (ts.isDeclaration(hostNode)) { return getDeclarationIdentifier(hostNode); } - // Covers remaining cases + // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } - return undefined; + break; case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { @@ -12121,9 +12552,7 @@ var ts; return arg; } } - return undefined; - case 1 /* EndOfFileToken */: - return undefined; + break; case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } @@ -12131,10 +12560,8 @@ var ts; if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } - return undefined; + break; } - default: - ts.Debug.assertNever(hostNode, "Found typedef tag attached to node which it should not be!"); } } function getDeclarationIdentifier(node) { @@ -12165,7 +12592,7 @@ var ts; } case 202 /* BinaryExpression */: { var expr = declaration; - switch (ts.getSpecialPropertyAssignmentKind(expr)) { + switch (ts.getAssignmentDeclarationKind(expr)) { case 1 /* ExportsProperty */: case 4 /* ThisProperty */: case 5 /* Property */: @@ -12211,15 +12638,14 @@ var ts; /** * Gets the JSDoc parameter tags for the node if present. * - * @remarks Returns any JSDoc param tag that matches the provided + * @remarks Returns any JSDoc param tag whose name matches the provided * parameter, whether a param tag on a containing function * expression, or a param tag on a variable declaration whose * initializer is the containing function. The tags closest to the * node are returned first, so in the previous example, the param * tag on the containing function expression would be first. * - * Does not return tags for binding patterns, because JSDoc matches - * parameters by name and binding patterns do not have a name. + * For binding patterns, parameter tags are matched by position. */ function getJSDocParameterTags(param) { if (param.name) { @@ -12240,6 +12666,23 @@ var ts; return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** + * Gets the JSDoc type parameter tags for the node if present. + * + * @remarks Returns any JSDoc template tag whose names match the provided + * parameter, whether a template tag on a containing function + * expression, or a template tag on a variable declaration whose + * initializer is the containing function. The tags closest to the + * node are returned first, so in the previous example, the template + * tag on the containing function expression would be first. + */ + function getJSDocTypeParameterTags(param) { + var name = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { + return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; }); + }); + } + ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags; /** * Return true if the node has JSDoc parameter tags. * @@ -12366,7 +12809,20 @@ var ts; ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } - return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + if (node.typeParameters) { + return node.typeParameters; + } + if (ts.isInJSFile(node)) { + var decls = ts.getJSDocTypeParameterDeclarations(node); + if (decls.length) { + return decls; + } + var typeTag = getJSDocType(node); + if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) { + return typeTag.typeParameters; + } + } + return ts.emptyArray; } ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getEffectiveConstraintOfTypeParameter(node) { @@ -13712,7 +14168,7 @@ var ts; /* @internal */ function isDeclaration(node) { if (node.kind === 148 /* TypeParameter */) { - return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + return node.parent.kind !== 301 /* JSDocTemplateTag */ || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14105,6 +14561,18 @@ var ts; return moduleResolution; } ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function hasJsonModuleEmitEnabled(options) { + switch (getEmitModuleKind(options)) { + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.AMD: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + return true; + default: + return false; + } + } + ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled; function unreachableCodeIsError(options) { return options.allowUnreachableCode === false; } @@ -14121,9 +14589,8 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop || + moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getEmitDeclarations(compilerOptions) { @@ -14135,13 +14602,14 @@ var ts; } ts.getStrictOptionValue = getStrictOptionValue; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { - if (oldOptions === newOptions) { - return false; - } - return ts.optionDeclarations.some(function (option) { return (!!option.strictFlag && getStrictOptionValue(newOptions, option.name) !== getStrictOptionValue(oldOptions, option.name)) || - (!!option.affectsSemanticDiagnostics && !newOptions[option.name] !== !oldOptions[option.name]); }); + return oldOptions !== newOptions && + ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !ts.isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); }); } ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics; + function getCompilerOptionValue(options, option) { + return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name]; + } + ts.getCompilerOptionValue = getCompilerOptionValue; function hasZeroOrOneAsteriskCharacter(str) { var seenAsterisk = false; for (var i = 0; i < str.length; i++) { @@ -14414,8 +14882,6 @@ var ts; if (pathComponents.length === 0) return ""; var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - if (pathComponents.length === 1) - return root; return root + pathComponents.slice(1).join(ts.directorySeparator); } ts.getPathFromPathComponents = getPathFromPathComponents; @@ -14637,6 +15103,13 @@ var ts; // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. var reservedCharacterPattern = /[^\w\s\/]/g; + function regExpEscape(text) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + ts.regExpEscape = regExpEscape; + function escapeRegExpCharacter(match) { + return "\\" + match; + } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; function hasExtension(fileName) { return ts.stringContains(getBaseFileName(fileName), "."); @@ -14697,6 +15170,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -14923,36 +15397,57 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var allSupportedExtensions = ts.supportedTSExtensions.concat(ts.supportedJSExtensions); + var allSupportedExtensionsWithJson = ts.supportedTSExtensions.concat(ts.supportedJSExtensions, [".json" /* Json */]); function getSupportedExtensions(options, extraFileExtensions) { var needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions; } - var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; })); return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } ts.getSupportedExtensions = getSupportedExtensions; - function isJavaScriptLike(scriptKind) { + function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { + if (!options || !options.resolveJsonModule) { + return supportedExtensions; + } + if (supportedExtensions === allSupportedExtensions) { + return allSupportedExtensionsWithJson; + } + if (supportedExtensions === ts.supportedTSExtensions) { + return ts.supportedTSExtensionsWithJson; + } + return supportedExtensions.concat([".json" /* Json */]); + } + ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule; + function isJSLike(scriptKind) { return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; } - function hasJavaScriptFileExtension(fileName) { - return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + function hasJSFileExtension(fileName) { + return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + ts.hasJSFileExtension = hasJSFileExtension; + function hasJSOrJsonFileExtension(fileName) { + return ts.supportedJSAndJsonExtensions.some(function (ext) { return ts.fileExtensionIs(fileName, ext); }); } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + ts.hasJSOrJsonFileExtension = hasJSOrJsonFileExtension; + function hasTSFileExtension(fileName) { + return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTSFileExtension = hasTSFileExtension; function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { if (!fileName) { return false; } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); + for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) { var extension = _a[_i]; if (ts.fileExtensionIs(fileName, extension)) { return true; @@ -15080,14 +15575,14 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { + function extensionIsTS(ext) { return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } - ts.extensionIsTypeScript = extensionIsTypeScript; - function resolutionExtensionIsTypeScriptOrJson(ext) { - return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + ts.extensionIsTS = extensionIsTS; + function resolutionExtensionIsTSOrJson(ext) { + return extensionIsTS(ext) || ext === ".json" /* Json */; } - ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson; /** * Gets the extension from a path. * Path must have a valid extension. @@ -15258,6 +15753,22 @@ var ts; return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib; } ts.skipTypeChecking = skipTypeChecking; + function isJsonEqual(a, b) { + return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual); + } + ts.isJsonEqual = isJsonEqual; + function getOrUpdate(map, key, getDefault) { + var got = map.get(key); + if (got === undefined) { + var value = getDefault(); + map.set(key, value); + return value; + } + else { + return got; + } + } + ts.getOrUpdate = getOrUpdate; })(ts || (ts = {})); var ts; (function (ts) { @@ -15346,6 +15857,7 @@ var ts; visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); case 275 /* SpreadAssignment */: @@ -15416,6 +15928,7 @@ var ts; visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.exclamationToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || @@ -15774,7 +16287,7 @@ var ts; ts.performance.mark("beforeParse"); var result; if (languageVersion === 100 /* JSON */) { - result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */); } else { result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); @@ -15943,8 +16456,12 @@ var ts; if (scriptKind === 6 /* JSON */) { var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.referencedFiles = ts.emptyArray; result_1.typeReferenceDirectives = ts.emptyArray; + result_1.libReferenceDirectives = ts.emptyArray; result_1.amdDependencies = ts.emptyArray; + result_1.hasNoDefaultLib = false; + result_1.pragmas = ts.emptyMap; return result_1; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); @@ -16612,7 +17129,15 @@ var ts; // which would be a candidate for improved error reporting. return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + switch (token()) { + case 21 /* OpenBracketToken */: + case 39 /* AsteriskToken */: + case 24 /* DotDotDotToken */: + case 23 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`) + return true; + default: + return isLiteralPropertyName(); + } case 18 /* RestProperties */: return isLiteralPropertyName(); case 9 /* ObjectBindingElements */: @@ -17380,8 +17905,10 @@ var ts; return finishNode(parameter); } function parseJSDocType() { + scanner.setInJSDocType(true); var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); var type = parseTypeOrTypePredicate(); + scanner.setInJSDocType(false); if (dotdotdot) { var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; @@ -19477,8 +20004,9 @@ var ts; var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.exclamationToken = parseOptionalToken(51 /* ExclamationToken */); if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return parseMethodDeclaration(node, asteriskToken); } @@ -20879,7 +21407,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -21004,13 +21532,6 @@ var ts; indent += asterisk.length; } break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; case 5 /* WhitespaceTrivia */: // only collect whitespace if we're already saving comments or have just crossed the comment indent margin var whitespace = scanner.getTokenText(); @@ -21025,7 +21546,9 @@ var ts; case 1 /* EndOfFileToken */: break loop; default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. state = 2 /* SavingComments */; pushComment(scanner.getTokenText()); break; @@ -21096,7 +21619,7 @@ var ts; var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); atToken.end = scanner.getTextPos(); nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); + var tagName = parseJSDocIdentifierName(/*message*/ undefined); skipWhitespaceOrAsterisk(); var tag; switch (tagName.escapedText) { @@ -21277,10 +21800,8 @@ var ts; var result = target === 1 /* Property */ ? createNode(303 /* JSDocPropertyTag */, atToken.pos) : createNode(297 /* JSDocParameterTag */, atToken.pos); - var comment; - if (indent !== undefined) - comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); + var comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -21294,14 +21815,14 @@ var ts; result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name, target) { + function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { if (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) { children = ts.append(children, child); } @@ -21389,7 +21910,7 @@ var ts; } function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); - skipWhitespace(); + skipWhitespaceOrAsterisk(); var typedefTag = createNode(302 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; @@ -21404,7 +21925,7 @@ var ts; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = atToken.pos; - while (child = tryParse(function () { return parseChildPropertyTag(); })) { + while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } @@ -21465,7 +21986,7 @@ var ts; var start = scanner.getStartPos(); var jsdocSignature = createNode(291 /* JSDocSignature */, start); jsdocSignature.parameters = []; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); } var returnTag = tryParse(function () { @@ -21505,17 +22026,17 @@ var ts; } return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(1 /* Property */); + function parseChildPropertyTag(indent) { + return parseChildParameterOrPropertyTag(1 /* Property */, indent); } - function parseChildParameterOrPropertyTag(target, name) { + function parseChildParameterOrPropertyTag(target, indent, name) { var canParseTag = true; var seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { - var child = tryParseChildTag(target); + var child = tryParseChildTag(target, indent); if (child && (child.kind === 297 /* JSDocParameterTag */ || child.kind === 303 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -21543,7 +22064,7 @@ var ts; } } } - function tryParseChildTag(target) { + function tryParseChildTag(target, indent) { ts.Debug.assert(token() === 57 /* AtToken */); var atToken = createNode(57 /* AtToken */); atToken.end = scanner.getTextPos(); @@ -21569,9 +22090,7 @@ var ts; if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken, tagName) { // the template tag looks like '@template {Constraint} T,U,V' @@ -22412,8 +22931,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +22945,42 @@ var ts; shortName: "?", type: "boolean" }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22474,21 +23028,6 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, - }, - { - name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - }, // Basic { name: "target", @@ -22503,6 +23042,8 @@ var ts; es2018: 5 /* ES2018 */, esnext: 6 /* ESNext */, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22521,6 +23062,7 @@ var ts; es2015: ts.ModuleKind.ES2015, esnext: ts.ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22533,6 +23075,7 @@ var ts; name: "lib", type: ts.libMap }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation @@ -22540,6 +23083,7 @@ var ts; { name: "allowJs", type: "boolean", + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Allow_javascript_files_to_be_compiled @@ -22557,6 +23101,7 @@ var ts; "react-native": 3 /* ReactNative */, "react": 2 /* React */ }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -22666,6 +23211,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23220,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23229,24 @@ var ts; { name: "strictFunctionTypes", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, description: ts.Diagnostics.Enable_strict_checking_of_function_types }, + { + name: "strictBindCallApply", + type: "boolean", + strictFlag: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions + }, { name: "strictPropertyInitialization", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22698,6 +23255,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23264,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23298,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23311,7 @@ var ts; node: ts.ModuleResolutionKind.NodeJs, classic: ts.ModuleResolutionKind.Classic, }), + affectsModuleResolution: true, paramType: ts.Diagnostics.STRATEGY, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, @@ -22758,6 +23319,7 @@ var ts; { name: "baseUrl", type: "string", + affectsModuleResolution: true, isFilePath: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names @@ -22767,6 +23329,7 @@ var ts; // use type = object to copy the value as-is name: "paths", type: "object", + affectsModuleResolution: true, isTSConfigOnly: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl @@ -22782,6 +23345,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime }, @@ -22793,6 +23357,7 @@ var ts; type: "string", isFilePath: true }, + affectsModuleResolution: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from }, @@ -22803,6 +23368,7 @@ var ts; name: "types", type: "string" }, + affectsModuleResolution: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation @@ -22887,30 +23453,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Show_verbose_diagnostic_information }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, { name: "resolveJsonModule", type: "boolean", category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", type: "string", @@ -22969,12 +23517,14 @@ var ts; { name: "noLib", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts }, { name: "noResolve", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files }, @@ -22987,6 +23537,7 @@ var ts; { name: "disableSizeLimit", type: "boolean", + affectsSourceFile: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects }, @@ -23032,6 +23583,7 @@ var ts; { name: "allowUnusedLabels", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unused_labels @@ -23039,6 +23591,7 @@ var ts; { name: "allowUnreachableCode", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code @@ -23066,6 +23619,7 @@ var ts; { name: "maxNodeModuleJsDepth", type: "number", + // TODO: GH#27108 affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, @@ -23093,7 +23647,45 @@ var ts; }, description: ts.Diagnostics.List_of_language_service_plugins } - ]; + ]); + /* @internal */ + ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; }); + /* @internal */ + ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; }); + /* @internal */ + ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) { + return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics; + }); + /* @internal */ + ts.buildOpts = ts.commonOptionsWithBuild.concat([ + { + name: "verbose", + shortName: "v", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Enable_verbose_logging, + type: "boolean" + }, + { + name: "dry", + shortName: "d", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" + }, + { + name: "force", + shortName: "f", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" + }, + { + name: "clean", + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" + } + ]); /* @internal */ ts.typeAcquisitionDeclarations = [ { @@ -23146,20 +23738,21 @@ var ts; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; - } + return optionNameMapCache || (optionNameMapCache = createOptionNameMap(ts.optionDeclarations)); + } + /*@internal*/ + function createOptionNameMap(optionDeclarations) { var optionNameMap = ts.createMap(); var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { + ts.forEach(optionDeclarations, function (option) { optionNameMap.set(option.name.toLowerCase(), option); if (option.shortName) { shortOptionNames.set(option.shortName, option.name); } }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; + return { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; } + ts.createOptionNameMap = createOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); @@ -23195,16 +23788,15 @@ var ts; } } ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { + function parseCommandLineWorker(getOptionNameMap, _a, commandLine, readFile) { + var unknownOptionDiagnostic = _a[0], optionTypeMismatchDiagnostic = _a[1]; var options = {}; var fileNames = []; - var projectReferences = undefined; var errors = []; parseStrings(commandLine); return { options: options, fileNames: fileNames, - projectReferences: projectReferences, errors: errors }; function parseStrings(args) { @@ -23216,7 +23808,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + var opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -23224,7 +23816,7 @@ var ts; else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(ts.createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { case "number": @@ -23260,7 +23852,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +23895,19 @@ var ts; parseStrings(args); } } + function parseCommandLine(commandLine, readFile) { + return parseCommandLineWorker(getOptionNameMap, [ + ts.Diagnostics.Unknown_compiler_option_0, + ts.Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } ts.parseCommandLine = parseCommandLine; /** @internal */ function getOptionFromName(optionName, allowShort) { + return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); + } + ts.getOptionFromName = getOptionFromName; + function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) { if (allowShort === void 0) { allowShort = false; } optionName = optionName.toLowerCase(); var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; @@ -23318,7 +23920,35 @@ var ts; } return optionNameMap.get(optionName); } - ts.getOptionFromName = getOptionFromName; + /*@internal*/ + function parseBuildCommand(args) { + var buildOptionNameMap; + var returnBuildOptionNameMap = function () { return (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(ts.buildOpts))); }; + var _a = parseCommandLineWorker(returnBuildOptionNameMap, [ + ts.Diagnostics.Unknown_build_option_0, + ts.Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args), options = _a.options, projects = _a.fileNames, errors = _a.errors; + var buildOptions = options; + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + projects.push("."); + } + // Nonsensical combinations + if (buildOptions.clean && buildOptions.force) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + } + if (buildOptions.clean && buildOptions.verbose) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + } + if (buildOptions.clean && buildOptions.watch) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + } + if (buildOptions.watch && buildOptions.dry) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + } + return { buildOptions: buildOptions, projects: projects, errors: errors }; + } + ts.parseBuildCommand = parseBuildCommand; function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -23632,7 +24262,11 @@ var ts; return result; } function convertArrayLiteralExpressionToJson(elements, elementOption) { - return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + if (!returnValue) { + return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + // Filter out invalid values + return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; }); } function convertPropertyValueToJson(valueExpression, option) { switch (valueExpression.kind) { @@ -23939,7 +24573,8 @@ var ts; var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + var projectReferences; + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; return { options: options, fileNames: fileNames, @@ -23956,8 +24591,22 @@ var ts; if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (ts.isArray(raw.files)) { filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + var hasExtends = ts.hasProperty(raw, "extends"); + if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) { + if (sourceFile) { + var fileName = configFileName || "tsconfig.json"; + var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty; + var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; }); + var error = nodeValue + ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : ts.createCompilerDiagnostic(diagnosticMessage, fileName); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { @@ -23993,19 +24642,18 @@ var ts; includeSpecs = ["**/*"]; } var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) { errors.push(getErrorForNoInputFiles(result.spec, configFileName)); } if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (ts.isArray(raw.references)) { - var references = []; for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { var ref = _a[_i]; if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: ts.getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -24013,7 +24661,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +24674,33 @@ var ts; } } } - /*@internal*/ function isErrorNoInputFiles(error) { return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ function getErrorForNoInputFiles(_a, configFileName) { var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) { + return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); + } + /*@internal*/ + function canJsonReportNoInutFiles(raw) { + return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references"); + } + ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles; + /*@internal*/ + function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) { + var existingErrors = configParseDiagnostics.length; + if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) { + configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + else { + ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); }); + } + return existingErrors !== configParseDiagnostics.length; + } + ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles; function isSuccessfulParsedTsconfig(value) { return !!value.options; } @@ -24123,11 +24786,6 @@ var ts; return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); }); return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { @@ -24174,7 +24832,7 @@ var ts; var _a; var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + sourceFile.extendedSourceFiles = [extendedResult.fileName]; } if (extendedResult.parseDiagnostics.length) { errors.push.apply(errors, extendedResult.parseDiagnostics); @@ -24182,7 +24840,7 @@ var ts; } var extendedDirname = ts.getDirectoryPath(extendedConfigPath); var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { + if (sourceFile && extendedResult.extendedSourceFiles) { (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); } if (isSuccessfulParsedTsconfig(extendedConfig)) { @@ -24396,7 +25054,7 @@ var ts; // or a recursive directory. This information is used by filesystem watchers to monitor for // new entries in these paths. var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } /** @@ -24421,10 +25079,15 @@ var ts; // file map with a possibly case insensitive key. We use this map to store paths matched // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); + // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard of *.json kind + var wildCardJsonFileMap = ts.createMap(); var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; // Rather than requery this for each file and filespec, we query the supported extensions // once and store it on the expansion context. var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Literal files are always included verbatim. An "include" or "exclude" specification cannot // remove a literal file. if (filesSpecs) { @@ -24434,9 +25097,25 @@ var ts; literalFileMap.set(keyMapper(file), file); } } + var jsonOnlyIncludeRegexes; if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; + var _loop_4 = function (file) { + if (ts.fileExtensionIs(file, ".json" /* Json */)) { + // Valid only if *.json specified + if (!jsonOnlyIncludeRegexes) { + var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; + } + var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); + if (includeIndex !== -1) { + var key_1 = keyMapper(file); + if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) { + wildCardJsonFileMap.set(key_1, file); + } + } + return "continue"; + } // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. // @@ -24444,7 +25123,7 @@ var ts; // .d.ts (or .js if "allowJs" is enabled) in the same // directory when they are compilation outputs. if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { - continue; + return "continue"; } // We may have included a wildcard path with a lower priority // extension due to the user-defined order of entries in the @@ -24455,16 +25134,16 @@ var ts; if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { wildcardFileMap.set(key, file); } + }; + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + _loop_4(file); } } var literalFiles = ts.arrayFrom(literalFileMap.values()); var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); - var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { - return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); - }); return { - fileNames: literalFiles.concat(wildcardFiles), - projectReferences: projectReferences, + fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())), wildcardDirectories: wildcardDirectories, spec: spec }; @@ -24653,6 +25332,12 @@ var ts; function noPackageId(r) { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r) { + if (r) { + ts.Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } /** * Kinds of file that we are currently looking for. * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. @@ -24669,7 +25354,7 @@ var ts; if (!resolved) { return undefined; } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { @@ -24678,48 +25363,94 @@ var ts; failedLookupLocations: failedLookupLocations }; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, jsonContent, baseDirectory, state) { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (!ts.isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { + if (!ts.hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + var value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } + function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) { + var fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) + return; + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + function readPackageJsonTypesFields(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent, baseDirectory, state) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + function readPackageJsonTypesVersionsField(jsonContent, state) { + var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + return typesVersions; + } + function readPackageJsonTypesVersionPaths(jsonContent, state) { + var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) + return; + if (state.traceEnabled) { + for (var key in typesVersions) { + if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + var result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor); + } + return; + } + var bestVersionKey = result.version, bestVersionPaths = result.paths; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + } + return; + } + return result; + } + var typeScriptVersion; /* @internal */ - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - if (!jsonText) - return {}; - var result = ts.parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function getPackageJsonTypesVersionsPaths(typesVersions) { + if (!typeScriptVersion) + typeScriptVersion = new ts.Version(ts.version); + for (var key in typesVersions) { + if (!ts.hasProperty(typesVersions, key)) + continue; + var keyRange = ts.VersionRange.tryParse(key); + if (keyRange === undefined) { + continue; + } + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } - return result.config; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; } } - ts.readJson = readJson; + ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -24763,7 +25494,8 @@ var ts; */ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -24783,7 +25515,6 @@ var ts; } } } - var failedLookupLocations = []; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -24810,11 +25541,11 @@ var ts; return ts.forEach(typeRoots, function (typeRoot) { var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); + var directoryExists = ts.directoryProbablyExists(candidateDirectory, host); if (!directoryExists && traceEnabled) { trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } else { @@ -24830,7 +25561,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + var result = void 0; + if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) { + result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); + } + else { + var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path; + result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + } var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -24869,14 +25607,18 @@ var ts; for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { var typeDirectivePath = _b[_a]; var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var packageJsonPath = ts.combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); + var baseFileName = ts.getBaseFileName(normalized); + // At this stage, skip results with leading dot. + if (baseFileName.charCodeAt(0) !== 46 /* dot */) { + // Return just the type directive names + result.push(baseFileName); + } } } } @@ -25099,15 +25841,15 @@ var ts; * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { if (!ts.isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) { if (!state.compilerOptions.rootDirs) { return undefined; } @@ -25145,7 +25887,7 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -25164,7 +25906,7 @@ var ts; trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); } var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName_1) { return resolvedFileName_1; } @@ -25175,74 +25917,60 @@ var ts; } return undefined; } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) { + var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - // string is for exact match - var matchedPattern; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + var resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - var extension = ts.tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path_1 !== undefined) { - return noPackageId({ path: path_1, ext: extension }); - } - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } + return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; /** * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 * Throws an error if the module can't be resolved. */ /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + function resolveJSModule(moduleName, initialDir, host) { + var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); } return resolvedModule.resolvedFileName; } - ts.resolveJavaScriptModule = resolveJavaScriptModule; + ts.resolveJSModule = resolveJSModule; + /* @internal */ + function tryResolveJSModule(moduleName, initialDir, host) { + var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; + return resolvedModule && resolvedModule.resolvedFileName; + } + ts.tryResolveJSModule = tryResolveJSModule; + function tryResolveJSModuleWorker(moduleName, initialDir, host) { + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, jsOnly) { var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || @@ -25254,8 +25982,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: ts.stringContains(resolved.path, ts.nodeModulesPathPart) }); } @@ -25263,7 +25991,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved_1) return undefined; var resolvedValue = resolved_1.value; @@ -25277,7 +26005,7 @@ var ts; } else { var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts; - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") }); } @@ -25294,29 +26022,30 @@ var ts; ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); } onlyRecordFailures = true; } } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + var packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + var packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); + var candidateExists = ts.directoryProbablyExists(candidate, state.host); if (!candidateExists) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); @@ -25324,7 +26053,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ ts.nodeModulesPathPart = "/node_modules/"; @@ -25365,52 +26094,46 @@ var ts; if (ts.endsWith(path, ".d.ts")) { return path; } - if (ts.endsWith(path, "/index")) { + if (path === "index" || ts.endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) { if (extensions === Extensions.Json) { var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { + if (ts.hasJSFileExtension(candidate)) { var extensionless = ts.removeFileExtension(candidate); if (state.traceEnabled) { var extension = candidate.substring(extensionless.length); trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing var directory = ts.getDirectoryPath(candidate); if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); + onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host); } } switch (extensions) { @@ -25424,12 +26147,12 @@ var ts; return tryExtension(".json" /* Json */); } function tryExtension(ext) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + var path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + function tryFile(fileName, onlyRecordFailures, state) { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -25443,40 +26166,33 @@ var ts; } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { if (considerPackageJson === void 0) { considerPackageJson = true; } - var _a = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }, packageJsonContent = _a.packageJsonContent, packageId = _a.packageId; - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + var packageId = packageInfo && packageInfo.packageId; + var packageJsonContent = packageInfo && packageInfo.packageJsonContent; + var versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent) { - var fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function getPackageJsonInfo(nodeModuleDirectory, subModuleName, failedLookupLocations, onlyRecordFailures, state) { + function getPackageJsonInfo(packageDirectory, subModuleName, onlyRecordFailures, state) { var host = state.host, traceEnabled = state.traceEnabled; - var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - var packageJsonPath = pathToPackageJson(nodeModuleDirectory); + var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host); + var packageJsonPath = ts.combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { - var packageJsonContent = readJson(packageJsonPath, host); + var packageJsonContent = ts.readJson(packageJsonPath, host); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - var path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + var path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); - subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + var jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + var potentialSubModule_1 = jsPath.substring(packageDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJSExtensions, function (extension) { return ts.tryRemoveExtension(potentialSubModule_1, extension); }) || potentialSubModule_1) + ".d.ts" /* Dts */; } @@ -25488,6 +26204,7 @@ var ts; if (!ts.endsWith(subModuleName, ".d.ts" /* Dts */)) { subModuleName = addExtensionAndIndex(subModuleName); } + var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; @@ -25499,51 +26216,56 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; + return { packageJsonContent: packageJsonContent, packageId: packageId, versionPaths: versionPaths }; } else { if (directoryExists && traceEnabled) { trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { + function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) { + var packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) || // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); - if (!file) { - return undefined; + (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) + : readPackageJsonMainField(jsonContent, candidate, state)); + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + var resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); } } - else { - return undefined; - } - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined; + var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host); + var indexPath = ts.combinePaths(candidate, "index"); + if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) { + var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, moduleName); + } + var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - var result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - ts.Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); + if (packageFileResult) + return packageFileResult; + return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { @@ -25563,87 +26285,129 @@ var ts; return extension === ".d.ts" /* Dts */; } } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - var packageJsonContent; - var packageId; - var packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId); - } - else { - var _a = getPackageName(moduleName), packageName = _a.packageName, rest = _a.rest; - if (rest !== "") { // If "rest" is empty, we just did this search above. - var packageRootPath = ts.combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; - } - } - var pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } /* @internal */ - function getPackageName(moduleName) { + function parsePackageName(moduleName) { var idx = moduleName.indexOf(ts.directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(ts.directorySeparator, idx + 1); } return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - ts.getPackageName = getPackageName; - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + ts.parsePackageName = parsePackageName; + function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache) { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache) { var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } + function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) { var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state); + } + } + function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName)); + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + var packageJsonContent; + var packageId; + var versionPaths; + var packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + (packageJsonContent = packageInfo.packageJsonContent, packageId = packageInfo.packageId, versionPaths = packageInfo.versionPaths); + var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + var loader = function (extensions, candidate, onlyRecordFailures, state) { + var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest; + if (rest !== "") { // If "rest" is empty, we just did this search above. + var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName); + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + var packageInfo_1 = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo_1) + (packageId = packageInfo_1.packageId, versionPaths = packageInfo_1.versionPaths); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, ts.version, rest); + } + var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host); + var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) { + var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName); + if (matchedPattern) { + var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + var resolved = ts.forEach(paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, onlyRecordFailures, state); + if (path_1 !== undefined) { + return noPackageId({ path: path_1, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ var mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName, state) { - var mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName, state) { + var mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -25651,11 +26415,11 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + getMangledNameForScopedPackage(packageName); + return "@types/" + mangleScopedPackageName(packageName); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ - function getMangledNameForScopedPackage(packageName) { + function mangleScopedPackageName(packageName) { if (ts.startsWith(packageName, "@")) { var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -25664,43 +26428,44 @@ var ts; } return packageName; } - ts.getMangledNameForScopedPackage = getMangledNameForScopedPackage; + ts.mangleScopedPackageName = mangleScopedPackageName; /* @internal */ - function getPackageNameFromAtTypesDirectory(mangledName) { + function getPackageNameFromTypesPackageName(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } - ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName; /* @internal */ - function getUnmangledNameForScopedPackage(typesPackageName) { + function unmangleScopedPackageName(typesPackageName) { return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : typesPackageName; } - ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host, failedLookupLocations) { + ts.unmangleScopedPackageName = unmangleScopedPackageName; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { + var _a; var result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push.apply(failedLookupLocations, result.failedLookupLocations); + (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -25708,24 +26473,24 @@ var ts; var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, traceEnabled, host, failedLookupLocations); + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved_3) { return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -25740,9 +26505,9 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; + var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; @@ -25957,13 +26722,17 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } + if (symbolFlags & 67220415 /* Value */) { + setValueDeclaration(symbol, node); + } + } + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } // Should not be called on a declaration with a computed property name, @@ -26008,7 +26777,7 @@ var ts; // module.exports = ... return "export=" /* ExportEquals */; case 202 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) { // module.exports = ... return "export=" /* ExportEquals */; } @@ -26088,7 +26857,8 @@ var ts; // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); } - else { + else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (ts.isNamedDeclaration(node)) { node.name.parent = node; } @@ -26166,12 +26936,12 @@ var ts; // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. if (ts.isJSDocTypeAlias(node)) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! } - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var exportKind = symbolFlags & 67220415 /* Value */ ? 1048576 /* ExportValue */ : 0; var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; @@ -26334,6 +27104,7 @@ var ts; function bindChildrenWorker(node) { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -26432,6 +27203,8 @@ var ts; return isNarrowingBinaryExpression(expr); case 200 /* PrefixUnaryExpression */: return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + case 197 /* TypeOfExpression */: + return isNarrowingExpression(expr.expression); } return false; } @@ -26834,7 +27607,6 @@ var ts; } var preCaseLabel = createBranchLabel(); addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); addAntecedent(preCaseLabel, fallthroughFlow); currentFlow = finishFlowLabel(preCaseLabel); var clause = clauses[i]; @@ -27230,7 +28002,7 @@ var ts; errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); } } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */); file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); } } @@ -27250,7 +28022,7 @@ var ts; function declareModuleSymbol(node) { var state = getModuleInstanceState(node); var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); return state; } function bindFunctionOrConstructorType(node) { @@ -27338,9 +28110,6 @@ var ts; declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -27360,7 +28129,7 @@ var ts; bind(typeAlias.typeExpression); if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { parent = typeAlias.parent; - bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); } else { bind(typeAlias.fullName); @@ -27585,7 +28354,7 @@ var ts; } function bindJSDoc(node) { if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var j = _a[_i]; bind(j); @@ -27632,7 +28401,7 @@ var ts; while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); break; } // falls through @@ -27649,15 +28418,15 @@ var ts; if (ts.isSpecialPropertyDeclaration(node)) { bindSpecialPropertyDeclaration(node); } - if (ts.isInJavaScriptFile(node) && + if (ts.isInJSFile(node) && file.commonJsModuleIndicator && ts.isModuleExportsPropertyAccessExpression(node) && - !lookupSymbolForNameWorker(container, "module")) { - declareSymbol(container.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67216318 /* FunctionScopedVariableExcludes */); + !lookupSymbolForNameWorker(blockScopeContainer, "module")) { + declareSymbol(file.locals, /*parent*/ undefined, node.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 67220414 /* FunctionScopedVariableExcludes */); } break; case 202 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); + var specialKind = ts.getAssignmentDeclarationKind(node); switch (specialKind) { case 1 /* ExportsProperty */: bindExportsPropertyAssignment(node); @@ -27730,15 +28499,15 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67212223 /* MethodExcludes */); case 237 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 155 /* Constructor */: return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); case 156 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67154879 /* GetAccessorExcludes */); case 157 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 163 /* FunctionType */: case 287 /* JSDocFunctionType */: case 291 /* JSDocSignature */: @@ -27754,7 +28523,7 @@ var ts; case 195 /* ArrowFunction */: return bindFunctionExpression(node); case 189 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { bindCallExpression(node); } break; @@ -27765,9 +28534,9 @@ var ts; inStrictMode = true; return bindClassLikeDeclaration(node); case 239 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67897736 /* InterfaceExcludes */); case 240 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67897832 /* TypeAliasExcludes */); case 241 /* EnumDeclaration */: return bindEnumDeclaration(node); case 242 /* ModuleDeclaration */: @@ -27848,37 +28617,35 @@ var ts; bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); } else { - var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + var flags = ts.exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? 2097152 /* Alias */ // An export default clause with any other expression exports a value : 4 /* Property */; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } function bindNamespaceExportDeclaration(node) { if (node.modifiers && node.modifiers.length) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); } - if (node.parent.kind !== 277 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; + var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level + : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files + : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files + : undefined; + if (diag) { + file.bindDiagnostics.push(createDiagnosticForNode(node, diag)); } else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { @@ -27914,7 +28681,7 @@ var ts; var lhs = node.left; var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { if (symbol) { - addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */); } return symbol; }); @@ -27944,7 +28711,7 @@ var ts; declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); } function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); + ts.Debug.assert(ts.isInJSFile(node)); var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case 237 /* FunctionDeclaration */: @@ -28001,7 +28768,7 @@ var ts; node.left.parent = node; node.right.parent = node; var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. @@ -28022,7 +28789,7 @@ var ts; var lhs = node.left; // Class declarations in Typescript do not allow property declarations var parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!ts.isInJavaScriptFile(node) && !ts.isFunctionSymbol(parentSymbol)) { + if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -28048,40 +28815,39 @@ var ts; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); - var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && - !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + var isToplevel = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ : propertyAccess.parent.parent.kind === 277 /* SourceFile */; - if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */))) { // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */; + var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { if (symbol) { addDeclarationToSymbol(symbol, id, flags_1); return symbol; } else { - return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + var table = parent ? parent.exports : + file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable()); + return declareSymbol(table, parent, id, flags_1, excludeFlags_1); } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } // Set up the members collection if it doesn't exist already var symbolTable = isPrototypeProperty ? (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); - // Declare the method/property - var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; - var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); - var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; - var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(propertyAccess)); + var includes = isMethod ? 8192 /* Method */ : 4 /* Property */; + var excludes = isMethod ? 67212223 /* MethodExcludes */ : 0 /* PropertyExcludes */; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -28090,7 +28856,7 @@ var ts; * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol) { + function isExpandoSymbol(symbol) { if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { return true; } @@ -28103,7 +28869,7 @@ var ts; init = init && ts.getRightMostAssignedExpression(init); if (init) { var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); - return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); } return false; } @@ -28187,8 +28953,11 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { + var isEnum = ts.isInJSFile(node) && !!ts.getJSDocEnumTag(node); + var enumFlags = (isEnum ? 256 /* RegularEnum */ : 0 /* None */); + var enumExcludes = (isEnum ? 68008191 /* RegularEnumExcludes */ : 0 /* None */); if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */ | enumFlags, 67220415 /* BlockScopedVariableExcludes */ | enumExcludes); } else if (ts.isParameterDeclaration(node)) { // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration @@ -28200,10 +28969,10 @@ var ts; // function foo([a,a]) {} // Duplicate Identifier error // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */ | enumFlags, 67220414 /* FunctionScopedVariableExcludes */ | enumExcludes); } } } @@ -28220,7 +28989,7 @@ var ts; bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220415 /* ParameterExcludes */); } // If this is a property-parameter, then also declare the property symbol into the // containing class. @@ -28238,10 +29007,10 @@ var ts; checkStrictModeFunctionName(node); if (inStrictMode) { checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + bindBlockScopedDeclaration(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67219887 /* FunctionExcludes */); } } function bindFunctionExpression(node) { @@ -28279,10 +29048,10 @@ var ts; if (!container_1.locals) { container_1.locals = ts.createSymbolTable(); } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } else if (node.parent.kind === 174 /* InferType */) { @@ -28291,14 +29060,14 @@ var ts; if (!container_2.locals) { container_2.locals = ts.createSymbolTable(); } - declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } else { bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 } } else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67635688 /* TypeParameterExcludes */); } } // reachability checks @@ -28317,9 +29086,7 @@ var ts; // report error on class declarations node.kind === 238 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { @@ -28357,7 +29124,7 @@ var ts; // As opposed to a pure declaration like an `interface` function isExecutableStatement(s) { // Don't remove statements that can validly be used before they appear. - return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) && // `var x;` may declare a variable used above !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); } @@ -28395,6 +29162,9 @@ var ts; if (local) { return local.exportSymbol || local; } + if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) { + return container.jsGlobalAugmentations.get(name); + } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } /** @@ -28470,40 +29240,40 @@ var ts; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */ + || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; // super property or element accesses could be inside lambdas, etc, and need a captured `this`, // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (expression.transformFlags & 67108864 /* ContainsSuper */) { + transformFlags |= 8192 /* ContainsLexicalThis */; } } if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; + transformFlags |= 16777216 /* ContainsDynamicImport */; // A dynamic 'import()' call that contains a lexical 'this' will // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 524288 /* ContainsSpread */) { + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28524,7 +29294,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28535,25 +29305,25 @@ var ts; // syntax. if (node.questionToken || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ + || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; + return transformFlags & ~637535553 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28588,35 +29358,35 @@ var ts; // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. var transformFlags = subtreeFlags | 192 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { transformFlags |= 3 /* AssertTypeScript */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; + return transformFlags & ~638121281 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28634,7 +29404,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28645,7 +29415,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; + return transformFlags & ~637797697 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -28657,7 +29427,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28667,11 +29437,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; + return transformFlags & ~653616449 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -28687,7 +29457,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // An async method declaration is ES2017 syntax. @@ -28698,7 +29468,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28712,11 +29482,11 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -28724,10 +29494,10 @@ var ts; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; + transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -28739,7 +29509,7 @@ var ts; transformFlags = 3 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ @@ -28752,13 +29522,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionDeclaration is generator function and is the body of a @@ -28771,7 +29541,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28787,13 +29557,13 @@ var ts; transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; } // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { transformFlags |= 192 /* AssertES2015 */; } // If a FunctionExpression is generator function and is the body of a @@ -28803,7 +29573,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; + return transformFlags & ~653620545 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -28820,26 +29590,28 @@ var ts; transformFlags |= 16 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { + transformFlags |= 16384 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + return transformFlags & ~653604161 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (transformFlags & 33554432 /* Super */) { + transformFlags ^= 33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28847,18 +29619,20 @@ var ts; var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; + if (expressionFlags & 33554432 /* Super */) { + transformFlags &= ~33554432 /* Super */; + // super inside of an async function requires hoisting the super access (ES2017). + // same for super inside of an async generator, which is ESNext. + transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; + return transformFlags & ~570426689 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { transformFlags |= 8 /* AssertESNext */; } // Type annotations are TypeScript syntax. @@ -28866,7 +29640,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -28877,22 +29651,22 @@ var ts; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28901,7 +29675,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -28912,7 +29686,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; + return transformFlags & ~637535553 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -28921,24 +29695,24 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; + return transformFlags & ~647001409 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { transformFlags |= 192 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; + var excludeFlags = 637535553 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 199 /* AwaitExpression */: @@ -29012,7 +29786,7 @@ var ts; case 205 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; break; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: @@ -29059,8 +29833,8 @@ var ts; // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 524288 /* ContainsComputedPropertyName */; + if (subtreeFlags & 8192 /* ContainsLexicalThis */) { // A computed method name like `[this.getName()](x: string) { ... }` needs to // distinguish itself from the normal case of a method body containing `this`: // `this` inside a method doesn't need to be rewritten (the method provides `this`), @@ -29069,58 +29843,58 @@ var ts; // `_this = this; () => class K { [_this.getName()]() { ... } }` // To make this distinction, use ContainsLexicalThisInComputedPropertyName // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; } break; case 206 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; break; case 275 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; break; case 182 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; } - excludeFlags = 940049729 /* BindingPatternExcludes */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 183 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; + transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + excludeFlags = 637666625 /* BindingPatternExcludes */; break; case 184 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; + transformFlags |= 131072 /* ContainsRestOrSpread */; } break; case 150 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; break; case 186 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + excludeFlags = 638358849 /* ObjectLiteralExcludes */; + if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. transformFlags |= 192 /* AssertES2015 */; } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { // A computed property name containing `this` might need to be rewritten, // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; + transformFlags |= 8192 /* ContainsLexicalThis */; } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES next node. transformFlags |= 8 /* AssertESNext */; @@ -29128,8 +29902,8 @@ var ts; break; case 185 /* ArrayLiteralExpression */: case 190 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { + excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; @@ -29140,22 +29914,22 @@ var ts; case 223 /* ForStatement */: case 224 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { transformFlags |= 192 /* AssertES2015 */; } break; case 277 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { transformFlags |= 192 /* AssertES2015 */; } break; case 228 /* ReturnStatement */: // Return statements may require an `await` in ESNext. - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; break; case 226 /* ContinueStatement */: case 227 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -29177,27 +29951,27 @@ var ts; case 189 /* CallExpression */: case 190 /* NewExpression */: case 185 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; case 242 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; + return 647001409 /* ModuleExcludes */; case 149 /* Parameter */: - return 939525441 /* ParameterExcludes */; + return 637535553 /* ParameterExcludes */; case 195 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; + return 653604161 /* ArrowFunctionExcludes */; case 194 /* FunctionExpression */: case 237 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; + return 653620545 /* FunctionExcludes */; case 236 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; + return 639894849 /* VariableDeclarationListExcludes */; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: - return 942011713 /* ClassExcludes */; + return 638121281 /* ClassExcludes */; case 155 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; + return 653616449 /* ConstructorExcludes */; case 154 /* MethodDeclaration */: case 156 /* GetAccessor */: case 157 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; + return 653616449 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: @@ -29216,12 +29990,12 @@ var ts; case 240 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 186 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; + return 638358849 /* ObjectLiteralExcludes */; case 272 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; + return 637797697 /* CatchClauseExcludes */; case 182 /* ObjectBindingPattern */: case 183 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; + return 637666625 /* BindingPatternExcludes */; case 192 /* TypeAssertionExpression */: case 210 /* AsExpression */: case 306 /* PartiallyEmittedExpression */: @@ -29230,9 +30004,9 @@ var ts; return 536872257 /* OuterExpressionExcludes */; case 187 /* PropertyAccessExpression */: case 188 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; + return 570426689 /* PropertyAccessExcludes */; default: - return 939525441 /* NodeExcludes */; + return 637535553 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -29447,6 +30221,18 @@ var ts; } ts.isInstantiatedModule = isInstantiatedModule; function createTypeChecker(host, produceDiagnostics) { + var getPackagesSet = ts.memoize(function () { + var set = ts.createMap(); + host.getSourceFiles().forEach(function (sf) { + if (!sf.resolvedModules) + return; + ts.forEachEntry(sf.resolvedModules, function (r) { + if (r && r.packageId) + set.set(r.packageId.name, true); + }); + }); + return set; + }); // Cancellation that controls whether or not we can cancel in the middle of type checking. // In general cancelling is *not* safe for the type checker. We might be in the middle of // computing something, and we will leave our internals in an inconsistent state. Callers @@ -29467,7 +30253,8 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; - var symbolInstantiationDepth = 0; + var instantiationDepth = 0; + var constraintDepth = 0; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -29476,6 +30263,7 @@ var ts; var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); + var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); @@ -29683,8 +30471,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, - getFalseType: function () { return falseType; }, - getTrueType: function () { return trueType; }, + getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; }, + getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -29752,7 +30540,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29782,8 +30571,21 @@ var ts; var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var regularFalseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); - var booleanType = createBooleanType([falseType, trueType]); + var regularTrueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + falseType.flags |= 33554432 /* FreshLiteral */; + trueType.flags |= 33554432 /* FreshLiteral */; + trueType.regularType = regularTrueType; + regularTrueType.freshType = trueType; + falseType.regularType = regularFalseType; + regularFalseType.freshType = falseType; + var booleanType = createBooleanType([regularFalseType, regularTrueType]); + // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` + // (The union is cached, so simply doing the marking here is sufficient) + createBooleanType([regularFalseType, trueType]); + createBooleanType([falseType, regularTrueType]); + createBooleanType([falseType, trueType]); var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); var voidType = createIntrinsicType(4096 /* Void */, "void"); var neverType = createIntrinsicType(32768 /* Never */, "never"); @@ -29817,6 +30619,7 @@ var ts; var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var globals = ts.createSymbolTable(); + /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; @@ -29828,6 +30631,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +30651,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +30663,6 @@ var ts; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; var deferredGlobalExtractSymbol; - var deferredNodes; var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; @@ -29946,6 +30751,8 @@ var ts; TypeFacts[TypeFacts["FunctionFacts"] = 4181984] = "FunctionFacts"; TypeFacts[TypeFacts["UndefinedFacts"] = 2457472] = "UndefinedFacts"; TypeFacts[TypeFacts["NullFacts"] = 2340752] = "NullFacts"; + TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 4079615] = "EmptyObjectStrictFacts"; + TypeFacts[TypeFacts["EmptyObjectFacts"] = 4194303] = "EmptyObjectFacts"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = ts.createMapFromTemplate({ string: 1 /* TypeofEQString */, @@ -29988,6 +30795,8 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType"; + TypeSystemPropertyName[TypeSystemPropertyName["JSDocTypeReference"] = 6] = "JSDocTypeReference"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -30123,35 +30932,35 @@ var ts; function getExcludedSymbolFlags(flags) { var result = 0; if (flags & 2 /* BlockScopedVariable */) - result |= 67216319 /* BlockScopedVariableExcludes */; + result |= 67220415 /* BlockScopedVariableExcludes */; if (flags & 1 /* FunctionScopedVariable */) - result |= 67216318 /* FunctionScopedVariableExcludes */; + result |= 67220414 /* FunctionScopedVariableExcludes */; if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; if (flags & 8 /* EnumMember */) result |= 68008959 /* EnumMemberExcludes */; if (flags & 16 /* Function */) - result |= 67215791 /* FunctionExcludes */; + result |= 67219887 /* FunctionExcludes */; if (flags & 32 /* Class */) result |= 68008383 /* ClassExcludes */; if (flags & 64 /* Interface */) - result |= 67901832 /* InterfaceExcludes */; + result |= 67897736 /* InterfaceExcludes */; if (flags & 256 /* RegularEnum */) result |= 68008191 /* RegularEnumExcludes */; if (flags & 128 /* ConstEnum */) result |= 68008831 /* ConstEnumExcludes */; if (flags & 512 /* ValueModule */) - result |= 67215503 /* ValueModuleExcludes */; + result |= 110735 /* ValueModuleExcludes */; if (flags & 8192 /* Method */) - result |= 67208127 /* MethodExcludes */; + result |= 67212223 /* MethodExcludes */; if (flags & 32768 /* GetAccessor */) - result |= 67150783 /* GetAccessorExcludes */; + result |= 67154879 /* GetAccessorExcludes */; if (flags & 65536 /* SetAccessor */) - result |= 67183551 /* SetAccessorExcludes */; + result |= 67187647 /* SetAccessorExcludes */; if (flags & 262144 /* TypeParameter */) - result |= 67639784 /* TypeParameterExcludes */; + result |= 67635688 /* TypeParameterExcludes */; if (flags & 524288 /* TypeAlias */) - result |= 67901928 /* TypeAliasExcludes */; + result |= 67897832 /* TypeAliasExcludes */; if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; @@ -30184,7 +30993,7 @@ var ts; */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & 67108864 /* JSContainer */) { + (source.flags | target.flags) & 67108864 /* Assignment */) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432 /* Transient */)) { target = cloneSymbol(target); @@ -30197,8 +31006,9 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || + ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules + // other kinds of value declarations take precedence over modules and assignment declarations target.valueDeclaration = source.valueDeclaration; } ts.addRange(target.declarations, source.declarations); @@ -30219,53 +31029,54 @@ var ts; } else { var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); - var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch - if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { - var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; - var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; - var cacheKey = firstFile_1.path + "|" + secondFile.path; - var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; - var symbolName_1 = symbolToString(source); - var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; + var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() }); }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; - targetList.instances.push(errorNode); + var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { + return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); - existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); - amalgamatedDuplicates.set(cacheKey, existing); - return target; + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + } + else { + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } - var symbolName_2 = symbolToString(source); - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); } return target; + function addDuplicateLocations(locs, symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + } + } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { var err = lookupOrIssueError(errorNode, message, symbolName); - if (relatedNode && ts.length(err.relatedInformation) < 5) { + for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { + var relatedNode = _a[_i]; + err.relatedInformation = err.relatedInformation || []; + if (ts.length(err.relatedInformation) >= 5) + continue; addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } @@ -30373,8 +31184,8 @@ var ts; function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { var constructorDeclaration = parameter.parent; var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67216319 /* Value */); - var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67216319 /* Value */); + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 67220415 /* Value */); + var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 67220415 /* Value */); if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } @@ -30517,7 +31328,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -30526,15 +31337,23 @@ var ts; // local types not visible outside the function body : false; } - if (meaning & 67216319 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 149 /* Parameter */ || - (lastLocation === location.type && - !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + if (meaning & result.flags & 3 /* Variable */) { + // expression inside parameter will lookup as normal variable scope when targeting es2015+ + var functionLocation = location; + if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && + functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + useResult = false; + } + else if (result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 149 /* Parameter */ || + (lastLocation === location.type && + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); + } } } else if (location.kind === 173 /* ConditionalType */) { @@ -30612,7 +31431,7 @@ var ts; if (ts.isClassLike(location.parent) && !ts.hasModifier(location, 32 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 67216319 /* Value */)) { + if (lookup(ctor.locals, name, meaning & 67220415 /* Value */)) { // Remember the property node, it will be used later to report appropriate error propertyWithInvalidInitializer = location; } @@ -30622,7 +31441,10 @@ var ts; case 238 /* ClassDeclaration */: case 207 /* ClassExpression */: case 239 /* InterfaceDeclaration */: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 67897832 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; @@ -30649,7 +31471,7 @@ var ts; // The type parameters of a class are not in scope in the base class expression. if (lastLocation === location.expression && location.parent.token === 85 /* ExtendsKeyword */) { var container = location.parent.parent; - if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67901928 /* Type */))) { + if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 67897832 /* Type */))) { if (nameNotFoundMessage) { error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters); } @@ -30669,7 +31491,7 @@ var ts; grandparent = location.parent.parent; if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { + if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67897832 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); return undefined; } @@ -30743,7 +31565,7 @@ var ts; if (!result) { if (lastLocation) { ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); - if (lastLocation.commonJsModuleIndicator && name === "exports") { + if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } } @@ -30752,7 +31574,7 @@ var ts; } } if (!result) { - if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) { if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -30807,14 +31629,14 @@ var ts; // we want to check for block-scoped if (errorLocation && (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67216319 /* Value */) === 67216319 /* Value */))) { + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 67220415 /* Value */) === 67220415 /* Value */))) { var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { + if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 @@ -30910,9 +31732,9 @@ var ts; } } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(errorLocation) ? 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 67220415 /* Value */ : 0); if (meaning === namespaceMeaning) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); var parent = errorLocation.parent; if (symbol) { if (ts.isQualifiedName(parent)) { @@ -30931,29 +31753,32 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */)) { + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); return true; } - var symbol = resolveSymbol(resolveName(errorLocation, name, 67901928 /* Type */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name)); + var message = (name === "Promise" || name === "Symbol") + ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); return true; } } return false; } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (67216319 /* Value */ & ~1024 /* NamespaceModule */ & ~67901928 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (67901928 /* Type */ & ~1024 /* NamespaceModule */ & ~67216319 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67901928 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (67897832 /* Type */ & ~1024 /* NamespaceModule */ & ~67220415 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~67897832 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -30964,7 +31789,7 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) || ts.isInJSFile(d) && !!ts.getJSDocEnumTag(d); }); if (declaration === undefined) return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { @@ -30981,6 +31806,9 @@ var ts; } else { ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); @@ -31050,7 +31878,7 @@ var ts; return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!ts.isSourceFileJavaScript(file)) { + if (!ts.isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -31104,7 +31932,7 @@ var ts; if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { return unknownSymbol; } - if (valueSymbol.flags & (67901928 /* Type */ | 1920 /* Namespace */)) { + if (valueSymbol.flags & (67897832 /* Type */ | 1920 /* Namespace */)) { return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); @@ -31160,7 +31988,7 @@ var ts; combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - var moduleName = getFullyQualifiedName(moduleSymbol); + var moduleName = getFullyQualifiedName(moduleSymbol, node); var declarationName = ts.declarationNameToString(name); var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { @@ -31194,7 +32022,7 @@ var ts; if (ts.isClassExpression(expression)) { return checkExpression(expression).symbol; } - var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + var aliasLike = resolveEntityName(expression, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); if (aliasLike) { return aliasLike; } @@ -31213,7 +32041,7 @@ var ts; case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case 255 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); case 252 /* ExportAssignment */: case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); @@ -31228,10 +32056,10 @@ var ts; * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { - if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } + if (excludes === void 0) { excludes = 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */; } if (!symbol) return false; - return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; @@ -31262,7 +32090,7 @@ var ts; var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 67216319 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + ((target.flags & 67220415 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -31311,11 +32139,11 @@ var ts; // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + return resolveEntityName(entityName, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + function getFullyQualifiedName(symbol, containingLocation) { + return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */); } /** * Resolves a qualified name and any involved aliases. @@ -31324,11 +32152,11 @@ var ts; if (ts.nodeIsMissing(name)) { return undefined; } - var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJavaScriptFile(name) ? meaning & 67216319 /* Value */ : 0); + var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 67220415 /* Value */ : 0); var symbol; if (name.kind === 71 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); + var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -31344,7 +32172,7 @@ var ts; else if (namespace === unknownSymbol) { return namespace; } - if (ts.isInJavaScriptFile(name)) { + if (ts.isInJSFile(name)) { if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -31379,15 +32207,15 @@ var ts; * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + function resolveEntityNameFromAssignmentDeclaration(name, meaning) { if (isJSDocTypeReference(name.parent)) { - var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + var secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node) { + function getAssignmentDeclarationLocation(node) { var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); if (typeAlias) { return; @@ -31395,9 +32223,21 @@ var ts; var host = ts.getJSDocHost(node); if (ts.isExpressionStatement(host) && ts.isBinaryExpression(host.expression) && - ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); - return symbol && symbol.parent.valueDeclaration; + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } + if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && + ts.isBinaryExpression(host.parent.parent) && + ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { + // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } } var sig = ts.getHostSignatureFromJSDocHost(host); if (sig) { @@ -31405,6 +32245,13 @@ var ts; return symbol && symbol.valueDeclaration; } } + function getDeclarationOfJSPrototypeContainer(symbol) { + var decl = symbol.parent.valueDeclaration; + var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) : + ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) : + undefined; + return initializer || decl; + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32281,7 @@ var ts; var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32300,7 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -31485,7 +32332,7 @@ var ts; error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + var tsExtension = ts.tryExtractTSExtension(moduleReference); if (tsExtension) { var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); @@ -31493,7 +32340,7 @@ var ts; else if (!compilerOptions.resolveJsonModule && ts.fileExtensionIs(moduleReference, ".json" /* Json */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && - ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) { + ts.hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { @@ -31505,24 +32352,23 @@ var ts; } function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId - ? ts.chainDiagnosticMessages( - /*details*/ undefined, typesPackageExists(packageId.name) - ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, ts.getMangledNameForScopedPackage(packageId.name)) + var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, packageId.name, ts.mangleScopedPackageName(packageId.name)) + : ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); } function typesPackageExists(packageName) { - return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { - return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); - }); }); + return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; } function getCommonJsExportEquals(exported, moduleSymbol) { - if (!exported || moduleSymbol.exports.size === 1) { + if (!exported || exported === unknownSymbol || moduleSymbol.exports.size === 1) { return exported; } var merged = cloneSymbol(exported); @@ -31750,7 +32596,7 @@ var ts; return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol); } function symbolIsValue(symbol) { - return !!(symbol.flags & 67216319 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67216319 /* Value */); + return !!(symbol.flags & 67220415 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 67220415 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -31850,7 +32696,7 @@ var ts; } function getQualifiedLeftMeaning(rightMeaning) { // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 67216319 /* Value */ ? 67216319 /* Value */ : 1920 /* Namespace */; + return rightMeaning === 67220415 /* Value */ ? 67220415 /* Value */ : 1920 /* Namespace */; } function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) { if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); } @@ -31900,7 +32746,10 @@ var ts; && symbolFromSymbolTable.escapedName !== "default" /* Default */ && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration))) // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name - && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))) { + && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) + // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ + // See similar comment in `resolveName` for details + && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */))) { var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { return [symbolFromSymbolTable]; @@ -31965,11 +32814,11 @@ var ts; return false; } function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67901928 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67897832 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { - var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67220415 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { @@ -32007,7 +32856,17 @@ var ts; // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + var containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + var firstDecl = ts.first(symbol.declarations); + if (!ts.length(containers) && meaning & 67220415 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } @@ -32115,7 +32974,7 @@ var ts; ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { @@ -32125,7 +32984,7 @@ var ts; } else { // Type Reference or TypeAlias entity = Identifier - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); @@ -32148,6 +33007,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32230,7 +33092,12 @@ var ts; var context = { enclosingDeclaration: enclosingDeclaration, flags: flags || 0 /* None */, - tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, + // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 67108864 /* DoNotIncludeSymbolChain */ ? { + getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getSourceFiles: function () { return host.getSourceFiles(); }, + getCurrentDirectory: host.getCurrentDirectory && (function () { return host.getCurrentDirectory(); }) + } : undefined }, encounteredError: false, visitedSymbols: undefined, inferTypeParameters: undefined, @@ -32275,13 +33142,13 @@ var ts; } if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); - var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var parentName = symbolToName(parentSymbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } if (type.flags & 544 /* EnumLike */) { - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + var name = symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ false); context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } @@ -32301,7 +33168,7 @@ var ts; if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { context.approximateLength += 6; - return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); + return symbolToTypeNode(type.symbol, context, 67220415 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); @@ -32368,17 +33235,20 @@ var ts; } // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. return type.symbol - ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + ? symbolToTypeNode(type.symbol, context, 67897832 /* Type */) : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); - return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67897832 /* Type */, typeArgumentNodes); } if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + if (ts.length(types) === 1) { + return typeToTypeNodeHelper(types[0], context); + } var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); @@ -32448,23 +33318,23 @@ var ts; if (symbol) { var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. - var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + var isInstanceType = type === getInferredClassType(symbol) ? 67897832 /* Type */ : 67220415 /* Value */; return symbolToTypeNode(symbol, context, isInstanceType); } // Always use 'typeof T' for type of class, enum, and module objects else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return symbolToTypeNode(symbol, context, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67220415 /* Value */); } else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); + return symbolToTypeNode(typeAlias, context, 67897832 /* Type */); } else { context.approximateLength += 3; @@ -32546,8 +33416,8 @@ var ts; var arity = getTypeReferenceArity(type); var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); var hasRestElement = type.target.hasRestElement; - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - for (var i = type.target.minLength; i < arity; i++) { + if (tupleConstituentNodes) { + for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) { tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); @@ -32586,7 +33456,7 @@ var ts; var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + var ref = symbolToTypeNode(parent, context, 67897832 /* Type */, typeArgumentSlice); context.flags = flags_2; resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } @@ -32599,7 +33469,7 @@ var ts; } var flags = context.flags; context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; - var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + var finalRef = symbolToTypeNode(type.symbol, context, 67897832 /* Type */, typeArgumentNodes); context.flags = flags; return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } @@ -32697,18 +33567,13 @@ var ts; anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { var decl = ts.first(propertySymbol.declarations); - if (context.tracker.trackSymbol && hasLateBindableName(decl)) { - // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(decl.name.expression); - var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (name) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } + if (hasLateBindableName(decl)) { + trackComputedName(decl.name, saveEnclosingDeclaration, context); } } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + var propertyName = symbolToName(propertySymbol, context, 67220415 /* Value */, /*expectsIdentifier*/ true); context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -32836,7 +33701,7 @@ var ts; return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } function typeParameterShadowsNameInScope(type, context) { - return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67897832 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; @@ -32847,7 +33712,7 @@ var ts; typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) - : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); + : symbolToName(type.symbol, context, 67897832 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; @@ -32888,6 +33753,9 @@ var ts; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { + if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) { + trackComputedName(node, context.enclosingDeclaration, context); + } var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); if (clone.kind === 184 /* BindingElement */) { @@ -32897,12 +33765,22 @@ var ts; } } } + function trackComputedName(node, enclosingDeclaration, context) { + if (!context.tracker.trackSymbol) + return; + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(node.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, enclosingDeclaration, 67220415 /* Value */); + } + } function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -33009,7 +33887,14 @@ var ts; var links = getSymbolLinks(symbol); var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); if (!specifier) { - specifier = ts.moduleSpecifiers.getModuleSpecifierForDeclarationFile(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, host.redirectTargetsMap); + var isBundle_1 = (compilerOptions.out || compilerOptions.outFile); + // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, + // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this + // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative + // specifier preference + var moduleResolverHost = context.tracker.moduleResolverHost; + var specifierCompilerOptions = isBundle_1 ? __assign({}, compilerOptions, { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -33017,7 +33902,7 @@ var ts; } function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module - var isTypeOf = meaning === 67216319 /* Value */; + var isTypeOf = meaning === 67220415 /* Value */; if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { // module is root, must use `ImportTypeNode` var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; @@ -33116,6 +34001,9 @@ var ts; function createExpressionFromSymbolChain(chain, index) { var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); var symbol = chain[index]; + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)); + } if (index === 0) { context.flags |= 16777216 /* InInitialEntityName */; } @@ -33174,7 +34062,7 @@ var ts; var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; - if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { + if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) { result.push(baseType); i += count - 1; continue; @@ -33358,10 +34246,10 @@ var ts; function collectLinkedAliases(node, setVisibility) { var exportSymbol; if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { - exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); + exportSymbol = resolveName(node, node.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === 255 /* ExportSpecifier */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + exportSymbol = getTargetOfExportSpecifier(node.parent, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; if (exportSymbol) { @@ -33382,7 +34270,7 @@ var ts; // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); } @@ -33431,6 +34319,8 @@ var ts; switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; + case 5 /* EnumTagType */: + return !!(getNodeLinks(target).resolvedEnumType); case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -33439,6 +34329,8 @@ var ts; return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; + case 6 /* JSDocTypeReference */: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -33603,27 +34495,27 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); - var index = pattern.elements.indexOf(declaration); + var index_1 = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // If the parent is a tuple type, the rest element has an array type with a union of the + // If the parent is a tuple type, the rest element has a tuple type of the // remaining tuple element types. Otherwise, the rest element has an array type with same // element type as the parent type. - type = isTupleType(parentType) ? - getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + type = everyType(parentType, isTupleType) ? + mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_1 = pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) ? - getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + var index_2 = pattern.elements.indexOf(declaration); + type = everyType(parentType, isTupleLikeType) ? + getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); } return errorType; } @@ -33631,11 +34523,11 @@ var ts; } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? - getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : + getUnionType([type, checkDeclarationInitializer(declaration)], 2 /* Subtype */) : type; } function getTypeForDeclarationFromJSDocComment(declaration) { @@ -33683,7 +34575,7 @@ var ts; if (declaredType) { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + if ((noImplicitAny || ts.isInJSFile(declaration)) && declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -33714,16 +34606,22 @@ var ts; return getReturnTypeOfSignature(getterSignature); } } + if (ts.isInJSFile(declaration)) { + var typeTag = ts.getJSDocType(func); + if (typeTag && ts.isFunctionTypeNode(typeTag)) { + return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); + } + } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } } - else if (ts.isInJavaScriptFile(declaration)) { - var expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (ts.isInJSFile(declaration)) { + var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } // Use the type of the initializer expression if one is present @@ -33743,16 +34641,16 @@ var ts; // No type specified and nothing can be inferred return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol, resolvedSymbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - var specialDeclaration = ts.getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - var tag = ts.getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol, resolvedSymbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + var tag = ts.getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - var expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } var definedInConstructor = false; var definedInMethod = false; @@ -33766,8 +34664,8 @@ var ts; if (!expression) { return errorType; } - var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); - if (special === 4 /* ThisProperty */) { + var kind = ts.isPropertyAccessExpression(expression) ? ts.getAssignmentDeclarationPropertyAccessKind(expression) : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -33775,9 +34673,9 @@ var ts; definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(ts.isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } var type = jsdocType; @@ -33785,7 +34683,7 @@ var ts; var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -33796,15 +34694,13 @@ var ts; } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { - if (noImplicitAny) { - reportImplicitAnyError(symbol.valueDeclaration, anyType); - } + reportImplicitAny(symbol.valueDeclaration, anyType); return anyType; } return widened; } - function getJSExpandoObjectType(decl, symbol, init) { - if (!init || !ts.isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl, symbol, init) { + if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) { return undefined; } var exports = ts.createSymbolTable(); @@ -33823,7 +34719,7 @@ var ts; type.objectFlags |= 16384 /* JSLiteral */; return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType, expression, _symbol, declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType, expression, _symbol, declaration) { var typeNode = ts.getJSDocType(expression.parent); if (typeNode) { var type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -33837,10 +34733,10 @@ var ts; return declaredType; } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) { + function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) { var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 131072 /* Object */ && - special === 2 /* ModuleExports */ && + kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { var exportedType_1 = resolveStructuredTypeMembers(type); var members_3 = ts.createSymbolTable(); @@ -33864,9 +34760,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33889,8 +34783,8 @@ var ts; }); } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty) { - var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { + var parentDeclaration = ts.forEach(property.declarations, function (d) { var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; return ts.isClassLike(parent) && parent; }); @@ -33898,7 +34792,7 @@ var ts; var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -33912,8 +34806,8 @@ var ts; if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); + if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAny(element, anyType); } return anyType; } @@ -34005,9 +34899,9 @@ var ts; // Rest parameters default to type any[], other parameters default to type any type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType; // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { + if (reportErrors) { if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } return type; @@ -34050,19 +34944,26 @@ var ts; // Handle export default expressions if (ts.isSourceFile(declaration)) { var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type_1.flags & 131072 /* Object */) { + return getRegularTypeOfObjectLiteral(type_1); + } + return type_1; } if (declaration.kind === 252 /* ExportAssignment */) { - return checkExpression(declaration.expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return errorType; } var type; - if (ts.isInJavaScriptFile(declaration) && + if (ts.isInJSFile(declaration) && (ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (ts.isJSDocPropertyLikeTag(declaration) || ts.isPropertyAccessExpression(declaration) @@ -34076,7 +34977,7 @@ var ts; return getTypeOfFuncClassEnumModule(symbol); } type = ts.isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (ts.isPropertyAssignment(declaration)) { @@ -34137,7 +35038,7 @@ var ts; function getTypeOfAccessorsWorker(symbol) { var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); - if (getter && ts.isInJavaScriptFile(getter)) { + if (getter && ts.isInJSFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -34165,14 +35066,12 @@ var ts; } // Otherwise, fall back to 'any'. else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } + if (setter) { + errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); } type = anyType; } @@ -34195,7 +35094,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { @@ -34223,7 +35122,7 @@ var ts; } else if (declaration.kind === 202 /* BinaryExpression */ || declaration.kind === 187 /* PropertyAccessExpression */ && declaration.parent.kind === 202 /* BinaryExpression */) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { var resolvedModule = resolveExternalModuleSymbol(symbol); @@ -34232,11 +35131,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_1 = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_2 = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_1; + return type_2; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -34261,7 +35160,7 @@ var ts; // type symbol, call getDeclaredTypeOfSymbol. // This check is important because without it, a call to getTypeOfSymbol could end // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 67216319 /* Value */ + links.type = targetSymbol.flags & 67220415 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } @@ -34270,22 +35169,14 @@ var ts; function getTypeOfInstantiatedSymbol(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = errorType; + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return links.type = errorType; } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return links.type = errorType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + if (!popTypeResolution()) { + type = reportCircularityError(symbol); } + links.type = type; } return links.type; } @@ -34444,23 +35335,20 @@ var ts; var constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type) { return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); - var isJavascript = ts.isInJavaScriptFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, 0 /* Call */); - } + var isJavascript = ts.isInJSFile(location); return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); - return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJavaScriptFile(location)) : sig; }); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; }); } /** * The base constructor of a class can resolve to @@ -34531,7 +35419,9 @@ var ts; var baseTypeNode = getBaseTypeNodeOfClass(type); var typeArgs = typeArgumentsFromTypeReferenceNode(baseTypeNode); var baseType; - var originalBaseType = baseConstructorType && baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined; + var originalBaseType = isJSConstructorType(baseConstructorType) ? baseConstructorType : + baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : + undefined; if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ && areAllOuterTypeParametersApplied(originalBaseType)) { // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the @@ -34542,8 +35432,8 @@ var ts; else if (baseConstructorType.flags & 1 /* Any */) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType)) { + baseType = !baseTypeNode.typeArguments && getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -34642,7 +35532,7 @@ var ts; for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { var node = baseTypeNodes_1[_b]; if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 67901928 /* Type */, /*ignoreErrors*/ true); + var baseSymbol = resolveEntityName(node.expression, 67897832 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -34781,9 +35671,9 @@ var ts; if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + var memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -35009,7 +35899,7 @@ var ts; if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 192 /* StringOrNumberLiteral */) { + if (type.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { return ts.escapeLeadingUnderscores("" + type.value); } return ts.Debug.fail(); @@ -35029,7 +35919,7 @@ var ts; else { symbol.declarations.push(member); } - if (symbolFlags & 67216319 /* Value */) { + if (symbolFlags & 67220415 /* Value */) { if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } @@ -35283,7 +36173,7 @@ var ts; return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var isJavaScript = ts.isInJSFile(baseTypeNode); var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); var typeArgCount = ts.length(typeArguments); var result = []; @@ -35420,7 +36310,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_4 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -35443,7 +36333,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_4(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -35497,6 +36387,7 @@ var ts; // will never be observed because a qualified name can't reference signatures. if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { type.callSignatures = getSignaturesOfSymbol(symbol); + type.constructSignatures = ts.filter(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration); }); } // And likewise for construct signatures for classes if (symbol.flags & 32 /* Class */) { @@ -35608,7 +36499,7 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); + (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || @@ -35778,10 +36669,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; - var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; - var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; - return constraint && constraint !== errorType ? constraint : undefined; + var objectType = getConstraintOfType(type.objectType) || type.objectType; + if (objectType !== type.objectType) { + var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); + if (constraint && constraint !== errorType) { + return constraint; + } + } + var baseConstraint = getBaseConstraintOfType(type); + return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { @@ -35798,7 +36694,8 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); + var simplified = getSimplifiedType(type.checkType); + var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); @@ -35877,6 +36774,7 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { + var nonTerminating = false; return type.resolvedBaseConstraint || (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); function getImmediateBaseConstraint(t) { @@ -35884,8 +36782,18 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } + if (constraintDepth === 50) { + // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a + // very high likelyhood we're dealing with an infinite generic type that perpetually generates + // new type identities as we descend into it. We stop the recursion here and mark this type + // and the outer types as having circular constraints. + nonTerminating = true; + return t.immediateBaseConstraint = noConstraintType; + } + constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); - if (!popTypeResolution()) { + constraintDepth--; + if (!popTypeResolution() || nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -35907,8 +36815,8 @@ var ts; var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } @@ -35923,7 +36831,7 @@ var ts; if (t.flags & 2097152 /* IndexedAccess */) { var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType, /*accessNode*/ undefined, errorType) : undefined; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 4194304 /* Conditional */) { @@ -35933,9 +36841,6 @@ var ts; if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } - if (isGenericMappedType(t)) { - return emptyObjectType; - } return t; } } @@ -35985,6 +36890,20 @@ var ts; function hasTypeParameterDefault(typeParameter) { return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; })); } + function getApparentTypeOfMappedType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type)); + } + function getResolvedApparentTypeOfMappedType(type) { + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var constraint = getConstraintOfTypeParameter(typeVariable); + if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + var mapper = makeUnaryTypeMapper(typeVariable, constraint); + return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the @@ -35992,14 +36911,15 @@ var ts; */ function getApparentType(type) { var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 68 /* StringLike */ ? globalStringType : - t.flags & 168 /* NumberLike */ ? globalNumberType : - t.flags & 272 /* BooleanLike */ ? globalBooleanType : - t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t.flags & 1048576 /* Index */ ? keyofConstraintType : - t; + return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : + t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; @@ -36029,10 +36949,10 @@ var ts; } } else if (isUnion) { - var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); - if (index) { - checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; - indexTypes = ts.append(indexTypes, index.type); + var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */)); + if (indexInfo) { + checkFlags |= indexInfo.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type); } else { checkFlags |= 16 /* Partial */; @@ -36123,8 +37043,12 @@ var ts; if (symbol && symbolIsValue(symbol)) { return symbol; } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + var functionType = resolved === anyFunctionType ? globalFunctionType : + resolved.callSignatures.length ? globalCallableFunctionType : + resolved.constructSignatures.length ? globalNewableFunctionType : + undefined; + if (functionType) { + var symbol_1 = getPropertyOfObjectType(functionType, name); if (symbol_1) { return symbol_1; } @@ -36205,7 +37129,7 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - return ts.isInJavaScriptFile(node) && ( + return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === 286 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { @@ -36305,7 +37229,7 @@ var ts; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); var isUntypedSignatureInJSFile = !iife && - ts.isInJavaScriptFile(declaration) && + ts.isInJSFile(declaration) && ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); @@ -36318,7 +37242,7 @@ var ts; var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67220415 /* Value */, undefined, undefined, /*isUse*/ false); paramSymbol = resolvedSymbol; } if (i === 0 && paramSymbol.escapedName === "this" /* This */) { @@ -36355,7 +37279,7 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); } @@ -36386,7 +37310,7 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -36473,7 +37397,7 @@ var ts; else { var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); var jsdocPredicate = void 0; - if (!type && ts.isInJavaScriptFile(signature.declaration)) { + if (!type && ts.isInJSFile(signature.declaration)) { var jsdocSignature = getSignatureOfTypeTag(signature.declaration); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -36514,6 +37438,7 @@ var ts; var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) : signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || + isJSConstructor(signature.declaration) && getJSClassType(getSymbolOfNode(signature.declaration)) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); if (!popTypeResolution()) { if (signature.declaration) { @@ -36550,7 +37475,7 @@ var ts; return getTypeFromTypeNode(typeNode); } if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var jsDocType = ts.isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -36569,8 +37494,12 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - var type = getTypeOfRestParameter(signature); - return type && getIndexTypeOfType(type, 1 /* Number */); + if (signature.hasRestParameter) { + var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; + return restType && getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; } function getSignatureInstantiation(signature, typeArguments, isJavascript) { return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); @@ -36611,7 +37540,7 @@ var ts; // where different generations of the same type parameter are in scope). This leads to a lot of new type // identities, and potentially a lot of work comparing those identities, so here we create an instantiation // that uses the original type identities for all unconstrained type parameters. - return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJavaScriptFile(signature.declaration)); + return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration)); } function getBaseSignature(signature) { var typeParameters = signature.typeParameters; @@ -36805,10 +37734,10 @@ var ts; if (typeParameters) { var numTypeArguments = ts.length(node.typeArguments); var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent); var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -36838,7 +37767,7 @@ var ts; var id = getTypeListId(typeArguments); var instantiation = links.instantiations.get(id); if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -36893,14 +37822,28 @@ var ts; if (type) { return type; } + // JS enums are 'string' or 'number', not an enum type. + var enumTag = ts.isInJSFile(node) && symbol.valueDeclaration && ts.getJSDocEnumTag(symbol.valueDeclaration); + if (enumTag) { + var links = getNodeLinks(enumTag); + if (!pushTypeResolution(enumTag, 5 /* EnumTagType */)) { + return errorType; + } + var type_4 = enumTag.typeExpression ? getTypeFromTypeNode(enumTag.typeExpression) : errorType; + if (!popTypeResolution()) { + type_4 = errorType; + error(node, ts.Diagnostics.Enum_type_0_circularly_references_itself, symbolToString(symbol)); + } + return (links.resolvedEnumType = type_4); + } // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } - if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { + if (!(symbol.flags & 67220415 /* Value */ && isJSDocTypeReference(node))) { return errorType; } var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); @@ -36908,7 +37851,7 @@ var ts; return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. - resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); + resolveTypeReferenceName(getTypeReferenceName(node), 67897832 /* Type */); return getTypeOfSymbol(symbol); } /** @@ -36917,16 +37860,21 @@ var ts; * the type of this reference is just the type of the value we resolved to. */ function getJSDocTypeReference(node, symbol, typeArguments) { + if (!pushTypeResolution(symbol, 6 /* JSDocTypeReference */)) { + return errorType; + } var assignedType = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, ts.Diagnostics.JSDoc_type_0_circularly_references_itself, symbolToString(symbol)); + return errorType; + } if (referenceType || assignedType) { // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) - return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); - } - var enumTag = ts.getJSDocEnumTag(symbol.valueDeclaration); - if (enumTag && enumTag.typeExpression) { - return getTypeFromTypeNode(enumTag.typeExpression); + var type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + return getSymbolLinks(symbol).resolvedJSDocType = type; } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { @@ -37042,16 +37990,16 @@ var ts; if (!links.resolvedType) { var symbol = void 0; var type = void 0; - var meaning = 67901928 /* Type */; + var meaning = 67897832 /* Type */; if (isJSDocTypeReference(node)) { type = getIntendedTypeFromJSDocTypeReference(node); - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } if (!type) { symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); type = getTypeReferenceType(node, symbol); } - // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the // type reference in checkTypeReferenceNode. links.resolvedSymbol = symbol; links.resolvedType = type; @@ -37100,10 +38048,10 @@ var ts; return type; } function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67216319 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + return getGlobalSymbol(name, 67220415 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); } function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 67901928 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + return getGlobalSymbol(name, 67897832 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary @@ -37131,6 +38079,9 @@ var ts; function getGlobalPromiseType(reportErrors) { return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; } + function getGlobalPromiseLikeType(reportErrors) { + return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType; + } function getGlobalPromiseConstructorSymbol(reportErrors) { return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); } @@ -37157,7 +38108,7 @@ var ts; } function getGlobalTypeOrUndefined(name, arity) { if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); + var symbol = getGlobalSymbol(name, 67897832 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } function getGlobalExtractSymbol() { @@ -37278,6 +38229,14 @@ var ts; } return links.resolvedType; } + function sliceTupleType(type, index) { + var tuple = type.target; + if (tuple.hasRestElement) { + // don't slice off rest element + index = Math.min(index, getTypeReferenceArity(type) - 1); + } + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); return strictNullChecks ? getOptionalType(type) : type; @@ -37346,10 +38305,7 @@ var ts; var len = typeSet.length; var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); if (index < 0) { - if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -37364,15 +38320,6 @@ var ts; } return includes; } - function containsIdenticalType(types, type) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var t = types_7[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } function isSubtypeOfAny(source, targets) { for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { var target = targets_1[_i]; @@ -37418,7 +38365,7 @@ var ts; var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || - t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); + t.flags & 448 /* Literal */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -37446,7 +38393,7 @@ var ts; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */ | 256 /* BooleanLiteral */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -37543,10 +38490,7 @@ var ts; if (type === wildcardType) includes |= 268435456 /* Wildcard */; } - else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && - !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); } } @@ -37555,8 +38499,8 @@ var 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, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type = types_7[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -37810,7 +38754,7 @@ var ts; } return false; } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? @@ -37823,20 +38767,23 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return errorType; + return missingType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; } } var propType = getTypeOfSymbol(prop); - return accessExpression ? getFlowTypeOfReference(accessExpression, propType) : propType; + return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? + getFlowTypeOfReference(accessExpression, propType) : + propType; } - if (isTupleType(objectType)) { - var restType = getRestTypeOfTupleType(objectType); - if (restType && isNumericLiteralName(propName) && +propName >= 0) { - return restType; + if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); } + return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } } if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { @@ -37882,7 +38829,7 @@ var ts; } } } - return anyType; + return missingType; } } if (isJSLiteralType(objectType)) { @@ -37900,7 +38847,10 @@ var ts; error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } } - return errorType; + if (isTypeAny(indexType)) { + return indexType; + } + return missingType; } function isGenericObjectType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); @@ -37908,20 +38858,6 @@ var ts; function isGenericIndexType(type) { return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } - // Return true if the given type is a non-generic object type with a string index signature and no - // other members. - function isStringIndexOnlyType(type) { - if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { - var t = resolveStructuredTypeMembers(type); - return t.properties.length === 0 && - t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - !!t.stringIndexInfo && !t.numberIndexInfo; - } - return false; - } - function isMappedTypeToNever(type) { - return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; - } function getSimplifiedType(type) { return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } @@ -37935,37 +38871,24 @@ var ts; // We recursively simplify the object type as it may in turn be an indexed access type. For example, with // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. var objectType = getSimplifiedType(type.objectType); - if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); - } - } - return type.simplified = getUnionType([ - getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), - getIntersectionType(stringIndexTypes) - ]); + var indexType = getSimplifiedType(type.indexType); + // T[A | B] -> T[A] | T[B] + if (indexType.flags & 262144 /* Union */) { + return type.simplified = mapType(indexType, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t)); }); + } + // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again + if (!(indexType.flags & 15794176 /* Instantiable */)) { + // (T | U)[K] -> T[K] | U[K] + if (objectType.flags & 262144 /* Union */) { + return type.simplified = mapType(objectType, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); }); } - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a - // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen - // eventually anyway, but it easier to reason about. - if (ts.some(objectType.types, isMappedTypeToNever)) { - var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); + // (T & U)[K] -> T[K] & U[K] + if (objectType.flags & 524288 /* Intersection */) { + return type.simplified = getIntersectionType(ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType)); })); } } + // So ultimately: + // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. We do not further simplify the result because mapped types can be recursive @@ -37986,7 +38909,8 @@ var ts; var templateMapper = combineTypeMappers(objectType.mapper, mapper); return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType, indexType, accessNode) { + function getIndexedAccessType(objectType, indexType, accessNode, missingType) { + if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -38013,17 +38937,28 @@ var ts; var apparentObjectType = getApparentType(objectType); if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; + var wasMissingProp = false; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === errorType) { - return errorType; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false, missingType); + if (propType === missingType) { + if (!accessNode) { + // If there's no error node, we can immeditely stop, since error reporting is off + return missingType; + } + else { + // Otherwise we set a flag and return at the end of the loop so we still mark all errors + wasMissingProp = true; + } } propTypes.push(propType); } + if (wasMissingProp) { + return missingType; + } return getUnionType(propTypes); } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true, missingType); } function getTypeFromIndexedAccessTypeNode(node) { var links = getNodeLinks(node); @@ -38201,7 +39136,7 @@ var ts; links.resolvedSymbol = unknownSymbol; return links.resolvedType = errorType; } - var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67216319 /* Value */ | 67901928 /* Type */ : 67901928 /* Type */; + var targetMeaning = node.isTypeOf ? 67220415 /* Value */ : node.flags & 2097152 /* JSDoc */ ? 67220415 /* Value */ | 67897832 /* Type */ : 67897832 /* Type */; // TODO: Future work: support unions/generics/whatever via a deferred import-type var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); if (!innerModuleSymbol) { @@ -38231,7 +39166,7 @@ var ts; resolveImportSymbolType(node, links, moduleSymbol, targetMeaning); } else { - var errorMessage = targetMeaning === 67216319 /* Value */ + var errorMessage = targetMeaning === 67220415 /* Value */ ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; error(node, errorMessage, node.argument.literal.text); @@ -38245,7 +39180,7 @@ var ts; function resolveImportSymbolType(node, links, symbol, meaning) { var resolvedSymbol = resolveSymbol(symbol); links.resolvedSymbol = resolvedSymbol; - if (meaning === 67216319 /* Value */) { + if (meaning === 67220415 /* Value */) { return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias } else { @@ -38387,8 +39322,8 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { - if (!type.freshType) { + if (type.flags & 448 /* Literal */ && !(type.flags & 33554432 /* FreshLiteral */)) { + if (!type.freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; @@ -38398,7 +39333,7 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + return type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : type; } @@ -38604,7 +39539,7 @@ var ts; } function cloneTypeMapper(mapper) { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : mapper; } function combineTypeMappers(mapper1, mapper2) { @@ -38705,7 +39640,7 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - if (ts.isInJavaScriptFile(declaration_1)) { + if (ts.isInJSFile(declaration_1)) { var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); if (paramTag) { var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); @@ -38715,7 +39650,7 @@ var ts; } } var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration_1)) { + if (isJSConstructor(declaration_1)) { var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); } @@ -38774,8 +39709,18 @@ var ts; return !!ts.forEachChild(node, containsReference); } } + function getHomomorphicTypeVariable(type) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 1048576 /* Index */) { + var typeVariable = constraintType.type; + if (typeVariable.flags & 65536 /* TypeParameter */) { + return typeVariable; + } + } + return undefined; + } function instantiateMappedType(type, mapper) { - // For a momomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping + // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping // operation depends on T as follows: // * If T is a primitive type no mapping is performed and the result is simply T. // * If T is a union type we distribute the mapped type over the union. @@ -38785,30 +39730,34 @@ var ts; // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } | // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce // { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 1048576 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 65536 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - var replacementMapper = createReplacementMapper(typeVariable_1, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); - } - return t; - }); + var typeVariable = getHomomorphicTypeVariable(type); + if (typeVariable) { + var mappedTypeVariable = instantiateType(typeVariable, mapper); + if (typeVariable !== mappedTypeVariable) { + // If we are already in the process of creating an instantiation of this mapped type, + // return the error type. This situation only arises if we are instantiating the mapped + // type for an array or tuple type, as we then need to eagerly resolve the (possibly + // circular) element type(s). + if (type.instantiating) { + return errorType; } + type.instantiating = true; + var result = mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */) && t !== wildcardType) { + var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); + } + return t; + }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); } - function isMappableType(type) { - return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); - } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -38832,6 +39781,12 @@ var ts; var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); if (type.objectFlags & 32 /* Mapped */) { result.declaration = type.declaration; + // C.f. instantiateSignature + var origTypeParameter = getTypeParameterFromMappedType(type); + var freshTypeParameter = cloneTypeParameter(origTypeParameter); + result.typeParameter = freshTypeParameter; + mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper); + freshTypeParameter.mapper = mapper; } result.target = type; result.mapper = mapper; @@ -38871,49 +39826,65 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (type && mapper && mapper !== identityMapper) { - if (type.flags & 65536 /* TypeParameter */) { - return mapper(type); + if (!type || !mapper || mapper === identityMapper) { + return type; + } + if (instantiationDepth === 50) { + // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing + // with a combination of infinite generic types that perpetually generate new type identities. We stop + // the recursion here by yielding the error type. + return errorType; + } + instantiationDepth++; + var result = instantiateTypeWorker(type, mapper); + instantiationDepth--; + return result; + } + function instantiateTypeWorker(type, mapper) { + var flags = type.flags; + if (flags & 65536 /* TypeParameter */) { + return mapper(type); + } + if (flags & 131072 /* Object */) { + var objectFlags = type.objectFlags; + if (objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. + return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? + getAnonymousTypeInstantiation(type, mapper) : type; } - if (type.flags & 131072 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ? - getAnonymousTypeInstantiation(type, mapper) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return getAnonymousTypeInstantiation(type, mapper); - } - if (type.objectFlags & 4 /* Reference */) { - var typeArguments = type.typeArguments; - var newTypeArguments = instantiateTypes(typeArguments, mapper); - return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; - } + if (objectFlags & 32 /* Mapped */) { + return getAnonymousTypeInstantiation(type, mapper); } - if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 524288 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (type.flags & 1048576 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 2097152 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - if (type.flags & 4194304 /* Conditional */) { - return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); - } - if (type.flags & 8388608 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + if (objectFlags & 4 /* Reference */) { + var typeArguments = type.typeArguments; + var newTypeArguments = instantiateTypes(typeArguments, mapper); + return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } + return type; + } + if (flags & 262144 /* Union */ && !(flags & 32764 /* Primitive */)) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 524288 /* Intersection */) { + var types = type.types; + var newTypes = instantiateTypes(types, mapper); + return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + } + if (flags & 1048576 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (flags & 2097152 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + if (flags & 4194304 /* Conditional */) { + return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); + } + if (flags & 8388608 /* Substitution */) { + return instantiateType(type.typeVariable, mapper); } return type; } @@ -38987,7 +39958,7 @@ var ts; return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { @@ -39035,8 +40006,9 @@ var ts; return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : - target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : - hasBaseType(source, getTargetType(target)); + target === globalObjectType ? !!(source.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */)) : + target === globalFunctionType ? !!(source.flags & 131072 /* Object */) && isFunctionObjectType(source) : + hasBaseType(source, getTargetType(target)); } /** * This is *not* a bi-directional relationship. @@ -39062,33 +40034,98 @@ var ts; * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. */ function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { - if (isTypeAssignableTo(source, target)) + return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain); + } + function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeRelatedTo(source, target, relation)) return true; - if (!elaborateError(expr, source, target)) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { + return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; } - function elaborateError(node, source, target) { - if (!node) + function isOrHasGenericConditional(type) { + return !!(type.flags & 4194304 /* Conditional */ || (type.flags & 524288 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional))); + } + function elaborateError(node, source, target, relation, headMessage) { + if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage)) { + return true; + } switch (node.kind) { case 268 /* JsxExpression */: case 193 /* ParenthesizedExpression */: - return elaborateError(node.expression, source, target); + return elaborateError(node.expression, source, target, relation, headMessage); case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: case 26 /* CommaToken */: - return elaborateError(node.right, source, target); + return elaborateError(node.right, source, target, relation, headMessage); } break; case 186 /* ObjectLiteralExpression */: - return elaborateObjectLiteral(node, source, target); + return elaborateObjectLiteral(node, source, target, relation); case 185 /* ArrayLiteralExpression */: - return elaborateArrayLiteral(node, source, target); + return elaborateArrayLiteral(node, source, target, relation); case 266 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target); + return elaborateJsxAttributes(node, source, target, relation); + case 195 /* ArrowFunction */: + return elaborateArrowFunction(node, source, target, relation); + } + return false; + } + function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage) { + var callSignatures = getSignaturesOfType(source, 0 /* Call */); + var constructSignatures = getSignaturesOfType(source, 1 /* Construct */); + for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) { + var signatures = _a[_i]; + if (ts.some(signatures, function (s) { + var returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (1 /* Any */ | 32768 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + var resultObj = {}; + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); + var diagnostic = resultObj.error; + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + return true; + } + } + return false; + } + function elaborateArrowFunction(node, source, target, relation) { + // Don't elaborate blocks + if (ts.isBlock(node.body)) { + return false; + } + // Or functions with annotated parameter types + if (ts.some(node.parameters, ts.hasType)) { + return false; + } + var sourceSig = getSingleCallSignature(source); + if (!sourceSig) { + return false; + } + var targetSignatures = getSignaturesOfType(target, 0 /* Call */); + if (!ts.length(targetSignatures)) { + return false; + } + var returnExpression = node.body; + var sourceReturn = getReturnTypeOfSignature(sourceSig); + var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature)); + if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) { + var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined); + if (elaborated) { + return elaborated; + } + var resultObj = {}; + checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); + if (resultObj.error) { + if (target.symbol && ts.length(target.symbol.declarations)) { + addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + } + return true; + } } return false; } @@ -39097,15 +40134,15 @@ var ts; * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator, source, target) { + function elaborateElementwise(iterator, source, target, relation) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; - var sourcePropType = getIndexedAccessType(source, nameType); - var targetPropType = getIndexedAccessType(target, nameType); - if (!isTypeAssignableTo(sourcePropType, targetPropType)) { - var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + var sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); + var targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { reportedError = true; } @@ -39114,10 +40151,10 @@ var ts; var resultObj = {}; // Use the expression type, if available var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; - var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { var reportedDiag = resultObj.error; @@ -39128,13 +40165,16 @@ var ts; var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || getIndexInfoOfType(target, 0 /* String */) || undefined; - if (indexInfo && indexInfo.declaration) { + if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; + if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } } } reportedError = true; @@ -39168,8 +40208,8 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node, source, target, relation) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -39201,9 +40241,14 @@ var ts; } }); } - function elaborateArrayLiteral(node, source, target) { + function elaborateArrayLiteral(node, source, target, relation) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); + } + // recreate a tuple from the elements, if possible + var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } return false; } @@ -39252,8 +40297,8 @@ var ts; } }); } - function elaborateObjectLiteral(node, source, target) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node, source, target, relation) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** * This is *not* a bi-directional relationship. @@ -39283,9 +40328,10 @@ var ts; source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); - var sourceGenericRestType = getGenericRestType(source); - var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; - if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + var sourceRestType = getNonArrayRestType(source); + var targetRestType = getNonArrayRestType(target); + if (sourceRestType && targetRestType && sourceCount !== targetCount) { + // We're not able to relate misaligned complex rest parameters return 0 /* False */; } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; @@ -39308,11 +40354,11 @@ var ts; result &= related; } } - var paramCount = Math.max(sourceCount, targetCount); - var lastIndex = paramCount - 1; + var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount); + var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1; for (var i = 0; i < paramCount; i++) { - var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); - var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); + var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i); + var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -39338,13 +40384,13 @@ var ts; result &= related; } if (!ignoreReturnTypes) { - var targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); + var targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol) : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - var sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); + var sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol) : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions var targetTypePredicate = getTypePredicateOfSignature(target); if (targetTypePredicate) { @@ -39508,10 +40554,10 @@ var ts; return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || @@ -39646,10 +40692,10 @@ var ts; */ function isRelatedTo(source, target, reportErrors, headMessage) { if (reportErrors === void 0) { reportErrors = false; } - if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { + if (source.flags & 448 /* Literal */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { + if (target.flags & 448 /* Literal */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source.flags & 8388608 /* Substitution */) { @@ -39705,13 +40751,10 @@ var ts; source = getRegularTypeOfObjectLiteral(source); } } - if (relation !== comparableRelation && - !(source.flags & 786432 /* UnionOrIntersection */) && - !(target.flags & 262144 /* Union */) && - !isIntersectionConstituent && - source !== globalObjectType && + if (relation !== comparableRelation && !isIntersectionConstituent && + source.flags & (32764 /* Primitive */ | 131072 /* Object */ | 524288 /* Intersection */) && source !== globalObjectType && + target.flags & (131072 /* Object */ | 524288 /* Intersection */) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - isWeakType(target) && !hasCommonProperties(source, target)) { if (reportErrors) { var calls = getSignaturesOfType(source, 0 /* Call */); @@ -39810,7 +40853,7 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 131072 /* Object */) { + if (flags & 131072 /* Object */ || flags & 2097152 /* IndexedAccess */ || flags & 4194304 /* Conditional */ || flags & 1048576 /* Index */ || flags & 8388608 /* Substitution */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { @@ -39820,32 +40863,6 @@ var ts; } } } - if (flags & 1048576 /* Index */) { - return isRelatedTo(source.type, target.type, /*reportErrors*/ false); - } - if (flags & 2097152 /* IndexedAccess */) { - if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result; - } - } - } - if (flags & 4194304 /* Conditional */) { - if (source.root.isDistributive === target.root.isDistributive) { - if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result; - } - } - } - } - } - } - if (flags & 8388608 /* Substitution */) { - return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); - } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { @@ -39862,8 +40879,8 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_5 = function (prop) { - if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + var _loop_6 = function (prop) { + if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -39901,13 +40918,16 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_5(prop); + var state_2 = _loop_6(prop); if (typeof state_2 === "object") return state_2.value; } } return false; } + function isPropertyFromSpread(prop, container) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -39936,7 +40956,8 @@ var ts; if (reportErrors) { var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -39963,32 +40984,24 @@ var ts; return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); } } + function findBestTypeForInvokable(source, unionTarget) { + var signatureKind = 0 /* Call */; + var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { - var match; var sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) { - var sourceProperty = sourcePropertiesFiltered_1[_i]; - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); - if (targetType && isRelatedTo(sourceType, targetType)) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - if (match) { - return undefined; - } - match = type; - } - } - } + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); } } - return match; + return undefined; } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; @@ -40153,6 +41166,37 @@ var ts; return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } function structuredTypeRelatedTo(source, target, reportErrors) { + var flags = source.flags & target.flags; + if (relation === identityRelation && !(flags & 131072 /* Object */)) { + if (flags & 1048576 /* Index */) { + return isRelatedTo(source.type, target.type, /*reportErrors*/ false); + } + var result_2 = 0 /* False */; + if (flags & 2097152 /* IndexedAccess */) { + if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_2; + } + } + } + if (flags & 4194304 /* Conditional */) { + if (source.root.isDistributive === target.root.isDistributive) { + if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_2; + } + } + } + } + } + } + if (flags & 8388608 /* Substitution */) { + return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); + } + return 0 /* False */; + } var result; var originalErrorInfo; var saveErrorInfo = errorInfo; @@ -40181,20 +41225,25 @@ var ts; var simplified = getSimplifiedType(target.type); var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { - return result; + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } } else if (target.flags & 2097152 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to C, where C is the - // constraint of T[K] - var constraint = getConstraintForRelation(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; + // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, + // where C is the base constraint of T[K] + if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + var constraint = getBaseConstraintOfType(target); + if (constraint && constraint !== target) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + return result; + } } } } @@ -40212,7 +41261,6 @@ var ts; var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); var templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; return result; } } @@ -40285,6 +41333,26 @@ var ts; } } else { + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + return -1 /* True */; + } + if (isGenericMappedType(target)) { + if (isGenericMappedType(source)) { + if (result = mappedTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + return 0 /* False */; + } + if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { + return 0 /* False */; + } + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target && !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) { // We have type references to the same generic type, and the type references are not marker @@ -40318,36 +41386,26 @@ var ts; errorInfo = saveErrorInfo; } } + else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { - result = -1 /* True */; - } - else if (isGenericMappedType(target)) { - result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); } } } @@ -40370,10 +41428,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_3; + if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -40504,33 +41562,6 @@ var ts; } return result; } - /** - * A type is 'weak' if it is an object type with at least one optional property - * and no required properties, call/construct signatures or index signatures - */ - function isWeakType(type) { - if (type.flags & 131072 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && - !resolved.stringIndexInfo && !resolved.numberIndexInfo && - resolved.properties.length > 0 && - ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); - } - if (type.flags & 524288 /* Intersection */) { - return ts.every(type.types, isWeakType); - } - return false; - } - function hasCommonProperties(source, target) { - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { - return true; - } - } - return false; - } function propertiesIdenticalTo(source, target) { if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; @@ -40562,8 +41593,8 @@ var ts; if (target === anyFunctionType || source === anyFunctionType) { return -1 /* True */; } - var sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - var targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ? 0 /* Call */ : kind); var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ? @@ -40755,6 +41786,52 @@ var ts; return false; } } + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + var match; + for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { + var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + for (var _b = 0, _c = target.types; _b < _c.length; _b++) { + var type = _c[_b]; + var targetType = getTypeOfPropertyOfType(type, propertyName); + if (targetType && related(getDiscriminatingType(), targetType)) { + if (match) { + if (type === match) + continue; // Finding multiple fields which discriminate to the same type is fine + return defaultValue; + } + match = type; + } + } + } + return match || defaultValue; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 131072 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 524288 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } // Return a type reference where the source type parameter is replaced with the target marker // type, and flag the result as a marker type reference. function getMarkerTypeReference(type, source, target) { @@ -41043,8 +42120,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var t = types_8[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -41096,9 +42173,14 @@ var ts; return isTupleType(type) || !!getPropertyOfType(type, "0"); } function getTupleElementType(type, index) { - return isTupleType(type) ? - index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : - getTypeOfPropertyOfType(type, "" + index); + var propType = getTypeOfPropertyOfType(type, "" + index); + if (propType) { + return propType; + } + if (everyType(type, isTupleType) && !everyType(type, function (t) { return !t.target.hasRestElement; })) { + return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); + } + return undefined; } function isNeitherUnitTypeNorNever(type) { return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); @@ -41120,10 +42202,10 @@ var ts; type; } function getWidenedLiteralType(type) { - return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & 512 /* EnumLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? getBaseTypeOfEnumLiteralType(type) : type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : - type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 256 /* BooleanLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? booleanType : type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } @@ -41148,13 +42230,17 @@ var ts; function getRestTypeOfTupleType(type) { return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; } + function getRestArrayTypeOfTupleType(type) { + var restType = getRestTypeOfTupleType(type); + return restType && createArrayType(restType); + } function getLengthOfTupleType(type) { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; result |= getFalsyFlags(t); } return result; @@ -41166,7 +42252,7 @@ var ts; return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : - type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 256 /* BooleanLiteral */ : 0 : type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { @@ -41180,11 +42266,12 @@ var ts; function getDefinitelyFalsyPartOfType(type) { return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : - type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type === regularFalseType || + type === falseType || type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || - type.flags & 64 /* StringLiteral */ && type.value === "" || - type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : - neverType; + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : + neverType; } /** * Add undefined or null or both to a type if they are missing. @@ -41421,8 +42508,12 @@ var ts; } return errorReported; } - function reportImplicitAnyError(declaration, type) { + function reportImplicitAny(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); + if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) { + // Only report implicit any errors/suggestions in TS and ts-check JS files + return; + } var diagnostic; switch (declaration.kind) { case 202 /* BinaryExpression */: @@ -41445,44 +42536,49 @@ var ts; case 157 /* SetAccessor */: case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: - if (!declaration.name) { + if (noImplicitAny && !declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 179 /* MappedType */: - error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); + } return; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); + reportImplicitAny(declaration, type); } } } function forEachMatchingParameterType(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); - var sourceHasRest = hasEffectiveRestParameter(source); - var targetHasRest = hasEffectiveRestParameter(target); - var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : - sourceHasRest ? targetCount : - targetHasRest ? sourceCount : - Math.min(sourceCount, targetCount); - var targetGenericRestType = getGenericRestType(target); - var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + var sourceRestType = getEffectiveRestType(source); + var targetRestType = getEffectiveRestType(target); + var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount; + var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount); + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + callback(sourceThisType, targetThisType); + } + } for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } - if (targetGenericRestType) { - callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + if (targetRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { @@ -41658,7 +42754,9 @@ var ts; var symbolStack; var visited; var contravariant = false; + var bivariant = false; var propagationType; + var allowComplexConstraintInference = true; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -41744,11 +42842,13 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + // We make contravariant inferences only if we are in a pure contravariant position, + // i.e. only if we have not descended into a bivariant position. + if (contravariant && !bivariant) { + inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); } else { - inference.candidates = ts.append(inference.candidates, candidate); + inference.candidates = ts.appendIfUnique(inference.candidates, candidate); } } if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { @@ -41797,6 +42897,9 @@ var ts; inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } + else if (target.flags & 4194304 /* Conditional */) { + inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + } else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; @@ -41832,7 +42935,22 @@ var ts; } else { if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { - source = getApparentType(source); + var apparentSource = getApparentType(source); + // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. + // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes` + // with the simplified source. + if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (131072 /* Object */ | 524288 /* Intersection */))) { + // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints! + // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference + // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves + // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations + // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. + // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // remove this `allowComplexConstraintInference` flag. + allowComplexConstraintInference = false; + return inferFromTypes(apparentSource, target); + } + source = apparentSource; } if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; @@ -41928,33 +43046,38 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); - var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); - var targetRestType = getRestTypeOfTupleType(target); - var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; - for (var i = 0; i < fixedLength; i++) { - inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + if (isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; } - if (targetRestType) { - var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; } } - else { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } } } @@ -41964,12 +43087,20 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; + var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i])); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + function inferFromSignature(source, target, skipParameters) { + if (!skipParameters) { + var saveBivariant = bivariant; + var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; + // Once we descend into a bivariant signature we remain bivariant for all nested inferences + bivariant = bivariant || kind === 154 /* MethodDeclaration */ || kind === 153 /* MethodSignature */ || kind === 155 /* Constructor */; + forEachMatchingParameterType(source, target, inferFromContravariantTypes); + bivariant = saveBivariant; + } var sourceTypePredicate = getTypePredicateOfSignature(source); var targetTypePredicate = getTypePredicateOfSignature(target); if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { @@ -42000,8 +43131,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -42024,7 +43155,7 @@ var ts; } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); + return !!constraint && maybeTypeOfKind(constraint.flags & 4194304 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -42042,7 +43173,7 @@ var ts; function getContravariantInference(inference) { return inference.priority & 28 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates); } - function getCovariantInference(inference, context, signature) { + function getCovariantInference(inference, signature) { // Extract all object literal types and replace them with a single widened and normalized type. var candidates = widenObjectLiteralCandidates(inference.candidates); // We widen inferred literal types if @@ -42055,10 +43186,9 @@ var ts; var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if - // union types were requested or if all inferences were made from the return type position, infer a - // union type. Otherwise, infer a common supertype. - var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 28 /* PriorityImpliesCombination */ ? + // If all inferences were made from a position that implies a combined result, infer a union type. + // Otherwise, infer a common supertype. + var unwidenedType = inference.priority & 28 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates); return getWidenedType(unwidenedType); @@ -42069,16 +43199,19 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined; if (inference.contraCandidates) { - // If we have contravariant inferences we find the best common subtype and treat - // that as a single covariant candidate. - inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); - inference.contraCandidates = undefined; + var inferredContravariantType = getContravariantInference(inference); + // If we have both co- and contra-variant inferences, we prefer the contra-variant inference + // unless the co-variant inference is a subtype and not 'never'. + inferredType = inferredCovariantType && !(inferredCovariantType.flags & 32768 /* Never */) && + isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ? + inferredCovariantType : inferredContravariantType; } - if (inference.candidates) { - inferredType = getCovariantInference(inference, context, signature); + else if (inferredCovariantType) { + inferredType = inferredCovariantType; } - else if (context.flags & 2 /* NoDefault */) { + else if (context.flags & 1 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. inferredType = silentNeverType; } @@ -42095,7 +43228,7 @@ var ts; inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); } } } @@ -42124,11 +43257,40 @@ var ts; return result; } // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name) { + switch (name) { + case "document": + case "console": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return ts.Diagnostics.Cannot_find_name_0; + } + } function getResolvedSymbol(node) { var links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = !ts.nodeIsMissing(node) && - resolveName(node, node.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, ts.Diagnostics.Cannot_find_name_0, node, !ts.isWriteOnlyAccess(node), + resolveName(node, node.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node.escapedText), node, !ts.isWriteOnlyAccess(node), /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; @@ -42251,14 +43413,30 @@ var ts; } return undefined; } + function isDiscriminantType(type) { + if (type.flags & 262144 /* Union */) { + if (type.flags & (16 /* Boolean */ | 512 /* EnumLiteral */)) { + return true; + } + var combined = 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + combined |= t.flags; + } + if (combined & 27072 /* Unit */ && !(combined & 15794176 /* Instantiable */)) { + return true; + } + } + return false; + } function isDiscriminantProperty(type, name) { if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); } - return prop.isDiscriminantProperty; + return !!prop.isDiscriminantProperty; } } return false; @@ -42302,6 +43480,18 @@ var ts; } return flow.id; } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 262144 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, // we remove type string. @@ -42310,8 +43500,15 @@ var ts; if (assignedType.flags & 32768 /* Never */) { return assignedType; } - var reducedType = filterType(declaredType, function (t) { return isTypeComparableTo(assignedType, t); }); - if (!(reducedType.flags & 32768 /* Never */)) { + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (assignedType.flags & 33554432 /* FreshLiteral */ && assignedType.flags & 256 /* BooleanLiteral */) { + reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types + } + // Our crude heuristic produces an invalid result in some cases: see GH#26130. + // For now, when that happens, we give up and don't narrow at all. (This also + // means we'll never narrow for erroneous assignments where the assigned type + // is not assignable to the declared type.) + if (isTypeAssignableTo(assignedType, reducedType)) { return reducedType; } } @@ -42319,8 +43516,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; result |= getTypeFacts(t); } return result; @@ -42357,13 +43554,15 @@ var ts; } if (flags & 272 /* BooleanLike */) { return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + (type === falseType || type === regularFalseType) ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + (type === falseType || type === regularFalseType) ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } if (flags & 131072 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : - strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; + return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? + strictNullChecks ? 4079615 /* EmptyObjectStrictFacts */ : 4194303 /* EmptyObjectFacts */ : + isFunctionObjectType(type) ? + strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : + strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; @@ -42403,7 +43602,7 @@ var ts; errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTupleElementType(type, index) || + return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; } @@ -42489,10 +43688,10 @@ var ts; getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } - function getInitialOrAssignedType(node) { - return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? + function getInitialOrAssignedType(node, reference) { + return getConstraintForLocation(node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : - getAssignedType(node); + getAssignedType(node), reference); } function isEmptyArrayAssignment(node) { return node.kind === 235 /* VariableDeclaration */ && node.initializer && @@ -42538,6 +43737,23 @@ var ts; } return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. + function getSwitchClauseTypeOfWitnesses(switchStatement) { + var witnesses = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + if (clause.kind === 269 /* CaseClause */) { + if (clause.expression.kind === 9 /* StringLiteral */) { + witnesses.push(clause.expression.text); + continue; + } + return ts.emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } function eachTypeContainedIn(source, types) { return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } @@ -42562,6 +43778,9 @@ var ts; function forEachType(type, f) { return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } + function everyType(type, f) { + return type.flags & 262144 /* Union */ ? ts.every(type.types, f) : f(type); + } function filterType(type, f) { if (type.flags & 262144 /* Union */) { var types = type.types; @@ -42580,8 +43799,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var current = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var current = types_12[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -42661,8 +43880,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -42742,8 +43961,8 @@ var ts; } return resultType; function getTypeAtFlowNode(flow) { - if (flowDepth === 2500) { - // We have made 2500 recursive invocations. To avoid overflowing the call stack we report an error + if (flowDepth === 2000) { + // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); @@ -42846,11 +44065,11 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node, reference)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 262144 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node, reference)); } return declaredType; } @@ -42859,6 +44078,14 @@ var ts; // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, // return the declared type. if (containsMatchingReference(reference, node)) { + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration + if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) { + var init = ts.getDeclaredExpandoInitializer(node); + if (init && (init.kind === 194 /* FunctionExpression */ || init.kind === 195 /* ArrowFunction */)) { + return getTypeAtFlowNode(flow.antecedent); + } + } return declaredType; } // Assignment doesn't affect reference @@ -42882,7 +44109,8 @@ var ts; } } else { - var indexType = getTypeOfExpression(node.left.argumentExpression); + // We must get the context free expression type so as to not recur in an uncached fashion on the LHS (which causes exponential blowup in compile time) + var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression); if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } @@ -42918,15 +44146,21 @@ var ts; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { + var expr = flow.switchStatement.expression; + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); } + else if (expr.kind === 197 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } function getTypeAtFlowBranchLabel(flow) { @@ -43185,12 +44419,22 @@ var ts; if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & 262144 /* Union */)) { + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + function narrowTypeForTypeof(type) { + if (type.flags & 2 /* Unknown */ && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { + if (isTypeSubtypeOf(type, targetType)) { + return type; + } if (isTypeSubtypeOf(targetType, type)) { return targetType; } @@ -43201,11 +44445,8 @@ var ts; } } } + return type; } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify values with unit types @@ -43224,6 +44465,82 @@ var ts; var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; }); + var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + var clauseWitnesses; + var switchFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; }); + // The adjust clause start and end after removing the `default` statement. + var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ + if (!(hasDefaultClause || (type.flags & 262144 /* Union */))) { + var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return typeofTypesByName.get(text) || neverType; })), switchFacts); + if (impliedType.flags & 262144 /* Union */) { + impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & 32768 /* Never */)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & 15794176 /* Instantiable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; }) : + getTypeWithFacts(type, switchFacts); + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -43236,7 +44553,7 @@ var ts; } // Check that right operand is a function type with a prototype property var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + if (!isTypeDerivedFrom(rightType, globalFunctionType)) { return type; } var targetType; @@ -43253,22 +44570,12 @@ var ts; return type; } if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (ts.getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (ts.getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } + var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + targetType = constructSignatures.length ? + getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) : + emptyObjectType; } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); - } - return type; + return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom); } function getNarrowedType(type, candidate, assumeTrue, isRelated) { if (!assumeTrue) { @@ -43392,8 +44699,8 @@ var ts; function isParameterAssigned(symbol) { var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; + if (!(links.flags & 8388608 /* AssignmentsMarked */)) { + links.flags |= 8388608 /* AssignmentsMarked */; if (!hasParentWithAssignmentsMarked(func)) { markParameterAssignments(func); } @@ -43401,7 +44708,7 @@ var ts; return symbol.isAssigned || false; } function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); }); } function markParameterAssignments(node) { if (node.kind === 71 /* Identifier */) { @@ -43449,7 +44756,7 @@ var ts; return type; } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */) && !isInTypeQuery(location) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { markAliasSymbolAsReferenced(symbol); } } @@ -43493,8 +44800,8 @@ var ts; var container = ts.getContainingClass(node); while (container !== undefined) { if (container === declaration && container.name !== node) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; break; } container = ts.getContainingClass(container); @@ -43508,8 +44815,8 @@ var ts; while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */; } break; } @@ -43522,7 +44829,7 @@ var ts; var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && - !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { + !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -43600,6 +44907,9 @@ var ts; function isInsideFunction(node, threshold) { return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); } + function getPartOfForStatementContainingNode(node, container) { + return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; }); + } function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || @@ -43624,22 +44934,42 @@ var ts; if (containedInIterationStatement) { if (usedInFunction) { // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + var capturesBlockScopeBindingInLoopBody = true; + if (ts.isForStatement(container) && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container) { + var part = getPartOfForStatementContainingNode(node.parent, container); + if (part) { + var links = getNodeLinks(part); + links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */; + var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []); + ts.pushIfUnique(capturedBindings, symbol); + if (part === container.initializer) { + capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body + } + } + } + if (capturesBlockScopeBindingInLoopBody) { + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. if (container.kind === 223 /* ForStatement */ && ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */; } // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */; } if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */; } } + function isBindingCapturedByNode(node, decl) { + var links = getNodeLinks(node); + return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl)); + } function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; @@ -43781,31 +45111,29 @@ var ts; } function tryGetThisTypeAt(node, container) { if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } + var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === 194 /* FunctionExpression */ && - container.parent.kind === 202 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x + var className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + var classType = getJSClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && + else if (isInJS && + (container.kind === 194 /* FunctionExpression */ || container.kind === 237 /* FunctionDeclaration */) && ts.getJSDocClassTag(container)) { - var classType = getJavascriptClassType(container.symbol); + var classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -43820,13 +45148,40 @@ var ts; var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; return getFlowTypeOfReference(node, type); } - if (ts.isInJavaScriptFile(node)) { + if (isInJS) { var type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } + function getClassNameFromPrototypeMethod(container) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === 194 /* FunctionExpression */ && + ts.isBinaryExpression(container.parent) && + ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = container' + return container.parent // x.prototype.y = container + .left // x.prototype.y + .expression // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === 154 /* MethodDeclaration */ && + container.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.left.expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 273 /* PropertyAssignment */ && + container.parent.parent.kind === 186 /* ObjectLiteralExpression */ && + ts.isBinaryExpression(container.parent.parent.parent) && + ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) { + return container.parent.parent.parent.left.expression; + } + } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { @@ -43911,16 +45266,18 @@ var ts; // // js // ... // asyncMethod() { - // const _super = name => super[name]; + // const _super = Object.create(null, { + // asyncMethod: { get: () => super.asyncMethod }, + // }); // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); + // let x = yield _super.asyncMethod.call(this); // return x; // }); // } // ... // // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment: // // // ts // ... @@ -43932,19 +45289,20 @@ var ts; // // js // ... // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); + // const _super = Object.create(null, { + // a: { get: () => super.a, set: (v) => super.a = v }, + // b: { get: () => super.b, set: (v) => super.b = v } + // }; // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; + // [_super.a, _super.b] = yield ar; // }); // } // ... // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. + // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments + // as a call expression cannot be used as the target of a destructuring assignment while a property access can. + // + // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; @@ -44052,7 +45410,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44109,7 +45467,7 @@ var ts; var args = getEffectiveCallArguments(iife); var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { - return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); + return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined); } var links = getNodeLinks(iife); var cached = links.resolvedSignature; @@ -44176,9 +45534,21 @@ var ts; return undefined; } var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function + if (contextualReturnType) { + if (functionFlags & 2 /* Async */) { // Async function + var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); + } + return contextualReturnType; // Regular function + } + } + return undefined; + } + function getContextualTypeForAwaitOperand(node) { + var contextualType = getContextualType(node); + if (contextualType) { + var contextualAwaitedType = getAwaitedType(contextualType); + return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return undefined; } @@ -44225,7 +45595,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 + var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -44246,13 +45616,20 @@ var ts; var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right; switch (operatorToken.kind) { case 58 /* EqualsToken */: - return node === right && isContextSensitiveAssignment(binaryExpression) ? getTypeOfExpression(left) : undefined; + if (node !== right) { + return undefined; + } + var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression); + if (!contextSensitive) { + return undefined; + } + return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive; case 54 /* BarBarToken */: // When an || expression has a contextual type, the operands are contextually typed by that type. When an || // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !ts.isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: @@ -44262,9 +45639,9 @@ var ts; } } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. - function isContextSensitiveAssignment(binaryExpression) { - var kind = ts.getSpecialPropertyAssignmentKind(binaryExpression); + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + function getIsContextSensitiveAssignmentOrContextType(binaryExpression) { + var kind = ts.getAssignmentDeclarationKind(binaryExpression); switch (kind) { case 0 /* None */: return true; @@ -44282,19 +45659,46 @@ var ts; if (!decl) { return false; } - if (ts.isInJavaScriptFile(decl)) { - return !!ts.getJSDocTypeTag(decl); + var lhs = binaryExpression.left; + var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl); + if (overallAnnotation) { + return getTypeFromTypeNode(overallAnnotation); } - else if (ts.isIdentifier(binaryExpression.left.expression)) { - var id = binaryExpression.left.expression; - var parentSymbol = resolveName(id, id.escapedText, 67216319 /* Value */, undefined, id.escapedText, /*isUse*/ true); - return !ts.isFunctionSymbol(parentSymbol); + else if (ts.isIdentifier(lhs.expression)) { + var id = lhs.expression; + var parentSymbol = resolveName(id, id.escapedText, 67220415 /* Value */, undefined, id.escapedText, /*isUse*/ true); + if (parentSymbol) { + var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration); + if (annotated) { + var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), lhs.name.escapedText); + return type || false; + } + return false; + } } - return true; + return !ts.isInJSFile(decl); } - case 4 /* ThisProperty */: case 2 /* ModuleExports */: - return !binaryExpression.symbol || binaryExpression.symbol.valueDeclaration && !!ts.getJSDocTypeTag(binaryExpression.symbol.valueDeclaration); + case 4 /* ThisProperty */: + if (!binaryExpression.symbol) + return true; + if (binaryExpression.symbol.valueDeclaration) { + var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); + if (annotated) { + var type = getTypeFromTypeNode(annotated); + if (type) { + return type; + } + } + } + if (kind === 2 /* ModuleExports */) + return false; + var thisAccess = binaryExpression.left; + if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { + return false; + } + var thisType = checkThisExpression(thisAccess.expression); + return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; default: return ts.Debug.assertNever(kind); } @@ -44312,6 +45716,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +45725,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true); } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. @@ -44342,8 +45744,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_3 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); + var symbolName_2 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_2); if (propertyType) { return propertyType; } @@ -44408,47 +45810,36 @@ var ts; case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 71 /* Identifier */: + case 140 /* UndefinedKeyword */: return true; case 187 /* PropertyAccessExpression */: case 193 /* ParenthesizedExpression */: return isPossiblyDiscriminantValue(node.expression); + case 268 /* JsxExpression */: + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } + function discriminateContextualTypeByObjectMembers(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } + function discriminateContextualTypeByJSXAttributes(node, contextualType) { + return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 265 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType); + } // 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) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { - return contextualType; - } - // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` - var match; - propLoop: for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (!prop.symbol) - continue; - if (prop.kind !== 273 /* PropertyAssignment */) - continue; - if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = checkExpression(prop.initializer); - for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { - var type = _c[_b]; - var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { - if (match) { - if (type === match) - continue; // Finding multiple fields which discriminate to the same type is fine - match = undefined; - break propLoop; - } - match = type; - } - } + if (contextualType && contextualType.flags & 262144 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, contextualType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, contextualType); } } - return match || contextualType; + return contextualType; } /** * Woah! Do you really want to use this function? @@ -44488,6 +45879,8 @@ var ts; return getContextualTypeForReturnExpression(node); case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); + case 199 /* AwaitExpression */: + return getContextualTypeForAwaitOperand(parent); case 189 /* CallExpression */: case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); @@ -44513,7 +45906,7 @@ var ts; return getContextualTypeForSubstitutionExpression(parent.parent, node); case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; + var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } case 268 /* JsxExpression */: @@ -44532,6 +45925,12 @@ var ts; return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { + if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { + // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit + // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type + // (as below) instead! + return node.parent.contextualType; + } if (isJsxIntrinsicIdentifier(node.tagName)) { return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); } @@ -44540,7 +45939,7 @@ var ts; // Short-circuit if the class tag is using an element type 'any' return anyType; } - var isJs = ts.isInJavaScriptFile(node); + var isJs = ts.isInJSFile(node); return mapType(valueType, function (t) { return getJsxSignaturesParameterTypes(t, isJs, node); }); } function getJsxSignaturesParameterTypes(valueType, isJs, context) { @@ -44612,11 +46011,11 @@ var ts; if (managedSym) { var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (ts.length(declaredManagedType.typeParameters) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context)); return createTypeReference(declaredManagedType, args); } else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { - var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); } } @@ -44722,8 +46121,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var current = types_14[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44759,7 +46158,7 @@ var ts; return (node.kind === 184 /* BindingElement */ && !!node.initializer) || (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } - function checkArrayLiteral(node, checkMode) { + function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; var hasNonEndingSpreadElement = false; @@ -44781,7 +46180,7 @@ var ts; // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); + var restArrayType = checkExpression(e.expression, checkMode, forceTuple); var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); if (restElementType) { @@ -44790,7 +46189,7 @@ var ts; } else { var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); elementTypes.push(type); } if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { @@ -44802,35 +46201,47 @@ var ts; var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementCount; i < patternElements.length; i++) { - var e = patternElements[i]; - if (hasDefaultValue(e)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { - if (e.kind !== 208 /* OmittedExpression */) { - error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); - } - } - } + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + return tupleResult; + } + else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } return getArrayLiteralType(elementTypes, 2 /* Subtype */); } + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + if (elementCount === void 0) { elementCount = elementTypes.length; } + // Infer a tuple type when the contextual type is or contains a tuple-like type + if (contextualType && forEachType(contextualType, isTupleLikeType)) { + var minLength = elementCount - (hasRestElement ? 1 : 0); + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); + } + } + } + return createTupleType(elementTypes, minLength, hasRestElement); + } + } function getArrayLiteralType(elementTypes, unionReduction) { if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? @@ -44920,9 +46331,9 @@ var ts; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); + var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); - var isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; @@ -44940,7 +46351,7 @@ var ts; var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -45150,12 +46561,14 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; + var propagatingFlags = 0; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & 939524096 /* PropagatingFlags */); var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -45172,7 +46585,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -45180,7 +46593,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, 4096 /* JsxAttributes */); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -45189,7 +46602,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } // Handle children attribute @@ -45204,14 +46617,16 @@ var ts; if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); } + var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes); + var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); // If there are children in the body of JSX element, create dummy attribute "children" with the union of children types so that it will pass the attribute checking process var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] : - createArrayType(getUnionType(childrenTypes)); + (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes))); var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, propagatingFlags, 4096 /* JsxAttributes */); } } if (hasSpreadAnyType) { @@ -45228,7 +46643,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; + result.flags |= (propagatingFlags |= 268435456 /* ContainsObjectLiteral */); result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -45261,7 +46676,7 @@ var ts; function getJsxType(name, location) { var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); - var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); + var typeSymbol = exports && getSymbol(exports, name, 67897832 /* Type */); return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** @@ -45309,7 +46724,7 @@ var ts; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { - var isJavascript = ts.isInJavaScriptFile(node); + var isJavascript = ts.isInJSFile(node); var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -45319,7 +46734,7 @@ var ts; if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { candidateForTypeArgumentError = signature; } - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 2 /* AnyDefault */ : 0 /* None */); var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); } @@ -45386,7 +46801,7 @@ var ts; */ function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) { // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67901928 /* Type */); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 67897832 /* Type */); // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute @@ -45410,7 +46825,7 @@ var ts; } function getJsxLibraryManagedAttributes(jsxNamespace) { // JSX.LibraryManagedAttributes [symbol] - return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67897832 /* Type */); } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all @@ -45632,7 +47047,7 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - var isJs = ts.isInJavaScriptFile(openingLikeElement); + var isJs = ts.isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** @@ -45748,7 +47163,7 @@ var ts; var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; var reactNamespace = getJsxNamespace(node); var reactLocation = isNodeOpeningLikeElement ? node.tagName : node; - var reactSym = resolveName(reactLocation, reactNamespace, 67216319 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); + var reactSym = resolveName(reactLocation, reactNamespace, 67220415 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true); if (reactSym) { // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted @@ -45869,10 +47284,10 @@ var ts; if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { return true; } - if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + if (ts.isInJSFile(symbol.valueDeclaration)) { var parent = symbol.valueDeclaration.parent; return parent && ts.isBinaryExpression(parent) && - ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */; } } /** @@ -45917,7 +47332,7 @@ var ts; // Referencing abstract properties within their own constructors is not allowed if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) { error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } @@ -46072,6 +47487,12 @@ var ts; } } } + else if (strictNullChecks && prop && prop.valueDeclaration && + ts.isPropertyAccessExpression(prop.valueDeclaration) && + ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && + getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) { + assumeUninitialized = true; + } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 @@ -46185,7 +47606,7 @@ var ts; return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */); } function getSuggestedSymbolForNonexistentProperty(name, containingType) { - return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67220415 /* Value */); } function getSuggestionForNonexistentProperty(name, containingType) { var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); @@ -46290,7 +47711,7 @@ var ts; var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); + : ts.isInJSFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. @@ -46356,7 +47777,7 @@ var ts; } return errorType; } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + var indexType = checkExpression(indexExpression); if (objectType === errorType || objectType === silentNeverType) { return objectType; } @@ -46364,7 +47785,7 @@ var ts; error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -46485,16 +47906,13 @@ var ts; } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments - var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } + var argCount; + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments if (node.kind === 191 /* TaggedTemplateExpression */) { - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length argCount = args.length; if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. @@ -46512,7 +47930,7 @@ var ts; } } else if (node.kind === 150 /* Decorator */) { - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + argCount = getDecoratorArgumentCount(node, signature); } else { if (!node.arguments) { @@ -46523,11 +47941,11 @@ var ts; argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + var spreadArgIndex = getSpreadArgumentIndex(args); + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } } // Too many arguments implies incorrect arity. if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { @@ -46558,7 +47976,7 @@ var ts; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { - var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); + var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type @@ -46567,7 +47985,7 @@ var ts; if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); } - return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature, node, context) { // Skip context sensitive pass @@ -46625,58 +48043,40 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; inferTypes(context.inferences, thisArgumentType, thisType); } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); - var genericRestType = getGenericRestType(signature); - var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + var argType = checkExpressionWithContextualType(arg, paramType, mapper); inferTypes(context.inferences, argType, paramType); } } - if (genericRestType) { - var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); - inferTypes(context.inferences, spreadType, genericRestType); - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); - } - } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context); + inferTypes(context.inferences, spreadType, restType); } return getInferredTypes(context); } - function getSpreadArgumentType(node, args, index, argCount, restType, context) { + function getArrayifiedType(type) { + if (forEachType(type, function (t) { return !(t.flags & (1 /* Any */ | 15794176 /* Instantiable */) || isArrayType(t) || isTupleType(t)); })) { + return createArrayType(getIndexTypeOfType(type, 1 /* Number */) || errorType); + } + return type; + } + function getSpreadArgumentType(args, index, argCount, restType, context) { if (index >= argCount - 1) { - var arg = getEffectiveArgument(node, args, argCount - 1); + var arg = args[argCount - 1]; if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. return arg.kind === 213 /* SyntheticExpression */ ? createArrayType(arg.type) : - checkExpressionWithContextualType(arg.expression, restType, context); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -46684,12 +48084,9 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = getEffectiveArgumentType(node, i); - if (!argType) { - argType = checkExpressionWithContextualType(args[i], contextualType, context); - if (spreadIndex < 0 && isSpreadArgument(args[i])) { - spreadIndex = i - index; - } + var argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; } types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); } @@ -46698,23 +48095,23 @@ var ts; createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { - var isJavascript = ts.isInJavaScriptFile(signature.declaration); + var isJavascript = ts.isInJSFile(signature.declaration); var typeParameters = signature.typeParameters; var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); var mapper; for (var i = 0; i < typeArgumentNodes.length; i++) { ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments"); var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (!constraint) - continue; - var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; - var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { - return false; + if (constraint) { + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; + var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) { + return undefined; + } } } return typeArgumentTypes; @@ -46769,36 +48166,27 @@ var ts; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; - var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; + var restType = getNonArrayRestType(signature); + var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length; for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { - if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { - var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); - return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); - } - else { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; - } + var arg = args[i]; + if (arg.kind !== 208 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { + return false; } } } + if (restType) { + var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined); + var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined; + return checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage); + } return true; } /** @@ -46812,19 +48200,20 @@ var ts; } } } + function createSyntheticExpression(parent, type, isSpread) { + var result = ts.createNode(213 /* SyntheticExpression */, parent.pos, parent.end); + result.parent = parent; + result.type = type; + result.isSpread = isSpread || false; + return result; + } /** * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; // TODO: GH#18217 + var args_4 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); @@ -46832,283 +48221,87 @@ var ts; } return args_4; } - else if (node.kind === 150 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; + if (node.kind === 150 /* Decorator */) { + return getEffectiveDecoratorArguments(node); } - else if (ts.isJsxOpeningLikeElement(node)) { + if (ts.isJsxOpeningLikeElement(node)) { return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } - else { - var args = node.arguments || ts.emptyArray; - var length_4 = args.length; - if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { - // We have a spread argument in the last position and no other spread arguments. If the type - // of the argument is a tuple type, spread the tuple elements into the argument list. We can - // call checkExpressionCached because spread expressions never have a contextual type. - var spreadArgument_1 = args[length_4 - 1]; - var type = checkExpressionCached(spreadArgument_1.expression); - if (isTupleType(type)) { - var typeArguments = type.typeArguments || ts.emptyArray; - var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; - var syntheticArgs = ts.map(typeArguments, function (t, i) { - var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); - arg.parent = spreadArgument_1; - arg.type = t; - arg.isSpread = i === restIndex_2; - return arg; - }); - return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); - } - } - return args; - } - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 150 /* Decorator */) { - switch (node.parent.kind) { - case 238 /* ClassDeclaration */: - case 207 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 152 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 154 /* MethodDeclaration */: - case 156 /* GetAccessor */: - case 157 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 149 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - default: - return ts.Debug.fail(); + var args = node.arguments || ts.emptyArray; + var length = args.length; + if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); }); + return ts.concatenate(args.slice(0, length - 1), syntheticArgs); } } - else { - return args.length; - } + return args; } /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. + * Returns the synthetic argument list for a decorator invocation. */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 238 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); + function getEffectiveDecoratorArguments(node) { + var parent = node.parent; + var expr = node.expression; + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class). + return [ + createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent))) + ]; + case 149 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts). + var func = parent.parent; + return [ + createSyntheticExpression(expr, parent.parent.kind === 155 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType), + createSyntheticExpression(expr, anyType), + createSyntheticExpression(expr, numberType) + ]; + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators + // for ES3, we will only pass two arguments. + var hasPropDesc = parent.kind !== 152 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */; + return [ + createSyntheticExpression(expr, getParentTypeOfClassElement(parent)), + createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)), + createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType) + ]; } - if (node.kind === 149 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 155 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; + return ts.Debug.fail(); } /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. + * Returns the argument count for a decorator node that works like a function invocation. */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - node = node.parent; - if (node.kind === 155 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 152 /* PropertyDeclaration */ || - node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - var name = element.name; - switch (name.kind) { - case 71 /* Identifier */: - return getLiteralType(ts.idText(name)); - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(name.text); - case 147 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(name); - if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return errorType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 238 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 149 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 152 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return errorType; - } - if (node.kind === 154 /* MethodDeclaration */ || - node.kind === 156 /* GetAccessor */ || - node.kind === 157 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return errorType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return errorType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 150 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 150 /* Decorator */ || - (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 150 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; + function getDecoratorArgumentCount(node, signature) { + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 1; + case 152 /* PropertyDeclaration */: + return 2; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // For ES3 or decorators with only two parameters we supply only two arguments + return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3; + case 149 /* Parameter */: + return 3; + default: + return ts.Debug.fail(); } } function getArgumentArityError(node, signatures, args) { @@ -47117,6 +48310,7 @@ var ts; var belowArgCount = Number.NEGATIVE_INFINITY; var aboveArgCount = Number.POSITIVE_INFINITY; var argCount = args.length; + var closestSignature; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; var minCount = getMinArgumentCount(sig); @@ -47125,7 +48319,10 @@ var ts; belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); @@ -47136,16 +48333,25 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var related; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + } + } if (hasRestParameter || hasSpreadArgument) { var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var min = Infinity; @@ -47178,36 +48384,20 @@ var ts; return resolveErrorCall(node); } var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // The excludeArgument array contains true for each context sensitive argument (an argument + // is context sensitive it is susceptible to a one-time permanent contextual typing). // // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those + // without using the susceptible parameters that are functions, and once more for those // parameters, contextually typing each as we go along. // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. + // For a tagged template, then the first argument be 'undefined' if necessary because it + // represents a TemplateStringsArray. // // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument; - var excludeCount = 0; - if (!isDecorator && !isSingleNonGenericCandidate) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - excludeCount++; - } - } - } + var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -47277,14 +48467,17 @@ var ts; else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && ts.every(signatures, function (sig) { return typeArguments.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments.length > ts.length(sig.typeParameters); })) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (args) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + else { + var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); }); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { @@ -47304,60 +48497,80 @@ var ts; return candidate; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { - var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + var candidate = candidates[candidateIndex]; + if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { continue; } - var candidate = void 0; - var inferenceContext = originalCandidate.typeParameters ? - createInferenceContext(originalCandidate.typeParameters, originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0 /* None */) : - undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - var typeArgumentResult = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); - if (typeArgumentResult) { - typeArgumentTypes = typeArgumentResult; - } - else { - candidateForTypeArgumentError = originalCandidate; - break; - } + var checkCandidate = void 0; + var inferenceContext = void 0; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false); + if (!typeArgumentTypes) { + candidateForTypeArgumentError = candidate; + continue; } - else { - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - } - var isJavascript = ts.isInJavaScriptFile(candidate.declaration); - candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); - // If the original signature has a generic rest type, instantiation may produce a - // signature with different arity and we need to perform another arity check. - if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { - candidateForArgumentArityError = candidate; - break; - } - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - candidateForArgumentError = candidate; - break; - } - if (excludeCount === 0) { - candidates[candidateIndex] = candidate; - return candidate; - } - excludeCount--; - if (excludeCount > 0) { - excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { - excludeArgument = undefined; + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = checkCandidate; + continue; } } + else { + checkCandidate = candidate; + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + if (excludeArgument) { + // If one or more context sensitive arguments were excluded, we start including + // them now (and keeping do so for any subsequent candidates) and perform a second + // round of type inference and applicability checking for this particular candidate. + excludeArgument = undefined; + if (inferenceContext) { + var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + } + if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + // Give preference to error candidates that have no rest parameters (as they are more specific) + if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { + candidateForArgumentError = checkCandidate; + } + continue; + } + } + candidates[candidateIndex] = checkCandidate; + return checkCandidate; } return undefined; } } + function getExcludeArgument(args) { + var excludeArgument; + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + } + } + return excludeArgument; + } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -47377,7 +48590,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_6 = function (i) { + var _loop_7 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -47388,7 +48601,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_6(i); + _loop_7(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -47427,17 +48640,27 @@ var ts; if (!typeParameters) { return candidate; } - var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; + var instantiated = typeArgumentNodes + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node))) + : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); + candidates[bestIndex] = instantiated; + return instantiated; + } + function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) { var typeArguments = typeArgumentNodes.map(getTypeOfNode); while (typeArguments.length > typeParameters.length) { typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } - var instantiated = createSignatureInstantiation(candidate, typeArguments); - candidates[bestIndex] = instantiated; - return instantiated; + return typeArguments; + } + function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { + var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; @@ -47490,11 +48713,11 @@ var ts; // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; // TS 1.0 Spec: 4.12 // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. if (funcType !== errorType && node.typeArguments) { @@ -47506,16 +48729,23 @@ var ts; // TypeScript employs overload resolution in typed function calls in order to support functions // with multiple call signatures. if (!callSignatures.length) { - if (constructSignatures.length) { + if (numConstructSignatures) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - invocationError(node, apparentType, 0 /* Call */); + var relatedInformation = void 0; + if (node.arguments.length === 1 && isTypeAssertion(ts.first(node.arguments))) { + var text = ts.getSourceFileOfNode(node).text; + if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } + invocationError(node, apparentType, 0 /* Call */, relatedInformation); } return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(function (sig) { return ts.isInJavaScriptFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { + if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -47588,11 +48818,13 @@ var ts; var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + if (!noImplicitAny) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } } return signature; } @@ -47662,10 +48894,11 @@ var ts; } return true; } - function invocationError(node, apparentType, kind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ - ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); + function invocationError(node, apparentType, kind, relatedInformation) { + var diagnostic = error(node, (kind === 0 /* Call */ ? + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -47689,8 +48922,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (!callSignatures.length) { @@ -47729,8 +48962,8 @@ var ts; return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length; + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) { return resolveUntypedCall(node); } if (isPotentiallyUncalledDecorator(node, callSignatures)) { @@ -47758,7 +48991,7 @@ var ts; return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && !signature.hasRestParameter && - signature.parameters.length < getEffectiveArgumentCount(decorator, /*args*/ undefined, signature); + signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } /** @@ -47837,34 +49070,38 @@ var ts; * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node) { - if (node && ts.isInJavaScriptFile(node)) { + function isJSConstructor(node) { + if (!node || !ts.isInJSFile(node)) { + return false; + } + var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node : + ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer : + undefined; + if (func) { // If the node has a @class tag, treat it like a constructor. if (ts.getJSDocClassTag(node)) return true; // If the symbol of the node has members, treat it like a constructor. - var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : - ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : - undefined; + var symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== undefined; } return false; } - function isJavascriptConstructorType(type) { + function isJSConstructorType(type) { if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol) { + function getJSClassType(symbol) { var inferred; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } var assigned = getAssignedClassType(symbol); var valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -47877,14 +49114,11 @@ var ts; (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); - if (assignmentSymbol) { - var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); - if (prototype) { - return checkExpression(prototype); - } - } + var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype"); + var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration); + return init ? checkExpression(init) : undefined; } - function getAssignedJavascriptPrototype(node) { + function getAssignedJSPrototype(node) { if (!node.parent) { return false; } @@ -47937,7 +49171,7 @@ var ts; if (!funcSymbol && node.expression.kind === 71 /* Identifier */) { funcSymbol = getResolvedSymbol(node.expression); } - var type = funcSymbol && getJavascriptClassType(funcSymbol); + var type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -47948,7 +49182,7 @@ var ts; } } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (ts.isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments[0]); } var returnType = getReturnTypeOfSignature(signature); @@ -47958,8 +49192,8 @@ var ts; return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } var jsAssignmentType; - if (ts.isInJavaScriptFile(node)) { - var decl = ts.getDeclarationOfJSInitializer(node); + if (ts.isInJSFile(node)) { + var decl = ts.getDeclarationOfExpando(node); if (decl) { var jsSymbol = getSymbolOfNode(decl); if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { @@ -47985,7 +49219,7 @@ var ts; if (!globalESSymbol) { return false; } - return globalESSymbol === resolveName(left, "Symbol", 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + return globalESSymbol === resolveName(left, "Symbol", 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); } function checkImportCallExpression(node) { // Check grammar of dynamic import @@ -48044,7 +49278,7 @@ var ts; // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 if (resolvedRequire === requireSymbol) { return true; } @@ -48169,14 +49403,11 @@ var ts; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); - var hasRest = hasEffectiveRestParameter(source); - if (hasRest && pos === paramCount - 1) { - var genericRestType = getGenericRestType(source); - if (genericRestType) { - return genericRestType; - } + var restType = getEffectiveRestType(source); + if (restType && pos === paramCount - 1) { + return restType; } - var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; for (var i = start; i < paramCount; i++) { @@ -48185,17 +49416,7 @@ var ts; } var minArgumentCount = getMinArgumentCount(source); var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, hasRest, names); - } - function getTypeOfRestParameter(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (isTupleType(restType)) { - return getRestTypeOfTupleType(restType); - } - return restType; - } - return undefined; + return createTupleType(types, minLength, !!restType, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -48219,15 +49440,6 @@ var ts; } return signature.minArgumentCount; } - function getGenericRestType(signature) { - if (signature.hasRestParameter) { - var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - if (restType.flags & 15794176 /* Instantiable */) { - return restType; - } - } - return undefined; - } function hasEffectiveRestParameter(signature) { if (signature.hasRestParameter) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); @@ -48235,6 +49447,17 @@ var ts; } return false; } + function getEffectiveRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; + } + return undefined; + } + function getNonArrayRestType(signature) { + var restType = getEffectiveRestType(signature); + return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); } @@ -48320,6 +49543,16 @@ var ts; } return emptyObjectType; } + function createPromiseLikeType(promisedType) { + // creates a `PromiseLike` type where `T` is the promisedType argument + var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true); + if (globalPromiseLikeType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseLikeType, [promisedType]); + } + return emptyObjectType; + } function createPromiseReturnType(func, promisedType) { var promiseType = createPromiseType(promisedType); if (promiseType === emptyObjectType) { @@ -48437,10 +49670,61 @@ var ts; ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) { + var facts = 0 /* None */; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (var i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (var i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (var i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || 8192 /* TypeofNEHostObject */; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (var i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || 64 /* TypeofEQHostObject */; + } + // Remove equalities for types that appear before the + // active clause. + for (var i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } function isExhaustiveSwitchStatement(node) { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === 197 /* TypeOfExpression */) { + var operandType = getTypeOfExpression(node.expression.expression); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + var witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); + var type_5 = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 32768 /* Never */); + } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; @@ -48490,7 +49774,7 @@ var ts; return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } @@ -48560,6 +49844,7 @@ var ts; } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage @@ -48569,8 +49854,10 @@ var ts; return links_1.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var singleReturnSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - return links_1.contextFreeType = createAnonymousType(node.symbol, emptySymbols, [singleReturnSignature], ts.emptyArray, undefined, undefined); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); + returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; } @@ -48611,7 +49898,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48816,8 +50102,8 @@ var ts; } if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var t = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48977,7 +50263,7 @@ var ts; if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; var type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -49003,8 +50289,8 @@ var ts; } else { checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = isTupleType(sourceType) ? - getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -49118,7 +50404,7 @@ var ts; return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { - if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { + if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -49256,9 +50542,9 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -49273,15 +50559,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { var prop = _a[_i]; var propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & 32 /* Class */) { var name = prop.escapedName; - var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + var symbol = resolveName(prop.valueDeclaration, name, 67897832 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); @@ -49334,8 +50620,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +50630,7 @@ var ts; case 3 /* PrototypeProperty */: case 4 /* ThisProperty */: var symbol = getSymbolOfNode(left); - var init = ts.getAssignedJavascriptInitializer(right); + var init = ts.getAssignedExpandoInitializer(right); return init && ts.isObjectLiteralExpression(init) && symbol && ts.hasEntries(symbol.exports); default: @@ -49450,7 +50736,7 @@ var ts; return stringType; } function getContextNode(node) { - if (node.kind === 266 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -49492,19 +50778,15 @@ var ts; var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || + ts.isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (ts.isInJavaScriptFile(declaration)) { + if (ts.isInJSFile(declaration)) { if (widened.flags & 24576 /* Nullable */) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyType); - } + reportImplicitAny(declaration, anyType); return anyType; } else if (isEmptyArrayLiteralType(widened)) { - if (noImplicitAny) { - reportImplicitAnyError(declaration, anyArrayType); - } + reportImplicitAny(declaration, anyArrayType); return anyArrayType; } } @@ -49535,11 +50817,11 @@ var ts; } return false; } - function checkExpressionForMutableLocation(node, checkMode, contextualType) { + function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { if (arguments.length === 2) { contextualType = getContextualType(node); } - var type = checkExpression(node, checkMode); + var type = checkExpression(node, checkMode, forceTuple); return isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, contextualType); } @@ -49586,15 +50868,19 @@ var ts; * to cache the result. */ function getTypeOfExpression(node, cache) { + var expr = ts.skipParentheses(node); // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { - var funcType = checkNonNullExpression(node.expression); + if (expr.kind === 189 /* CallExpression */ && expr.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { + var funcType = checkNonNullExpression(expr.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return getReturnTypeOfSignature(signature); } } + else if (expr.kind === 192 /* TypeAssertionExpression */ || expr.kind === 210 /* AsExpression */) { + return getTypeFromTypeNode(expr.type); + } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions // should have a parameter that indicates whether full error checking is required such that // we can perform the optimizations locally. @@ -49608,9 +50894,13 @@ var ts; * It sets the contextual type of the node to any before calling getTypeOfExpression. */ function getContextFreeTypeOfExpression(node) { + var links = getNodeLinks(node); + if (links.contextFreeType) { + return links.contextFreeType; + } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = getTypeOfExpression(node); + var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } @@ -49621,13 +50911,13 @@ var ts; // object, it serves as an indicator that all contained function and arrow expressions should be considered to // have the wildcard function type; this form of type check is used during overload resolution to exclude // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { + function checkExpression(node, checkMode, forceTuple) { var type; if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } if (isConstEnumObjectType(type)) { @@ -49646,13 +50936,13 @@ var ts; return type; } function checkParenthesizedExpression(node, checkMode) { - var tag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode); } return checkExpression(node.expression, checkMode); } - function checkExpressionWorker(node, checkMode) { + function checkExpressionWorker(node, checkMode, forceTuple) { switch (node.kind) { case 71 /* Identifier */: return checkIdentifier(node); @@ -49677,7 +50967,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return globalRegExpType; case 185 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); + return checkArrayLiteral(node, checkMode, forceTuple); case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); case 187 /* PropertyAccessExpression */: @@ -49770,9 +51060,6 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } - function isRestParameterType(type) { - return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); - } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -49802,7 +51089,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -50268,7 +51555,7 @@ var ts; checkDecorators(node); } function getEffectiveTypeArguments(node, typeParameters) { - return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJavaScriptFile(node)); + return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node)); } function checkTypeArgumentConstraints(node, typeParameters) { var typeArguments; @@ -50299,7 +51586,7 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); @@ -50400,8 +51687,8 @@ var ts; function checkMappedType(node) { checkSourceElement(node.typeParameter); checkSourceElement(node.type); - if (noImplicitAny && !node.type) { - reportImplicitAnyError(node, anyType); + if (!node.type) { + reportImplicitAny(node, anyType); } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); @@ -50640,6 +51927,13 @@ var ts; } } } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); function checkExportsOnMergedDeclarations(node) { if (!produceDiagnostics) { return; @@ -50697,13 +51991,6 @@ var ts; } } } - var DeclarationSpaces; - (function (DeclarationSpaces) { - DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; - DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; - DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; - DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; - })(DeclarationSpaces || (DeclarationSpaces = {})); function getDeclarationSpaces(decl) { var d = decl; switch (d.kind) { @@ -50733,10 +52020,10 @@ var ts; case 246 /* ImportEqualsDeclaration */: case 249 /* NamespaceImport */: case 248 /* ImportClause */: - var result_3 = 0 /* None */; + var result_4 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; + ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); + return result_4; case 235 /* VariableDeclaration */: case 184 /* BindingElement */: case 237 /* FunctionDeclaration */: @@ -50966,7 +52253,7 @@ var ts; error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); return; } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67220415 /* Value */, /*ignoreErrors*/ true); var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { @@ -50989,7 +52276,7 @@ var ts; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67220415 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); return; @@ -51046,7 +52333,7 @@ var ts; if (!typeName) return; var rootName = getFirstIdentifier(typeName); - var meaning = (typeName.kind === 71 /* Identifier */ ? 67901928 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + var meaning = (typeName.kind === 71 /* Identifier */ ? 67897832 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */ @@ -51304,8 +52591,8 @@ var ts; if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); + if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { + reportImplicitAny(node, anyType); } if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) { // A generator with a body and no type annotation can still cause errors. It can error if the @@ -51315,7 +52602,7 @@ var ts; } } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { var typeTag = ts.getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -51801,7 +53088,7 @@ var ts; else if (n.kind === 71 /* Identifier */) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - var symbol = resolveName(n, n.escapedText, 67216319 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); + var symbol = resolveName(n, n.escapedText, 67220415 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -51884,7 +53171,7 @@ var ts; if (nameText) { var property = getPropertyOfType(parentType, nameText); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. - if (parent.initializer && property && !ts.isComputedPropertyName(name)) { + if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer.kind === 97 /* SuperKeyword */, parentType, property); } } @@ -51924,7 +53211,7 @@ var ts; // Don't validate for-in initializer as it is already an error var initializer = ts.getEffectiveInitializer(node); if (initializer) { - var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + var isJSObjectLiteralInitializer = ts.isInJSFile(node) && ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && ts.hasEntries(symbol.exports); @@ -51940,7 +53227,7 @@ var ts; var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & 67108864 /* JSContainer */)) { + !(symbol.flags & 67108864 /* Assignment */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -52314,13 +53601,17 @@ var ts; } if (allowSyncIterables) { if (typeAsIterable.iteratedTypeOfIterable) { - return typeAsIterable.iteratedTypeOfIterable; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(typeAsIterable.iteratedTypeOfIterable) + : typeAsIterable.iteratedTypeOfIterable; } // As an optimization, if the type is an instantiation of the global `Iterable` or // `IterableIterator` then just grab its type argument. if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = getAwaitedType(type.typeArguments[0]) + : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); @@ -52347,9 +53638,11 @@ var ts; ? createAsyncIterableType(iteratedType) : createIterableType(iteratedType), errorNode); } - return asyncMethodType - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; + if (iteratedType) { + return allowAsyncIterables + ? typeAsIterable.iteratedTypeOfAsyncIterable = asyncMethodType ? iteratedType : getAwaitedType(iteratedType) + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } } } function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { @@ -52890,7 +54183,10 @@ var ts; if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + else { + // Report static side error only when instance type is assignable + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + } if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } @@ -52901,7 +54197,7 @@ var ts; // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { + if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType_1; })) { error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } @@ -52944,7 +54240,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_7 = function (member) { + var _loop_8 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -52963,7 +54259,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_7(member); + _loop_8(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -53127,6 +54423,8 @@ var ts; } function isPropertyInitializedInConstructor(propName, propType, constructor) { var reference = ts.createPropertyAccess(ts.createThis(), propName); + reference.expression.parent = reference; + reference.parent = constructor; reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); return !(getFalsyFlags(flowType) & 8192 /* Undefined */); @@ -53616,8 +54914,8 @@ var ts; // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (67216319 /* Value */ | 1048576 /* ExportValue */) ? 67216319 /* Value */ : 0) | - (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | + var excludedMeanings = (symbol.flags & (67220415 /* Value */ | 1048576 /* ExportValue */) ? 67220415 /* Value */ : 0) | + (symbol.flags & 67897832 /* Type */ ? 67897832 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { var message = node.kind === 255 /* ExportSpecifier */ ? @@ -53628,7 +54926,7 @@ var ts; // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules && node.kind === 255 /* ExportSpecifier */ - && !(target.flags & 67216319 /* Value */) + && !(target.flags & 67220415 /* Value */) && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } @@ -53681,14 +54979,14 @@ var ts; if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 67216319 /* Value */) { + if (target.flags & 67220415 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 67216319 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + if (!(resolveEntityName(moduleName, 67220415 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 67901928 /* Type */) { + if (target.flags & 67897832 /* Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -53742,13 +55040,13 @@ var ts; } function checkExportSpecifier(node) { checkAliasSymbol(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); } if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + var symbol = resolveName(exportedName, exportedName.escapedText, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); @@ -53779,7 +55077,7 @@ var ts; } if (node.expression.kind === 71 /* Identifier */) { markExportAsReferenced(node); - if (compilerOptions.declaration) { + if (ts.getEmitDeclarations(compilerOptions)) { collectLinkedAliases(node.expression, /*setVisibility*/ true); } } @@ -53811,7 +55109,7 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -53859,7 +55157,7 @@ var ts; if (!node) { return; } - if (ts.isInJavaScriptFile(node)) { + if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; return ts.forEach(tags, checkSourceElement); @@ -54026,7 +55324,7 @@ var ts; } } function checkJSDocTypeIsInJsFile(node) { - if (!ts.isInJavaScriptFile(node)) { + if (!ts.isInJSFile(node)) { grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -54097,13 +55395,20 @@ var ts; // determining the type of foo would cause foo to be given type any because of the recursive reference. // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { - if (deferredNodes) { + var enclosingFile = ts.getSourceFileOfNode(node); + var links = getNodeLinks(enclosingFile); + if (!(links.flags & 1 /* TypeChecked */)) { + links.deferredNodes = links.deferredNodes || ts.createMap(); var id = "" + getNodeId(node); - deferredNodes.set(id, node); + links.deferredNodes.set(id, node); } } - function checkDeferredNodes() { - deferredNodes.forEach(function (node) { + function checkDeferredNodes(context) { + var links = getNodeLinks(context); + if (!links.deferredNodes) { + return; + } + links.deferredNodes.forEach(function (node) { switch (node.kind) { case 194 /* FunctionExpression */: case 195 /* ArrowFunction */: @@ -54157,9 +55462,8 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); + checkDeferredNodes(node); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } @@ -54170,7 +55474,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54273,7 +55576,7 @@ var ts; // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. if (!isStatic) { - copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); + copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67897832 /* Type */); } break; case 194 /* FunctionExpression */: @@ -54358,12 +55661,12 @@ var ts; } return result; } - function isNodeWithinConstructorOfClass(node, classDeclaration) { - return ts.findAncestor(node, function (element) { - if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node) { + return !!ts.findAncestor(node, function (element) { + if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) { return true; } - else if (element === classDeclaration || ts.isFunctionLikeDeclaration(element)) { + else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) { return "quit"; } return false; @@ -54388,7 +55691,7 @@ var ts; return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent); switch (specialPropertyAssignmentKind) { case 1 /* ExportsProperty */: case 3 /* PrototypeProperty */: @@ -54414,7 +55717,7 @@ var ts; if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } - if (ts.isInJavaScriptFile(entityName) && + if (ts.isInJSFile(entityName) && entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment @@ -54426,7 +55729,7 @@ var ts; if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression var success = resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + /*all meanings*/ 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); if (success && success !== unknownSymbol) { return success; } @@ -54452,10 +55755,10 @@ var ts; var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { - meaning = 67901928 /* Type */; + meaning = 67897832 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 67216319 /* Value */; + meaning |= 67220415 /* Value */; } } else { @@ -54471,7 +55774,7 @@ var ts; return ts.getParameterSymbolFromJSDoc(entityName.parent); } if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 301 /* JSDocTemplateTag */) { - ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; } @@ -54485,7 +55788,7 @@ var ts; var symbol = getIntrinsicTagSymbol(entityName.parent); return symbol === unknownSymbol ? undefined : symbol; } - return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + return resolveEntityName(entityName, 67220415 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); @@ -54502,7 +55805,7 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67897832 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } else if (entityName.parent.kind === 265 /* JsxAttribute */) { @@ -54581,7 +55884,7 @@ var ts; // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } @@ -54597,6 +55900,7 @@ var ts; case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: + case 75 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 181 /* ImportType */: return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; @@ -54606,7 +55910,7 @@ var ts; } function getShorthandAssignmentValueSymbol(location) { if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); + return resolveEntityName(location.name, 67220415 /* Value */ | 2097152 /* Alias */); } return undefined; } @@ -54614,30 +55918,25 @@ var ts; function getExportSpecifierLocalTargetSymbol(node) { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + resolveEntityName(node.propertyName || node.name, 67220415 /* Value */ | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return errorType; } + var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); + var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class)); if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); - if (ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; + return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode; } if (ts.isExpressionNode(node)) { return getRegularTypeOfExpression(node); } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + if (classType && !classDecl.isImplements) { // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } @@ -54732,13 +56031,32 @@ var ts; ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } + function getClassElementPropertyKeyType(element) { + var name = element.name; + switch (name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.idText(name)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + return isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */) ? nameType : stringType; + default: + ts.Debug.fail("Unsupported property name."); + return errorType; + } + } // Return the list of properties of the given type, augmented with properties from Function // if the type has call or construct signatures function getAugmentedPropertiesOfType(type) { type = getApparentType(type); var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); - if (typeHasCallOrConstructSignatures(type)) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : + getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : + undefined; + if (functionType) { + ts.forEach(getPropertiesOfType(functionType), function (p) { if (!propsByName.has(p.escapedName)) { propsByName.set(p.escapedName, p); } @@ -54799,13 +56117,13 @@ var ts; // for export assignments - check if resolved symbol for RHS is itself a value // otherwise - check if at least one export is value symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 67216319 /* Value */) + ? !!(moduleSymbol.flags & 67220415 /* Value */) : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); } return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 67216319 /* Value */); + return s && !!(s.flags & 67220415 /* Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -54854,7 +56172,7 @@ var ts; var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 67216319 /* Value */)) { + if (isNonLocalAlias(symbol, /*excludes*/ 67220415 /* Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -54867,11 +56185,11 @@ var ts; var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (ts.isStatementWithLocals(container)) { var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (resolveName(container.parent, symbol.escapedName, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { + if (resolveName(container.parent, symbol.escapedName, 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) { // binding is captured in the function // should be renamed if: // - binding is not top level - top level bindings never collide with anything @@ -54887,7 +56205,7 @@ var ts; // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); @@ -54963,7 +56281,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 67216319 /* Value */) && + return !!(target.flags & 67220415 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -54976,7 +56294,7 @@ var ts; return true; } var target = getSymbolLinks(symbol).target; // TODO: GH#18217 - if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { + if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67220415 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } @@ -55021,6 +56339,25 @@ var ts; !parameter.initializer && ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } + function isExpandoFunctionDeclaration(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return false; + } + var symbol = getSymbolOfNode(declaration); + if (!symbol || !(symbol.flags & 16 /* Function */)) { + return false; + } + return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 67220415 /* Value */ && ts.isPropertyAccessExpression(p.valueDeclaration); }); + } + function getPropertiesOfContainerFunction(node) { + var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration); + if (!declaration) { + return ts.emptyArray; + } + var symbol = getSymbolOfNode(declaration); + return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray; + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags || 0; } @@ -55065,9 +56402,9 @@ var ts; return ts.TypeReferenceSerializationKind.Unknown; } // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 67216319 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var valueSymbol = resolveEntityName(typeName, 67220415 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 67901928 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + var typeSymbol = resolveEntityName(typeName, 67897832 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); if (valueSymbol && valueSymbol === typeSymbol) { var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { @@ -55169,7 +56506,7 @@ var ts; location = getDeclarationContainer(parent); } } - return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + return resolveName(location, reference.escapedText, 67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } function getReferencedValueDeclaration(referenceIn) { if (!ts.isGeneratedIdentifier(referenceIn)) { @@ -55184,18 +56521,20 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { + if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); + return !!(type.flags & 448 /* Literal */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function literalTypeToNode(type) { - return ts.createLiteral(type.value); + function literalTypeToNode(type, enclosing) { + var enumResult = type.flags & 512 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 67220415 /* Value */, enclosing) + : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse(); + return enumResult || ts.createLiteral(type.value); } function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -55238,6 +56577,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55279,7 +56620,12 @@ var ts; getAccessor: getAccessor }; }, - getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); } + getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); }, + isBindingCapturedByNode: function (node, decl) { + var parseNode = ts.getParseTreeNode(node); + var parseDecl = ts.getParseTreeNode(decl); + return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); + } }; function isInHeritageClause(node) { return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; @@ -55293,9 +56639,9 @@ var ts; // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67897832 /* Type */ | 1920 /* Namespace */; if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { - meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + meaning = 67220415 /* Value */ | 1048576 /* ExportValue */; } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; @@ -55384,6 +56730,9 @@ var ts; if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } + if (file.jsGlobalAugmentations) { + mergeSymbolTable(globals, file.jsGlobalAugmentations); + } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); } @@ -55428,6 +56777,8 @@ var ts; globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; + globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType; globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); @@ -55455,31 +56806,30 @@ var ts; } } amalgamatedDuplicates.forEach(function (_a) { - var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; - var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols; // If not many things conflict, issue individual errors - if (conflictingKeys.length < 8) { - addErrorsForDuplicates(firstFileInstances, secondFileInstances); - addErrorsForDuplicates(secondFileInstances, firstFileInstances); - return; + if (conflictingSymbols.size < 8) { + conflictingSymbols.forEach(function (_a, symbolName) { + var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations; + var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; + for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) { + var node = firstFileLocations_1[_i]; + addDuplicateDeclarationError(node, message, symbolName, secondFileLocations); + } + for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) { + var node = secondFileLocations_1[_b]; + addDuplicateDeclarationError(node, message, symbolName, firstFileLocations); + } + }); + } + else { + // Otherwise issue top-level error since the files appear very identical in terms of what they contain + var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } - // Otheriwse issue top-level error since the files appear very identical in terms of what they appear - var list = conflictingKeys.join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); }); amalgamatedDuplicates = undefined; - function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { - secondFileInstances.forEach(function (locations, symbolName) { - var firstFileEquivalent = firstFileInstances.get(symbolName); - var message = locations.blockScoped - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - locations.instances.forEach(function (node) { - addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); - }); - }); - } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { @@ -55491,7 +56841,7 @@ var ts; for (var helper = 1 /* FirstEmitHelper */; helper <= 65536 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67216319 /* Value */); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 67220415 /* Value */); if (!symbol) { error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); } @@ -55865,11 +57215,32 @@ var ts; } } } + function getNonSimpleParameters(parameters) { + return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); }); + } + function checkGrammarForUseStrictSimpleParameterList(node) { + if (languageVersion >= 3 /* ES2016 */) { + var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements); + if (useStrictDirective_1) { + var nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (ts.length(nonSimpleParameters)) { + ts.forEach(nonSimpleParameters, function (parameter) { + addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + }); + var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); + addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + return true; + } + } + } + return false; + } function checkGrammarFunctionLikeDeclaration(node) { // Prevent cascading error by short-circuit var file = ts.getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node) { var file = ts.getSourceFileOfNode(node); @@ -56047,6 +57418,9 @@ var ts; function checkGrammarForInvalidQuestionMark(questionToken, message) { return !!questionToken && grammarErrorOnNode(questionToken, message); } + function checkGrammarForInvalidExclamationToken(exclamationToken, message) { + return !!exclamationToken && grammarErrorOnNode(exclamationToken, message); + } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; (function (Flags) { @@ -56090,8 +57464,10 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 273 /* PropertyAssignment */: case 274 /* ShorthandPropertyAssignment */: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case 273 /* PropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { @@ -56308,6 +57684,9 @@ var ts; else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); } @@ -56404,26 +57783,32 @@ var ts; expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } + function isSimpleLiteralEnumReference(expr) { + if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + ts.isEntityNameExpression(expr.expression)) + return !!(checkExpressionCached(expr).flags & 512 /* EnumLiteral */); + } + function checkAmbientInitializer(node) { + if (node.initializer) { + var isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === 101 /* TrueKeyword */ || node.initializer.kind === 86 /* FalseKeyword */); + var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + } + } + else { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + if (!isConstOrReadonly || isInvalidInitializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + } function checkGrammarVariableDeclaration(node) { if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { if (node.flags & 4194304 /* Ambient */) { - if (node.initializer) { - if (ts.isVarConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } + checkAmbientInitializer(node); } else if (!node.initializer) { if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { @@ -56563,10 +57948,11 @@ var ts; return false; } function checkGrammarConstructorTypeParameters(node) { - var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; - return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined; + var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters); + if (range) { + var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } function checkGrammarConstructorTypeAnnotation(node) { @@ -56597,8 +57983,8 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 4194304 /* Ambient */ && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + if (node.flags & 4194304 /* Ambient */) { + checkAmbientInitializer(node); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { @@ -60174,6 +61560,21 @@ var ts; return statementOffset; } ts.addCustomPrologue = addCustomPrologue; + function findUseStrictPrologue(statements) { + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + ts.findUseStrictPrologue = findUseStrictPrologue; function startsWithUseStrict(statements) { var firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -60187,19 +61588,7 @@ var ts; * @param statements An array of statements */ function ensureUseStrict(statements) { - var foundUseStrict = false; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (ts.isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + var foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return ts.setTextRange(ts.createNodeArray([ startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))) @@ -62824,8 +64213,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (524288 /* ContainsRest */ | 1048576 /* ContainsObjectRest */)) + && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -62891,7 +64280,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 1048576 /* ContainsObjectRest */) { + if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -63831,7 +65220,7 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */; var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. @@ -63879,9 +65268,11 @@ var ts; // Check if we have property assignment inside class declaration. // If there is a property assignment, we need to emit constructor whether users define it or not // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); - var hasParameterPropertyAssignments = node.transformFlags & 262144 /* ContainsParameterPropertyAssignments */; var constructor = ts.getFirstConstructorWithBody(node); + var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); + var hasParameterPropertyAssignments = constructor && + constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { @@ -65795,7 +67186,7 @@ var ts; * double-binding semantics for the class name. */ function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; @@ -65917,7 +67308,7 @@ var ts; } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 16777216 /* ConstructorReferenceInClass */) { + if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -66057,6 +67448,14 @@ var ts; */ var enclosingSuperContainerFlags = 0; var enclosingFunctionParameterNames; + /** + * Keeps track of property names accessed on super (`super.x`) within async functions. + */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors (variable statements). */ + var substitutedSuperAccessors = []; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -66090,6 +67489,16 @@ var ts; return visitFunctionExpression(node); case 195 /* ArrowFunction */: return visitArrowFunction(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66331,23 +67740,33 @@ var ts; var parameter = _a[_i]; recordDeclarationName(parameter, enclosingFunctionParameterNames); } + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.createBlock(statements, /*multiLine*/ true); - ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + var block = ts.createBlock(statements, /*multiLine*/ true); + ts.setTextRange(block, node.body); + if (emitSuperHelpers && hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -66365,6 +67784,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66400,6 +67821,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -66422,6 +67845,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -66450,13 +67881,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -66481,18 +67912,62 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } } ts.transformES2017 = transformES2017; + /** Creates a variable named `_super` with accessor properties for the given property names. */ + function createSuperAccessVariableStatement(resolver, node, names) { + // Create a variable declaration with a getter/setter (if binding) definition for each name: + // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0; + var accessors = []; + names.forEach(function (_, key) { + var name = ts.unescapeLeadingUnderscores(key); + var getterAndSetter = []; + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + if (hasBinding) { + getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( + /* modifiers */ undefined, + /* typeParameters */ undefined, + /* parameters */ [ + ts.createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "v", + /* questionToken */ undefined, + /* type */ undefined, + /* initializer */ undefined) + ], + /* type */ undefined, + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + } + accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); + }); + return ts.createVariableStatement( + /* modifiers */ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), + /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), + /* typeArguments */ undefined, [ + ts.createNull(), + ts.createObjectLiteral(accessors, /* multiline */ true) + ])) + ], 2 /* Const */)); + } + ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; var awaiterHelper = { name: "typescript:awaiter", scoped: false, @@ -66520,12 +67995,12 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_superIndex") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex") }; })(ts || (ts = {})); /*@internal*/ @@ -66548,6 +68023,12 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; + /** Keeps track of property names accessed on super (`super.x`) within async functions. */ + var capturedSuperProperties; + /** Whether the async function contains an element access on super (`super[x]`). */ + var hasSuperElementAccess; + /** A set of node IDs for generated super accessors. */ + var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -66616,6 +68097,16 @@ var ts; return visitParenthesizedExpression(node, noDestructuringValue); case 272 /* CatchClause */: return visitCatchClause(node); + case 187 /* PropertyAccessExpression */: + if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 97 /* SuperKeyword */) { + capturedSuperProperties.set(node.name.escapedText, true); + } + return ts.visitEachChild(node, visitor, context); + case 188 /* ElementAccessExpression */: + if (capturedSuperProperties && node.expression.kind === 97 /* SuperKeyword */) { + hasSuperElementAccess = true; + } + return ts.visitEachChild(node, visitor, context); default: return ts.visitEachChild(node, visitor, context); } @@ -66680,7 +68171,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 1048576 /* ContainsObjectSpread */) { + if (node.transformFlags & 262144 /* 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}); @@ -66712,7 +68203,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 26 /* CommaToken */) { @@ -66727,7 +68218,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 1048576 /* ContainsObjectRest */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -66744,7 +68235,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -66841,7 +68332,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 1048576 /* ContainsObjectRest */) { + if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -66938,25 +68429,37 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); appendObjectRestAssignmentsIfNeeded(statements, node); - statements.push(ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(39 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - var block = ts.updateBlock(node.body, statements); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= 2 /* ES2015 */) { + var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.addStatementsAfterPrologue(statements, [variableStatement]); + } + statements.push(returnStatement); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var block = ts.updateBlock(node.body, statements); + if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { - enableSubstitutionForAsyncMethodsWithSuper(); ts.addEmitHelper(block, ts.asyncSuperHelper); } } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return block; } function transformFunctionBody(node) { @@ -66980,7 +68483,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 1048576 /* ContainsObjectRest */) { + if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -67009,6 +68512,8 @@ var ts; context.enableEmitNotification(156 /* GetAccessor */); context.enableEmitNotification(157 /* SetAccessor */); context.enableEmitNotification(155 /* Constructor */); + // We need to be notified when entering the generated accessor arrow functions. + context.enableEmitNotification(217 /* VariableStatement */); } } /** @@ -67031,6 +68536,14 @@ var ts; return; } } + // Disable substitution in the generated super accessor itself. + else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) { + var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; + enclosingSuperContainerFlags = 0; + previousOnEmitNode(hint, node, emitCallback); + enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags; + return; + } previousOnEmitNode(hint, node, emitCallback); } /** @@ -67059,13 +68572,13 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(ts.idText(node.name)), node); + return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node); } return node; } function substituteElementAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(node.argumentExpression, node); + return createSuperElementAccessInAsyncMethod(node.argumentExpression, node); } return node; } @@ -67090,13 +68603,13 @@ var ts; || kind === 156 /* GetAccessor */ || kind === 157 /* SetAccessor */; } - function createSuperAccessInAsyncMethod(argumentExpression, location) { + function createSuperElementAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -67754,6 +69267,11 @@ var ts; /** Enables substitutions for block-scoped bindings. */ ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings"; })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {})); + var LoopOutParameterFlags; + (function (LoopOutParameterFlags) { + LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body"; + LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer"; + })(LoopOutParameterFlags || (LoopOutParameterFlags = {})); var CopyDirection; (function (CopyDirection) { CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal"; @@ -67934,7 +69452,7 @@ var ts; return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } function visitor(node) { @@ -68532,7 +70050,7 @@ var ts; // but only if the constructor itself doesn't use 'this' elsewhere. if (superCallExpression && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { + && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); if (superCallExpression.kind !== 202 /* BinaryExpression */ || superCallExpression.left.kind !== 189 /* CallExpression */) { @@ -68603,7 +70121,7 @@ var ts; * @param node A function-like node. */ function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 131072 /* ContainsDefaultValueAssignments */) !== 0; + return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -68732,7 +70250,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { + if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -68920,7 +70438,7 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 16384 /* ContainsLexicalThis */) { + if (node.transformFlags & 8192 /* ContainsLexicalThis */) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -69210,19 +70728,27 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 8388608 /* ContainsBindingPattern */ + // If the first or last declaration is a binding pattern, we need to modify + // the source map range for the declaration list. + if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { - // If the first or last declaration is a binding pattern, we need to modify - // the source map range for the declaration list. - var firstDeclaration = ts.firstOrUndefined(declarations); - if (firstDeclaration) { - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); - } + ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } return declarationList; } return ts.visitEachChild(node, visitor, context); } + function getRangeUnion(declarations) { + // declarations may not be sorted by position. + // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes. + var pos = -1, end = -1; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var node = declarations_10[_i]; + pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos); + end = Math.max(end, node.end); + } + return ts.createRange(pos, end); + } /** * Gets a value indicating whether we should emit an explicit initializer for a variable * declaration in a `let` declaration list. @@ -69270,8 +70796,8 @@ var ts; // * Why loop initializer is excluded? // - Since we've introduced a fresh name it already will be undefined. var flags = resolver.getNodeCheckFlags(node); - var isCapturedInFunction = flags & 131072 /* CapturedBlockScopedBinding */; - var isDeclaredInLoop = flags & 262144 /* BlockScopedBindingInLoop */; + var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */; + var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */; var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || (isCapturedInFunction && isDeclaredInLoop @@ -69526,7 +71052,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 16777216 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -69557,7 +71083,23 @@ var ts; } return ts.visitEachChild(node, visitor, context); } - function shouldConvertIterationStatementBody(node) { + function shouldConvertPartOfIterationStatement(node) { + return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0; + } + function shouldConvertInitializerOfForStatement(node) { + return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); + } + function shouldConvertConditionOfForStatement(node) { + return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition); + } + function shouldConvertIncrementorOfForStatement(node) { + return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + } + function shouldConvertIterationStatement(node) { + return shouldConvertBodyOfIterationStatement(node) + || shouldConvertInitializerOfForStatement(node); + } + function shouldConvertBodyOfIterationStatement(node) { return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0; } /** @@ -69583,7 +71125,7 @@ var ts; } } function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, convert) { - if (!shouldConvertIterationStatementBody(node)) { + if (!shouldConvertIterationStatement(node)) { var saveAllowedNonLabeledJumps = void 0; if (convertedLoopState) { // we get here if we are trying to emit normal loop loop inside converted loop @@ -69599,7 +71141,69 @@ var ts; } return result; } - var functionName = ts.createUniqueName("_loop"); + var currentState = createConvertedLoopState(node); + var statements = []; + var outerConvertedLoopState = convertedLoopState; + convertedLoopState = currentState; + var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined; + var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined; + convertedLoopState = outerConvertedLoopState; + if (initializerFunction) + statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) + statements.push(bodyFunction.functionDeclaration); + addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); + if (initializerFunction) { + statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); + } + var loop; + if (bodyFunction) { + if (convert) { + loop = convert(node, outermostLabeledStatement, bodyFunction.part); + } + else { + var clone_3 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true)); + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + } + } + else { + var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + ts.aggregateTransformFlags(clone_4); + loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + } + statements.push(loop); + return statements; + } + function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) { + switch (node.kind) { + case 223 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody); + case 224 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody); + case 225 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody); + case 221 /* DoStatement */: return convertDoStatement(node, convertedLoopBody); + case 222 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody); + default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected"); + } + } + function convertForStatement(node, initializerFunction, convertedLoopBody) { + var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition); + var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor); + return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody); + } + function convertForOfStatement(node, convertedLoopBody) { + return ts.updateForOf(node, + /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertForInStatement(node, convertedLoopBody) { + return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function convertDoStatement(node, convertedLoopBody) { + return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression)); + } + function convertWhileStatement(node, convertedLoopBody) { + return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody); + } + function createConvertedLoopState(node) { var loopInitializer; switch (node.kind) { case 223 /* ForStatement */: @@ -69616,165 +71220,276 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { + var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(decl, loopParameters, loopOutParameters); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } - var outerConvertedLoopState = convertedLoopState; - convertedLoopState = { loopOutParameters: loopOutParameters }; - if (outerConvertedLoopState) { + var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; + if (convertedLoopState) { // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop. // if outer converted loop has already accumulated some state - pass it through - if (outerConvertedLoopState.argumentsName) { + if (convertedLoopState.argumentsName) { // outer loop has already used 'arguments' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.argumentsName = outerConvertedLoopState.argumentsName; + currentState.argumentsName = convertedLoopState.argumentsName; } - if (outerConvertedLoopState.thisName) { + if (convertedLoopState.thisName) { // outer loop has already used 'this' so we've already have some name to alias it // use the same name in all nested loops - convertedLoopState.thisName = outerConvertedLoopState.thisName; + currentState.thisName = convertedLoopState.thisName; } - if (outerConvertedLoopState.hoistedLocalVariables) { + if (convertedLoopState.hoistedLocalVariables) { // we've already collected some non-block scoped variable declarations in enclosing loop // use the same storage in nested loop - convertedLoopState.hoistedLocalVariables = outerConvertedLoopState.hoistedLocalVariables; + currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables; } } - startLexicalEnvironment(); - var loopBody = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); - var lexicalEnvironment = endLexicalEnvironment(); - var currentState = convertedLoopState; - convertedLoopState = outerConvertedLoopState; - if (loopOutParameters.length || lexicalEnvironment) { - var statements_4 = ts.isBlock(loopBody) ? loopBody.statements.slice() : [loopBody]; - if (loopOutParameters.length) { - copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); - } - ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); - loopBody = ts.createBlock(statements_4, /*multiline*/ true); - } - if (ts.isBlock(loopBody)) { - loopBody.multiLine = true; - } - else { - loopBody = ts.createBlock([loopBody], /*multiline*/ true); - } - var containsYield = (node.statement.transformFlags & 16777216 /* ContainsYield */) !== 0; - var isAsyncBlockContainingAwait = containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0; - var loopBodyFlags = 0; - if (currentState.containsLexicalThis) { - loopBodyFlags |= 8 /* CapturesThis */; - } - if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 262144 /* AsyncFunctionBody */; - } - var convertedLoopVariable = ts.createVariableStatement( - /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, - /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( - /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, loopParameters, - /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 2097152 /* NoHoisting */)); - var statements = [convertedLoopVariable]; + return currentState; + } + function addExtraDeclarationsForConvertedLoop(statements, state, outerState) { var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary - if (currentState.argumentsName) { + if (state.argumentsName) { // if alias for arguments is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.argumentsName = currentState.argumentsName; + outerState.argumentsName = state.argumentsName; } else { // this is top level converted loop and we need to create an alias for 'arguments' object - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.argumentsName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, /*type*/ undefined, ts.createIdentifier("arguments"))); } } - if (currentState.thisName) { + if (state.thisName) { // if alias for this is set - if (outerConvertedLoopState) { + if (outerState) { // pass it to outer converted loop - outerConvertedLoopState.thisName = currentState.thisName; + outerState.thisName = state.thisName; } else { // this is top level converted loop so we need to create an alias for 'this' here // NOTE: // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set. // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'. - (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(currentState.thisName, + (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, /*type*/ undefined, ts.createIdentifier("this"))); } } - if (currentState.hoistedLocalVariables) { + if (state.hoistedLocalVariables) { // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later - if (outerConvertedLoopState) { + if (outerState) { // pass them to outer converted loop - outerConvertedLoopState.hoistedLocalVariables = currentState.hoistedLocalVariables; + outerState.hoistedLocalVariables = state.hoistedLocalVariables; } else { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } // hoist collected variable declarations - for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { - var identifier = _c[_b]; + for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) { + var identifier = _a[_i]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } } // add extra variables to hold out parameters if necessary - if (loopOutParameters.length) { + if (state.loopOutParameters.length) { if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { - var outParam = loopOutParameters_1[_d]; + for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) { + var outParam = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } + if (state.conditionVariable) { + if (!extraVariableDeclarations) { + extraVariableDeclarations = []; + } + extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse())); + } // create variable statement to hold all introduced variable declarations if (extraVariableDeclarations) { statements.push(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations))); } - var convertedLoopBodyStatements = generateCallToConvertedLoop(functionName, loopParameters, currentState, containsYield); - var loop; - if (convert) { - loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); + } + function createOutVariable(p) { + return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName); + } + /** + * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer + * that is captured in a closure inside of the initializer. The `_loop_init` function is + * used to preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForInitializerOfForStatement(node, currentState) { + var functionName = ts.createUniqueName("_loop_init"); + var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0 /* None */; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) + emitFlags |= 262144 /* AsyncFunctionBody */; + var statements = []; + statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer)); + copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements); + // This transforms the following ES2015 syntax: + // + // for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_init_1 = function () { + // var i = (setImmediate(() => console.log(i)), 0); + // out_i_1 = i; + // }; + // var out_i_1; + // _loop_init_1(); + // for (var i = out_i_1; i < 2; i++) { + // // loop body + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the initial value for `i` outside of the per-iteration environment. + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable)); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; + } + /** + * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer + * that is captured in a closure inside of the loop body. The `_loop` function is used to + * preserve the per-iteration environment semantics of + * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation). + */ + function createFunctionForBodyOfIterationStatement(node, currentState, outerState) { + var functionName = ts.createUniqueName("_loop"); + startLexicalEnvironment(); + var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); + var lexicalEnvironment = endLexicalEnvironment(); + var statements = []; + if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) { + // If a block-scoped variable declared in the initializer of `node` is captured in + // the condition or incrementor, we must move the condition and incrementor into + // the body of the for loop. + // + // This transforms the following ES2015 syntax: + // + // for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) { + // // loop body + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // if (inc_1) + // setImmediate(() => console.log(i)), i++; + // else + // inc_1 = true; + // if (!(setImmediate(() => console.log(i)), i < 2)) + // return out_i_1 = i, "break"; + // // loop body + // out_i_1 = i; + // } + // var out_i_1, inc_1 = false; + // for (var i = 0;;) { + // var state_1 = _loop_1(i); + // i = out_i_1; + // if (state_1 === "break") + // break; + // } + // + // Which prevents mutations to `i` in the per-iteration environment of the body + // from affecting the value of `i` in the previous per-iteration environment. + // + // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration + // environment that is carried over to the next iteration of the loop. As a result, + // we must indicate whether this is the first evaluation of the loop body so that + // we only evaluate the incrementor on subsequent evaluations. + currentState.conditionVariable = ts.createUniqueName("inc"); + statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue())))); + if (shouldConvertConditionOfForStatement(node)) { + statements.push(ts.createIf(ts.createPrefix(51 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement))); + } + } + if (ts.isBlock(statement)) { + ts.addRange(statements, statement.statements); } else { - var clone_3 = ts.getMutableClone(node); - // clean statement part - clone_3.statement = undefined; - // visit childnodes to transform initializer/condition/incrementor parts - clone_3 = ts.visitEachChild(clone_3, visitor, context); - // set loop statement - clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); - // reset and re-aggregate the transform flags - clone_3.transformFlags = 0; - ts.aggregateTransformFlags(clone_3); - loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); + statements.push(statement); } - statements.push(loop); - return statements; + copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + var loopBody = ts.createBlock(statements, /*multiLine*/ true); + if (ts.isBlock(statement)) + ts.setOriginalNode(loopBody, statement); + var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var emitFlags = 0; + if (currentState.containsLexicalThis) + emitFlags |= 8 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) + emitFlags |= 262144 /* AsyncFunctionBody */; + // This transforms the following ES2015 syntax (in addition to other variations): + // + // for (let i = 0; i < 2; i++) { + // setImmediate(() => console.log(i)); + // } + // + // Into the following ES5 syntax: + // + // var _loop_1 = function (i) { + // setImmediate(() => console.log(i)); + // }; + // for (var i = 0; i < 2; i++) { + // _loop_1(i); + // } + var functionDeclaration = ts.createVariableStatement( + /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ + ts.createVariableDeclaration(functionName, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression( + /*modifiers*/ undefined, containsYield ? ts.createToken(39 /* AsteriskToken */) : undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, currentState.loopParameters, + /*type*/ undefined, loopBody), emitFlags)) + ]), 2097152 /* NoHoisting */)); + var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield); + return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part }; } function copyOutParameter(outParam, copyDirection) { var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName; var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName; return ts.createBinary(target, 58 /* EqualsToken */, source); } - function copyOutParameters(outParams, copyDirection, statements) { + function copyOutParameters(outParams, partFlags, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + if (outParam.flags & partFlags) { + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); + } } } - function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { - var outerConvertedLoopState = convertedLoopState; + function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) { + var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []); + var callResult = containsYield + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) + : call; + return ts.createStatement(callResult); + } + function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) { var statements = []; // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop // simple loops are emitted as just 'loop()'; @@ -69782,24 +71497,24 @@ var ts; var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) && !state.labeledNonLocalBreaks && !state.labeledNonLocalContinues; - var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); - var callResult = isAsyncBlockContainingAwait + var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; })); + var callResult = containsYield ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createExpressionStatement(callResult)); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); } else { var loopResultName = ts.createUniqueName("state"); var stateVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)])); statements.push(stateVariable); - copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); + copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements); if (state.nonLocalJumps & 8 /* Return */) { var returnStatement = void 0; - if (outerConvertedLoopState) { - outerConvertedLoopState.nonLocalJumps |= 8 /* Return */; + if (outerState) { + outerState.nonLocalJumps |= 8 /* Return */; returnStatement = ts.createReturn(loopResultName); } else { @@ -69812,8 +71527,8 @@ var ts; } if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) { var caseClauses = []; - processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerConvertedLoopState, caseClauses); - processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerConvertedLoopState, caseClauses); + processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses); + processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses); statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses))); } } @@ -69853,21 +71568,29 @@ var ts; caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(decl, loopParameters, loopOutParameters) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(element, loopParameters, loopOutParameters); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); } } } else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); - if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { + var checkFlags = resolver.getNodeCheckFlags(decl); + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { var outParamName = ts.createUniqueName("out_" + ts.idText(name)); - loopOutParameters.push({ originalName: name, outParamName: outParamName }); + var flags = 0; + if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { + flags |= 1 /* Body */; + } + if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } } } @@ -70007,7 +71730,7 @@ var ts; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) ? transformFunctionBody(node) : visitFunctionBodyDownLevel(node); if (node.kind === 156 /* GetAccessor */) { @@ -70186,7 +71909,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 524288 /* ContainsSpread */ || + if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || node.expression.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -70194,7 +71917,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -70241,7 +71964,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 524288 /* ContainsSpread */) { + if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -70723,7 +72446,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -71148,10 +72871,10 @@ var ts; case 228 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 33554432 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -71354,7 +73077,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 16777216 /* ContainsYield */) { + if (node.transformFlags & 4194304 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -71478,10 +73201,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_4 = ts.getMutableClone(node); - clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_4; + var clone_5 = ts.getMutableClone(node); + clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -71742,10 +73465,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_5 = ts.getMutableClone(node); - clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_5; + var clone_6 = ts.getMutableClone(node); + clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_6; } return ts.visitEachChild(node, visitor, context); } @@ -72412,7 +74135,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -72444,10 +74167,10 @@ var ts; if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_6 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_6, node); - ts.setCommentRange(clone_6, node); - return clone_6; + var clone_7 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); + return clone_7; } } } @@ -73529,7 +75252,10 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || + !(ts.isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & 16777216 /* ContainsDynamicImport */ || + (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } currentSourceFile = node; @@ -73583,6 +75309,7 @@ var ts; function transformAMDModule(node) { var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); + var jsonSourceFile = ts.isJsonSourceFile(node) && node; // An AMD define function has the following shape: // // define(id?, dependencies?, factory); @@ -73613,22 +75340,24 @@ var ts; // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - ts.createArrayLiteral([ + ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : [ ts.createLiteral("require"), ts.createLiteral("exports") ].concat(aliasedModuleNames, unaliasedModuleNames)), // Add the module body function argument: // // function (require, exports, module1, module2) ... - ts.createFunctionExpression( - /*modifiers*/ undefined, - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, [ - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), - ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") - ].concat(importAliasNames), - /*type*/ undefined, transformAsynchronousModuleBody(node)) + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() : + ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"), + ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports") + ].concat(importAliasNames), + /*type*/ undefined, transformAsynchronousModuleBody(node)) ]))) ]), /*location*/ node.statements)); @@ -73862,7 +75591,7 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { @@ -73929,7 +75658,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -74894,7 +76623,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -75979,7 +77708,7 @@ var ts; else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -76786,7 +78515,7 @@ var ts; // Heritage clause is written by user so it can always be named if (node.parent.parent.kind === 238 /* ClassDeclaration */) { // Class or Interface implemented/extended is inaccessible - diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 108 /* ImplementsKeyword */ ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; } @@ -76821,11 +78550,11 @@ var ts; var ts; (function (ts) { function getDeclarationDiagnostics(host, resolver, file) { - if (file && ts.isSourceFileJavaScript(file)) { + if (file && ts.isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } var compilerOptions = host.getCompilerOptions(); - var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; @@ -76851,7 +78580,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +78598,7 @@ var ts; var errorNameNode; var currentSourceFile; var refs; + var libs; var resolver = context.getEmitResolver(); var options = context.getCompilerOptions(); var newLine = ts.getNewLineCharacter(options); @@ -76878,10 +78608,10 @@ var ts; if (!typeReferenceDirectives) { return; } - necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + necessaryTypeReferences = necessaryTypeReferences || ts.createMap(); for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { var ref = typeReferenceDirectives_2[_i]; - necessaryTypeRefernces.set(ref, true); + necessaryTypeReferences.set(ref, true); } } function trackReferencedAmbientModule(node, symbol) { @@ -76950,15 +78680,16 @@ var ts; } } function transformRoot(node) { - if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } if (node.kind === 278 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); + libs = ts.createMap(); var hasNoDefaultLib_1 = false; var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { - if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + if (sourceFile.isDeclarationFile || ts.isSourceFileJS(sourceFile)) return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; @@ -76970,11 +78701,12 @@ var ts; needsScopeFixMarker = false; resultHasScopeMarker = false; collectReferences(sourceFile, refs); + collectLibs(sourceFile, libs); if (ts.isExternalModule(sourceFile)) { resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) needsDeclare = false; - var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); - var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + var statements_4 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_4)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); return newFile; } needsDeclare = true; @@ -76987,6 +78719,7 @@ var ts; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.syntheticLibReferences = getLibReferences(); bundle.hasNoDefaultLib = hasNoDefaultLib_1; var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); @@ -77005,8 +78738,9 @@ var ts; suppressNewDiagnosticContexts = false; lateMarkedStatements = undefined; lateStatementReplacementMap = ts.createMap(); - necessaryTypeRefernces = undefined; + necessaryTypeReferences = undefined; refs = collectReferences(currentSourceFile, ts.createMap()); + libs = collectLibs(currentSourceFile, ts.createMap()); var references = []; var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); @@ -77017,11 +78751,14 @@ var ts; if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); } - var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences()); updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit; return updated; + function getLibReferences() { + return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); }); + } function getFileReferencesForUsedTypeReferences() { - return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : []; } function getFileReferenceForTypeName(typeName) { // Elide type references for which we have imports @@ -77051,7 +78788,7 @@ var ts; if (isBundledEmit && ts.contains(node.sourceFiles, file)) return; // Omit references to files which are being merged var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); - declFileName = paths.declarationFilePath || paths.jsFilePath; + declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -77059,13 +78796,18 @@ var ts; if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { fileName = fileName.substring(2); } + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } references.push({ pos: -1, end: -1, fileName: fileName }); } }; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + if (noResolve || ts.isSourceFileJS(sourceFile)) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -77075,6 +78817,15 @@ var ts; }); return ret; } + function collectLibs(sourceFile, ret) { + ts.forEach(sourceFile.libReferenceDirectives, function (ref) { + var lib = host.getLibFileFromReference(ref); + if (lib) { + ret.set(ref.fileName.toLocaleLowerCase(), true); + } + }); + return ret; + } function filterBindingPatternInitializers(name) { if (name.kind === 71 /* Identifier */) { return name; @@ -77591,10 +79342,25 @@ var ts; } case 237 /* FunctionDeclaration */: { // Generators lose their generator-ness, excepting their return type - return cleanup(ts.updateFunctionDeclaration(input, + var clean = cleanup(ts.updateFunctionDeclaration(input, /*decorators*/ undefined, ensureModifiers(input, isPrivate), /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), /*body*/ undefined)); + if (clean && resolver.isExpandoFunctionDeclaration(input)) { + var declarations = ts.mapDefined(resolver.getPropertiesOfContainerFunction(input), function (p) { + if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { + return undefined; + } + var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); + }); + var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */); + return [clean, namespaceDecl]; + } + else { + return clean; + } } case 242 /* ModuleDeclaration */: { needsDeclare = false; @@ -77817,7 +79583,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_8 = function (range) { + var _loop_9 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -77831,7 +79597,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_8(range); + _loop_9(range); } } return prop; @@ -77878,10 +79644,11 @@ var ts; } function canHaveLiteralInitializer(node) { switch (node.kind) { - case 235 /* VariableDeclaration */: case 152 /* PropertyDeclaration */: case 151 /* PropertySignature */: + return !ts.hasModifier(node, 8 /* Private */); case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return true; } return false; @@ -79113,20 +80880,25 @@ var ts; function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); if (sourceFile.kind === 278 /* Bundle */) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var outPath = options.outFile || options.out; + var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; + var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; } else { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it + var isJsonEmittedToSameLocation = ts.isJsonSourceFile(sourceFile) && + ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath; + var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - var isJs = ts.isSourceFileJavaScript(sourceFile); + var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; - var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; } } @@ -79149,7 +80921,7 @@ var ts; return ".json" /* Json */; } if (options.jsx === 1 /* Preserve */) { - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { return ".jsx" /* Jsx */; } @@ -79198,26 +80970,31 @@ var ts; emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { - emittedFilesList.push(jsFilePath); - } - if (sourceMapFilePath) { - emittedFilesList.push(sourceMapFilePath); + if (jsFilePath) { + emittedFilesList.push(jsFilePath); + } + if (sourceMapFilePath) { + emittedFilesList.push(sourceMapFilePath); + } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (declarationMapPath) { + emittedFilesList.push(declarationMapPath); } } } function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - // Make sure not to write js file and source map file if any of them cannot be written - if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { - emitSkipped = true; + if (emitOnlyDtsFiles || !jsFilePath) { return; } - if (emitOnlyDtsFiles) { + // Make sure not to write js file and source map file if any of them cannot be written + if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) { + emitSkipped = true; return; } // Transform the source files @@ -79242,12 +81019,12 @@ var ts; transform.dispose(); } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJS); var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. @@ -79976,7 +81753,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79998,7 +81775,7 @@ var ts; // SyntaxKind.TemplateMiddle // SyntaxKind.TemplateTail function emitLiteral(node) { - var text = getLiteralTextOfNode(node); + var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writeLiteral(text); @@ -80423,7 +82200,7 @@ var ts; expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - var text = getLiteralTextOfNode(expression); + var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(23 /* DotToken */)); } @@ -80634,7 +82411,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - if (!ts.isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) { writeSemicolon(); } } @@ -81337,13 +83116,13 @@ var ts; emitSourceFileWorker(node); } function emitSyntheticTripleSlashReferencesIfNeeded(node) { - emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } - function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) { if (hasNoDefaultLib) { write("/// "); writeLine(); @@ -81369,11 +83148,16 @@ var ts; write("/// "); writeLine(); } - for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { - var directive = types_17[_d]; + for (var _d = 0, types_16 = types; _d < types_16.length; _d++) { + var directive = types_16[_d]; write("/// "); writeLine(); } + for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { + var directive = libs_1[_e]; + write("/// "); + writeLine(); + } } function emitSourceFileWorker(node) { var statements = node.statements; @@ -81538,7 +83322,8 @@ var ts; var parameter = ts.singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !ts.some(parentNode.decorators) // parent may not have decorators && !ts.some(parentNode.modifiers) // parent may not have modifiers && !ts.some(parentNode.typeParameters) // parent may not have type parameters @@ -81959,19 +83744,19 @@ var ts; } return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node) { + function getLiteralTextOfNode(node, neverAsciiEscape) { if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode)) { - return ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? + return neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" : "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\""; } else { - return getLiteralTextOfNode(textSourceNode); + return getLiteralTextOfNode(textSourceNode, neverAsciiEscape); } } - return ts.getLiteralText(node, currentSourceFile); + return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape); } /** * Push a new name generation scope. @@ -82150,7 +83935,7 @@ var ts; if (node.locals) { var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { + if (local && local.flags & (67220415 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -82229,7 +84014,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82743,17 +84528,24 @@ var ts; } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; function createCompilerHost(options, setParentNodes) { + return createCompilerHostWorker(options, setParentNodes); + } + ts.createCompilerHost = createCompilerHost; + /*@internal*/ + // TODO(shkamat): update this after reworking ts build API + function createCompilerHostWorker(options, setParentNodes, system) { + if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); } function getSourceFile(fileName, languageVersion, onError) { var text; try { ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); + text = system.readFile(fileName, options.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -82769,7 +84561,7 @@ var ts; if (existingDirectories.has(directoryPath)) { return true; } - if (ts.sys.directoryExists(directoryPath)) { + if (system.directoryExists(directoryPath)) { existingDirectories.set(directoryPath, true); return true; } @@ -82779,7 +84571,7 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); + system.createDirectory(directoryPath); } } var outputFingerprints; @@ -82787,8 +84579,8 @@ var ts; if (!outputFingerprints) { outputFingerprints = ts.createMap(); } - var hash = ts.sys.createHash(data); // TODO: GH#18217 - var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + var hash = system.createHash(data); // TODO: GH#18217 + var mtimeBefore = system.getModifiedTime(fileName); // TODO: GH#18217 if (mtimeBefore) { var fingerprint = outputFingerprints.get(fileName); // If output has not been changed, and the file has no external modification @@ -82799,8 +84591,8 @@ var ts; return; } } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 + system.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime; // TODO: GH#18217 outputFingerprints.set(fileName, { hash: hash, byteOrderMark: writeByteOrderMark, @@ -82811,11 +84603,11 @@ var ts; try { ts.performance.mark("beforeIOWrite"); ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + if (ts.isWatchSet(options) && system.createHash && system.getModifiedTime) { writeFileIfUpdated(fileName, data, writeByteOrderMark); } else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); + system.writeFile(fileName, data, writeByteOrderMark); } ts.performance.mark("afterIOWrite"); ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); @@ -82827,36 +84619,33 @@ var ts; } } function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); + var realpath = system.realpath && (function (path) { return system.realpath(path); }); return { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, + fileExists: function (fileName) { return system.fileExists(fileName); }, + readFile: function (fileName) { return system.readFile(fileName); }, + trace: function (s) { return system.write(s + newLine); }, + directoryExists: function (directoryName) { return system.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, - getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), - setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), - deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } }; } - ts.createCompilerHost = createCompilerHost; + ts.createCompilerHostWorker = createCompilerHostWorker; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { + if (ts.getEmitDeclarations(program.getCompilerOptions())) { ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } return ts.sortAndDeduplicateDiagnostics(diagnostics); @@ -82864,8 +84653,8 @@ var ts; ts.getPreEmitDiagnostics = getPreEmitDiagnostics; function formatDiagnostics(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; output += formatDiagnostic(diagnostic, host); } return output; @@ -82891,7 +84680,7 @@ var ts; ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; + var gutterStyleSequence = "\u001b[7m"; var gutterSeparator = " "; var resetEscapeSequence = "\u001b[0m"; var ellipsis = "..."; @@ -82979,8 +84768,8 @@ var ts; ts.formatLocation = formatLocation; function formatDiagnosticsWithColorAndContext(diagnostics, host) { var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; + for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { + var diagnostic = diagnostics_3[_i]; if (diagnostic.file) { var file = diagnostic.file, start = diagnostic.start; output += formatLocation(file, start, host); // TODO: GH#18217 @@ -82995,11 +84784,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_4 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_4, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -83057,7 +84846,7 @@ var ts; * Determines if program structure is upto date or needs to be recreated */ /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -83066,6 +84855,10 @@ var ts; if (program.getRootFileNames().length !== rootFileNames.length) { return false; } + // If project references dont match + if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { + return false; + } // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -83086,8 +84879,24 @@ var ts; } return true; function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); + return !sourceFileVersionUptoDate(sourceFile) || + hasInvalidatedResolution(sourceFile.resolvedPath); + } + function sourceFileVersionUptoDate(sourceFile) { + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + } + function projectReferenceUptoDate(oldRef, newRef, index) { + if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { + return false; + } + var oldResolvedRef = program.getResolvedProjectReferences()[index]; + if (oldResolvedRef) { + // If sourceFile for the oldResolvedRef existed, check the version for uptodate + return sourceFileVersionUptoDate(oldResolvedRef.sourceFile); + } + // In old program, not able to resolve project reference path, + // so if config file doesnt exist, it is uptodate. + return !fileExists(resolveProjectReferencePath(oldRef)); } } ts.isProgramUptoDate = isProgramUptoDate; @@ -83097,21 +84906,17 @@ var ts; } ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; /** - * Determined if source file needs to be re-created even if its text hasn't changed + * Determine if source file needs to be re-created even if its text hasn't changed */ function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + if (!program) + return false; + // If any compiler options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`. + var oldOptions = program.getCompilerOptions(); + return !!ts.sourceFileAffectingCompilerOptions.some(function (option) { + return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option)); + }); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { return { @@ -83162,7 +84967,7 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); // Map storing if there is emit blocking diagnostics for given input var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; @@ -83209,7 +85014,7 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files var resolvedProjectReferences = projectReferences ? [] : undefined; - var projectReferenceRedirects = ts.createMap(); + var projectReferenceRedirects; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { @@ -83221,11 +85026,12 @@ var ts; var parsedRef = parseProjectReferenceConfigFile(ref); resolvedProjectReferences.push(parsedRef); if (parsedRef) { - if (parsedRef.commandLine.options.outFile) { - var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + var dtsOutfile = ts.changeExtension(out, ".d.ts"); processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } - addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + addProjectReferenceRedirects(parsedRef.commandLine); } } } @@ -83312,7 +85118,9 @@ var ts; isEmittedFile: isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences: getProjectReferences + getProjectReferences: getProjectReferences, + getResolvedProjectReferences: getResolvedProjectReferences, + getProjectReferenceRedirect: getProjectReferenceRedirect }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -83346,9 +85154,9 @@ var ts; // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); } - else if (options.composite) { + else if (options.composite && options.configFilePath) { // Project compilations never infer their root from the input source paths - commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); } else { @@ -83391,13 +85199,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_4 = []; + var result_5 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_4.push(resolvedModule); + result_5.push(resolvedModule); } - return result_4; + return result_5; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -83482,8 +85290,11 @@ var ts; // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + if (!oldProgramState.program) { + return false; + } var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + var resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -83491,15 +85302,8 @@ var ts; // because the normal module resolution algorithm will find this anyway. return false; } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + var firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find(function (f) { return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && ts.contains(f.ambientModuleNames, moduleName); }); if (!firstUnmodifiedFile) { return false; } @@ -83529,15 +85333,20 @@ var ts; return oldProgram.structureIsReused = 0 /* Not */; } // Check if any referenced project tsconfig files are different - var oldRefs = oldProgram.getProjectReferences(); + // If array of references is changed, we cant resue old program + var oldProjectReferences = oldProgram.getProjectReferences(); + if (!ts.arrayIsEqualTo(oldProjectReferences, projectReferences, ts.projectReferenceIsEqualTo)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check the json files for the project references + var oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be array if projectReferences provided are array + ts.Debug.assert(!!oldRefs); for (var i = 0; i < projectReferences.length; i++) { var oldRef = oldRefs[i]; + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - var newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = 0 /* Not */; @@ -83545,16 +85354,15 @@ var ts; } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = 0 /* Not */; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = 0 /* Not */; - } + // Resolved project referenced should be undefined if projectReferences is undefined + ts.Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -83577,7 +85385,7 @@ var ts; for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { var oldSourceFile = oldSourceFiles_2[_i]; var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 if (!newSourceFile) { return oldProgram.structureIsReused = 0 /* Not */; @@ -83604,7 +85412,11 @@ var ts; else { fileChanged = newSourceFile !== oldSourceFile; } + // Since the project references havent changed, its right to set originalFileName and resolvedPath here newSourceFile.path = oldSourceFile.path; + newSourceFile.originalFileName = oldSourceFile.originalFileName; + newSourceFile.resolvedPath = oldSourceFile.resolvedPath; + newSourceFile.fileName = oldSourceFile.fileName; filePaths.push(newSourceFile.path); var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { @@ -83670,7 +85482,7 @@ var ts; // try to verify results of module resolution for (var _a = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _a < modifiedSourceFiles_1.length; _a++) { var _b = modifiedSourceFiles_1[_a], oldSourceFile = _b.oldFile, newSourceFile = _b.newFile; - var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); + var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { var moduleNames = getModuleNames(newSourceFile); var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; @@ -83686,7 +85498,8 @@ var ts; } } if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); @@ -83721,14 +85534,21 @@ var ts; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); + if (resolvedProjectReferences) { + resolvedProjectReferences.forEach(function (ref) { + if (ref) { + addProjectReferenceRedirects(ref.commandLine); + } + }); + } sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -83739,11 +85559,12 @@ var ts; return host.fileExists(f); } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); } - function getProjectReferences() { - if (!resolvedProjectReferences) - return; + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } function getPrependNodes() { if (!projectReferences) { return ts.emptyArray; @@ -83753,12 +85574,13 @@ var ts; var ref = projectReferences[i]; var resolvedRefOpts = resolvedProjectReferences[i].commandLine; if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!resolvedRefOpts.options.outFile) + if (!out) continue; - var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); - var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; - var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var dtsFilename = ts.changeExtension(out, ".d.ts"); + var js = host.readFile(out) || "/* Input file " + out + " was missing */\r\n"; + var jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file var jsMap = host.readFile(jsMapPath); var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; var dtsMapPath = dtsFilename + ".map"; @@ -83815,7 +85637,7 @@ var ts; // get any preEmit diagnostics, not just the ones if (options.noEmitOnError) { var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) { declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); } if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { @@ -83881,9 +85703,9 @@ var ts; function getSyntacticDiagnosticsForFile(sourceFile) { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -83972,7 +85794,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -84201,7 +86023,7 @@ var ts; if (file.imports) { return; } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isJavaScriptFile = ts.isSourceFileJS(file); var isExternalModuleFile = ts.isExternalModule(file); // file.imports may not be undefined if there exists dynamic import var imports; @@ -84309,7 +86131,7 @@ var ts; } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { if (fail) fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return undefined; @@ -84365,11 +86187,14 @@ var ts; fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); } } - function createRedirectSourceFile(redirectTarget, unredirected, fileName, path) { + function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) { var redirect = Object.create(redirectTarget); redirect.fileName = fileName; redirect.path = path; + redirect.resolvedPath = resolvedPath; + redirect.originalFileName = originalFileName; redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected }; + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); Object.defineProperties(redirect, { id: { get: function () { return this.redirectInfo.redirectTarget.id; }, @@ -84384,6 +86209,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId) { + var originalFileName = fileName; if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path @@ -84449,7 +86275,7 @@ var ts; if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. // Instead of creating a duplicate, just redirect to the existing one. - var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); // TODO: GH#18217 + var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217 redirectTargetsMap.add(fileFromPackageId.path, fileName); filesByName.set(path, dupFile); sourceFileToPackageName.set(path, packageId.name); @@ -84470,6 +86296,7 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; file.resolvedPath = toPath(fileName); + file.originalFileName = originalFileName; if (host.useCaseSensitiveFileNames()) { var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case @@ -84499,24 +86326,26 @@ var ts; return file; } function getProjectReferenceRedirect(fileName) { - var path = toPath(fileName); + // Ignore dts or any of the non ts files + if (!projectReferenceRedirects || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || !ts.fileExtensionIsOneOf(fileName, ts.supportedTSExtensions)) { + return undefined; + } // If this file is produced by a referenced project, we need to rewrite it to // look in the output folder of the referenced project rather than the input - var normalized = ts.getNormalizedAbsolutePath(fileName, path); - var result; - projectReferenceRedirects.forEach(function (v, k) { - if (result !== undefined) { + return ts.forEach(projectReferenceRedirects, function (referencedProject) { + // not input file from the referenced project, ignore + if (!ts.contains(referencedProject.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + var out = referencedProject.options.outFile || referencedProject.options.out; + return out ? + ts.changeExtension(out, ".d.ts" /* Dts */) : + ts.getOutputDeclarationFileName(fileName, referencedProject); }); - return result; } function processReferencedFiles(file, isDefaultLib) { ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName); processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); }); } @@ -84526,7 +86355,7 @@ var ts; if (!typeDirectives) { return; } - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName); for (var i = 0; i < typeDirectives.length; i++) { var ref = file.typeReferenceDirectives[i]; var resolvedTypeReferenceDirective = resolutions[i]; @@ -84613,7 +86442,7 @@ var ts; // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. var moduleNames = getModuleNames(file); var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); ts.Debug.assert(resolutions.length === moduleNames.length); for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; @@ -84622,7 +86451,7 @@ var ts; continue; } var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension); var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; var resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -84642,7 +86471,7 @@ var ts; && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); if (elideImport) { modulesWithElidedImports.set(file.path, true); } @@ -84662,27 +86491,19 @@ var ts; } } function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } + var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; }); return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); } function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); - allFilesBelongToPath = false; - } + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; } } } @@ -84690,7 +86511,7 @@ var ts; } function parseProjectReferenceConfigFile(ref) { // The actual filename (i.e. add "/tsconfig.json" if necessary) - var refPath = resolveProjectReferencePath(host, ref); + var refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); @@ -84701,22 +86522,16 @@ var ts; var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); return { commandLine: commandLine, sourceFile: sourceFile }; } - function addProjectReferenceRedirects(referencedProject, target) { - var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 - target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); - } - function getDeclarationOutputDirectory(proj) { - return proj.options.declarationDir || - proj.options.outDir || - ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + function addProjectReferenceRedirects(referencedProject) { + (projectReferenceRedirects || (projectReferenceRedirects = [])).push(referencedProject); } function verifyCompilerOptions() { if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); } if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + if (ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, getEmitDeclarationOptionName(options), "isolatedModules"); } if (options.noEmitOnError) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); @@ -84756,9 +86571,10 @@ var ts; createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); } if (ref.prepend) { - if (resolvedRefOpts.outFile) { - if (!host.fileExists(resolvedRefOpts.outFile)) { - createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + var out = resolvedRefOpts.outFile || resolvedRefOpts.out; + if (out) { + if (!host.fileExists(out)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path); } } else { @@ -84768,17 +86584,16 @@ var ts; } } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); - var _loop_9 = function (file) { - if (normalizedRootNames.every(function (r) { return r !== file; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); + if (rootNames.length < sourceFiles.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { + var file = _a[_i]; + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } - }; - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var file = sourceFiles_4[_i]; - _loop_9(file); } } if (options.paths) { @@ -84828,15 +86643,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); } if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite"); } if (options.out || options.outFile) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.declarationMap && !ts.getEmitDeclarations(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite"); } if (options.lib && options.noLib) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); @@ -84863,7 +86678,7 @@ var ts; programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } // Cannot specify module gen that isn't amd or system with --out - if (outFile) { + if (outFile && !options.emitDeclarationOnly) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } @@ -84876,9 +86691,9 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { - createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!ts.hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } // there has to be common source directory if user specified --outdir || --sourceRoot @@ -84893,15 +86708,15 @@ var ts; createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + if (!options.noEmit && options.allowJs && ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", getEmitDeclarationOptionName(options)); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + if (!ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } if (options.noEmit) { createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); @@ -85092,7 +86907,7 @@ var ts; if (options.outDir) { return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { // Otherwise just check if sourceFile with the name exists var filePathWithoutExtension = ts.removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || @@ -85109,7 +86924,10 @@ var ts; function parseConfigHostFromCompilerHost(host) { return { fileExists: function (f) { return host.fileExists(f); }, - readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readDirectory: function (root, extensions, excludes, includes, depth) { + ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory(root, extensions, excludes, includes, depth); + }, readFile: function (f) { return host.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, @@ -85117,17 +86935,14 @@ var ts; }; } ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; - /** - * Returns the target config filename of a project reference. - * Note: The file might not exist. - */ - function resolveProjectReferencePath(host, ref) { - if (!host.fileExists(ref.path)) { - return ts.combinePaths(ref.path, "tsconfig.json"); - } - return ref.path; + function resolveProjectReferencePath(hostOrRef, ref) { + var passedInRef = ref ? ref : hostOrRef; + return ts.resolveConfigFileProjectName(passedInRef.path); } ts.resolveProjectReferencePath = resolveProjectReferencePath; + function getEmitDeclarationOptionName(options) { + return options.declaration ? "declaration" : "composite"; + } /* @internal */ /** * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. @@ -85197,7 +87012,7 @@ var ts; function getReferencedFileFromImportedModuleSymbol(symbol) { if (symbol.declarations && symbol.declarations[0]) { var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - return declarationSourceFile && declarationSourceFile.path; + return declarationSourceFile && declarationSourceFile.resolvedPath; } } /** @@ -85207,6 +87022,12 @@ var ts; var symbol = checker.getSymbolAtLocation(importName); return symbol && getReferencedFileFromImportedModuleSymbol(symbol); } + /** + * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path + */ + function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) { + return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName); + } /** * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true */ @@ -85230,7 +87051,7 @@ var ts; if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(referencedPath); } } @@ -85241,11 +87062,45 @@ var ts; return; } var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName); addReferencedFile(typeFilePath); }); } + // Add module augmentation as references + if (sourceFile.moduleAugmentations.length) { + var checker = program.getTypeChecker(); + for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) { + var moduleName = _e[_d]; + if (!ts.isStringLiteral(moduleName)) { + continue; + } + var symbol = checker.getSymbolAtLocation(moduleName); + if (!symbol) { + continue; + } + // Add any file other than our own as reference + addReferenceFromAmbientModule(symbol); + } + } + // From ambient modules + for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) { + var ambientModule = _g[_f]; + if (ambientModule.declarations.length > 1) { + addReferenceFromAmbientModule(ambientModule); + } + } return referencedFiles; + function addReferenceFromAmbientModule(symbol) { + // Add any file other than our own as reference + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var declarationSourceFile = ts.getSourceFileOfNode(declaration); + if (declarationSourceFile && + declarationSourceFile !== sourceFile) { + addReferencedFile(declarationSourceFile.resolvedPath); + } + } + } function addReferencedFile(referencedPath) { if (!referencedFiles) { referencedFiles = ts.createMap(); @@ -85765,7 +87620,7 @@ var ts; BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { var host; var newProgram; var oldProgram; @@ -85778,7 +87633,14 @@ var ts; } else if (ts.isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram; - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = ts.createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions, + host: oldProgramOrHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics: configFileParsingDiagnostics, + projectReferences: projectReferences + }); host = oldProgramOrHost; } else { @@ -85952,16 +87814,16 @@ var ts; ts.createBuilderProgram = createBuilderProgram; })(ts || (ts = {})); (function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; return { // Only return program, all other methods are not implemented getProgram: function () { return program; }, @@ -86110,7 +87972,7 @@ var ts; } // otherwise try to load typings from @types var globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; @@ -86248,7 +88110,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? failedLookupLocation : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); + // Ensure failed look up is normalized path + failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); ts.Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); // tslint:disable-line var subDirectoryInRoot = failedLookupLocationPath.indexOf(ts.directorySeparator, rootPath.length + 1); if (subDirectoryInRoot !== -1) { @@ -86588,121 +88451,117 @@ var ts; (function (ts) { var moduleSpecifiers; (function (moduleSpecifiers) { + var RelativePreference; + (function (RelativePreference) { + RelativePreference[RelativePreference["Relative"] = 0] = "Relative"; + RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative"; + RelativePreference[RelativePreference["Auto"] = 2] = "Auto"; + })(RelativePreference || (RelativePreference = {})); + // See UserPreferences#importPathEnding + var Ending; + (function (Ending) { + Ending[Ending["Minimal"] = 0] = "Minimal"; + Ending[Ending["Index"] = 1] = "Index"; + Ending[Ending["JsExtension"] = 2] = "JsExtension"; + })(Ending || (Ending = {})); + function getPreferences(_a, compilerOptions, importingSourceFile) { + var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding; + return { + relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */, + ending: getEnding(), + }; + function getEnding() { + switch (importModuleSpecifierEnding) { + case "minimal": return 0 /* Minimal */; + case "index": return 1 /* Index */; + case "js": return 2 /* JsExtension */; + default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */; + } + } + } + function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) { + return { + relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */, + ending: ts.hasJSOrJsonFileExtension(oldImportSpecifier) ? 2 /* JsExtension */ + : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, + }; + } + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + if (res === oldImportSpecifier) + return undefined; + return res; + } + moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { if (preferences === void 0) { preferences = {}; } - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); - return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || - ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getModuleSpecifierForDeclarationFile(moduleSymbol, compilerOptions, importingSourceFile, host, redirectTargetsMap) { - var isBundle = (compilerOptions.out || compilerOptions.outFile); - if (isBundle && host.getCommonSourceDirectory) { - // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports, - // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this - // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative - // specifier preference - compilerOptions = __assign({}, compilerOptions, { baseUrl: host.getCommonSourceDirectory() }); - } - var preferences = { importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" }; - return ts.first(ts.first(getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, host.getSourceFiles ? host.getSourceFiles() : [importingSourceFile], preferences, redirectTargetsMap))); + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + var info = getInfo(importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || + getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } - moduleSpecifiers.getModuleSpecifierForDeclarationFile = getModuleSpecifierForDeclarationFile; - // For each symlink/original for a module, returns a list of ways to import that file. - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences, redirectTargetsMap) { + // Returns an import for each symlink and for the realpath. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) - return [[ambient]]; - var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); - if (!files) { - return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); - } + return [ambient]; + var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.fileName, info.getCanonicalFileName, host, redirectTargetsMap); - var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); - return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { - return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); - }); + var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); + return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); } moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path - function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { - var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); - var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + function getInfo(importingSourceFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); - return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; } - function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { - var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; - return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); - } - function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { - var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var ending = _b.ending, relativePreference = _b.relativePreference; var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || - removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); - if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { - return [relativePath]; + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions); + if (!baseUrl || relativePreference === 0 /* Relative */) { + return relativePath; } var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); if (!relativeToBaseUrl) { - return [relativePath]; + return relativePath; } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions); + var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths; + if (relativePreference === 1 /* NonRelative */) { + return nonRelative; } - if (preferences.importModuleSpecifierPreference === "non-relative") { - return [importRelativeToBaseUrl]; + if (relativePreference !== 2 /* Auto */) + ts.Debug.assertNever(relativePreference); + // Prefer a relative import over a baseUrl import if it has fewer components. + return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; + } + function countPathComponents(path) { + var count = 0; + for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { + if (path.charCodeAt(i) === 47 /* slash */) + count++; } - if (preferences.importModuleSpecifierPreference !== undefined) - ts.Debug.assertNever(preferences.importModuleSpecifierPreference); - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + return count; } function usesJsExtensionOnImports(_a) { var imports = _a.imports; return ts.firstDefined(imports, function (_a) { var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + return ts.pathIsRelative(text) ? ts.hasJSOrJsonFileExtension(text) : undefined; }) || false; } function stringsEqual(a, b, getCanonicalFileName) { @@ -86766,16 +88625,6 @@ var ts; result.push.apply(result, targets); return result; } - function getRelativePathNParents(relativePath) { - var components = ts.getPathComponents(relativePath); - if (components[0] || components.length === 1) - return 0; - for (var i = 1; i < components.length; i++) { - if (components[i] !== "..") - return i - 1; - } - return components.length - 1; - } function tryGetModuleNameFromAmbientModule(moduleSymbol) { var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); }); if (decl) { @@ -86793,7 +88642,8 @@ var ts; var suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { + ts.endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) { var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -86813,25 +88663,30 @@ var ts; var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.removeFileExtension(relativePath); } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - // For a type definition, we can strip `/index` even with classic resolution. - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here + function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options) { + var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + if (!host.fileExists || !host.readFile) { return undefined; } var parts = getNodeModulePathParts(moduleFileName); if (!parts) { return undefined; } + var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)) + : undefined; + var versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); @@ -86840,20 +88695,18 @@ var ts; if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + // For classic resolution, only allow importing from node_modules/@types, not other node_modules + return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; function getDirectoryOrExtensionlessFileName(path) { // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } @@ -86868,12 +88721,14 @@ var ts; } } function tryGetAnyFileFromPath(host, path) { + if (!host.fileExists) + return; // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { var e = extensions_3[_i]; var fullPath = path + e; - if (host.fileExists(fullPath)) { // TODO: GH#18217 + if (host.fileExists(fullPath)) { return fullPath; } } @@ -86936,13 +88791,36 @@ var ts; return isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } - function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + function removeExtensionAndIndexPostFix(fileName, ending, options) { + if (ts.fileExtensionIs(fileName, ".json" /* Json */)) + return fileName; var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; + switch (ending) { + case 0 /* Minimal */: + return ts.removeSuffix(noExtension, "/index"); + case 1 /* Index */: + return noExtension; + case 2 /* JsExtension */: + return noExtension + getJSExtensionForFile(fileName, options); + default: + return ts.Debug.assertNever(ending); + } + } + function getJSExtensionForFile(fileName, options) { + var ext = ts.extensionFromPath(fileName); + switch (ext) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + return ".js" /* Js */; + case ".tsx" /* Tsx */: + return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + case ".js" /* Js */: + case ".jsx" /* Jsx */: + case ".json" /* Json */: + return ext; + default: + return ts.Debug.assertNever(ext); + } } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -86981,11 +88859,6 @@ var ts; }; } ts.createDiagnosticReporter = createDiagnosticReporter; - /** @internal */ - ts.nonClearingMessageCodes = [ - ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, - ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code - ]; /** * @returns Whether the screen was cleared. */ @@ -86994,7 +88867,7 @@ var ts; !options.preserveWatchOutput && !options.extendedDiagnostics && !options.diagnostics && - !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { + ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) { system.clearScreen(); return true; } @@ -87044,7 +88917,7 @@ var ts; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile) { // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -87060,7 +88933,7 @@ var ts; } } // Emit and report any errors we ran into. - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { ts.addRange(diagnostics, program.getSemanticDiagnostics()); @@ -87094,6 +88967,25 @@ var ts; } ts.emitFilesAndReportErrors = emitFilesAndReportErrors; var noopFileWatcher = { close: ts.noop }; + function createWatchHost(system, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + return { + onWatchStatusChange: onWatchStatusChange, + watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, + watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, + setTimeout: system.setTimeout ? (function (callback, ms) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); + }) : ts.noop, + clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + }; + } + ts.createWatchHost = createWatchHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -87106,7 +88998,7 @@ var ts; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; - var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); + var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -87120,17 +89012,10 @@ var ts; readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, realpath: system.realpath && (function (path) { return system.realpath(path); }), getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, + watchFile: watchFile, + watchDirectory: watchDirectory, + setTimeout: setTimeout, + clearTimeout: clearTimeout, trace: function (s) { return system.write(s); }, onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, @@ -87179,18 +89064,19 @@ var ts; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; })(ts || (ts = {})); (function (ts) { - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -87213,9 +89099,10 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options; + var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; + var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { @@ -87286,7 +89173,8 @@ var ts; }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram: getCurrentProgram, - writeLog: writeLog + writeLog: writeLog, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, }; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? @@ -87324,9 +89212,9 @@ var ts; } // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -87351,7 +89239,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -87532,12 +89420,7 @@ var ts; function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (result.fileNames.length) { - configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); - hasChangedConfigFileParsingErrors = true; - } - else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { - configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (ts.updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; @@ -87563,7 +89446,9 @@ var ts; rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 - configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + projectReferences = configFileParseResult.projectReferences; + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice(); + canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw); hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { @@ -87650,6 +89535,8 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); +// Currently we do not want to expose API for build, we should work out the API, and then expose it just like we did for builder/watch +/*@internal*/ var ts; (function (ts) { var minimumDate = new Date(-8640000000000000); @@ -87670,7 +89557,8 @@ var ts; BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; - BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors"; })(BuildResultFlags || (BuildResultFlags = {})); var UpToDateStatusType; (function (UpToDateStatusType) { @@ -87687,94 +89575,65 @@ var ts; UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); - /** - * A FileMap maintains a normalized-key to value relationship - */ - function createFileMap() { + function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword var lookup = ts.createMap(); return { setValue: setValue, getValue: getValue, - getValueOrUndefined: getValueOrUndefined, removeKey: removeKey, - getKeys: getKeys, - hasKey: hasKey + forEach: forEach, + hasKey: hasKey, + getSize: getSize, + clear: clear }; - function getKeys() { - return Object.keys(lookup); + function forEach(action) { + lookup.forEach(action); } function hasKey(fileName) { - return lookup.has(ts.normalizePath(fileName)); + return lookup.has(toPath(fileName)); } function removeKey(fileName) { - lookup.delete(ts.normalizePath(fileName)); + lookup.delete(toPath(fileName)); } function setValue(fileName, value) { - lookup.set(ts.normalizePath(fileName), value); + lookup.set(toPath(fileName), value); } function getValue(fileName) { - var f = ts.normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f); - } - else { - throw new Error("No value corresponding to " + fileName + " exists in this map"); - } + return lookup.get(toPath(fileName)); } - function getValueOrUndefined(fileName) { - var f = ts.normalizePath(fileName); - return lookup.get(f); + function getSize() { + return lookup.size; + } + function clear() { + lookup.clear(); } } - function createDependencyMapper() { - var childToParents = createFileMap(); - var parentToChildren = createFileMap(); - var allKeys = createFileMap(); - function addReference(childConfigFileName, parentConfigFileName) { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { + var existingValue = configFileMap.getValue(resolved); + var newValue; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } - function getReferencesTo(parentConfigFileName) { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; - } - function getReferencesOf(childConfigFileName) { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - function getKeys() { - return allKeys.getKeys(); - } - function addEntry(mapToAddTo, key, element) { - key = ts.normalizePath(key); - element = ts.normalizePath(element); - var arr = mapToAddTo.getValueOrUndefined(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - allKeys.setValue(key, true); - allKeys.setValue(element, true); - } - return { - addReference: addReference, - getReferencesTo: getReferencesTo, - getReferencesOf: getReferencesOf, - getKeys: getKeys - }; + return existingValue || newValue; + } + function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { + return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } function getOutputDeclarationFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); return ts.changeExtension(outputPath, ".d.ts" /* Dts */); } - function getOutputJavaScriptFileName(inputFileName, configFile) { + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile) { var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : @@ -87787,7 +89646,11 @@ var ts; return ts.emptyArray; } var outputs = []; - outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + var js = getOutputJSFileName(inputFileName, configFile); + outputs.push(js); + if (configFile.options.sourceMap) { + outputs.push(js + ".map"); + } if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { var dts = getOutputDeclarationFileName(inputFileName, configFile); outputs.push(dts); @@ -87798,13 +89661,17 @@ var ts; return outputs; } function getOutFileOutputs(project) { - if (!project.options.outFile) { + var out = project.options.outFile || project.options.out; + if (!out) { return ts.Debug.fail("outFile must be set"); } var outputs = []; - outputs.push(project.options.outFile); + outputs.push(out); + if (project.options.sourceMap) { + outputs.push(out + ".map"); + } if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + var dts = ts.changeExtension(out, ".d.ts" /* Dts */); outputs.push(dts); if (project.options.declarationMap) { outputs.push(dts + ".map"); @@ -87815,808 +89682,820 @@ var ts; function rootDirOfOptions(opts, configFileName) { return opts.rootDir || ts.getDirectoryPath(configFileName); } - function createConfigFileCache(host) { - var cache = createFileMap(); - var configParseHost = ts.parseConfigHostFromCompilerHost(host); - function parseConfigFile(configFilePath) { - var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); - if (sourceFile === undefined) { - return undefined; - } - var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - function removeKey(configFilePath) { - cache.removeKey(configFilePath); - } - return { - parseConfigFile: parseConfigFile, - removeKey: removeKey - }; - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } function isDeclarationFile(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } - function createBuildContext(options) { - var invalidatedProjects = createFileMap(); - var queuedProjects = createFileMap(); - var missingRoots = ts.createMap(); - return { - options: options, - projectStatus: createFileMap(), - unchangedOutputs: createFileMap(), - invalidatedProjects: invalidatedProjects, - missingRoots: missingRoots, - queuedProjects: queuedProjects + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createBuilderStatusReporter(system, pretty) { + return function (diagnostic) { + var output = pretty ? "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] " : new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + system.write(output); }; } - ts.createBuildContext = createBuildContext; - var buildOpts = [ - { - name: "verbose", - shortName: "v", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Enable_verbose_logging, - type: "boolean" - }, - { - name: "dry", - shortName: "d", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, - type: "boolean" - }, - { - name: "force", - shortName: "f", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, - type: "boolean" - }, - { - name: "clean", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Delete_the_outputs_of_all_projects, - type: "boolean" - }, - { - name: "watch", - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Watch_input_files, - type: "boolean" - } - ]; - function performBuild(args, compilerHost, buildHost, system) { - var verbose = false; - var dry = false; - var force = false; - var clean = false; - var watch = false; - var projects = []; - for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { - var arg = args_6[_i]; - switch (arg.toLowerCase()) { - case "-v": - case "--verbose": - verbose = true; - continue; - case "-d": - case "--dry": - dry = true; - continue; - case "-f": - case "--force": - force = true; - continue; - case "--clean": - clean = true; - continue; - case "--watch": - case "-w": - watch = true; - continue; - case "--?": - case "-?": - case "--help": - ts.printHelp(buildOpts, "--build "); - return ts.ExitStatus.Success; - } - // Not a flag, parse as filename - addProject(arg); - } - // Nonsensical combinations - if (clean && force) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && verbose) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (clean && watch) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (watch && dry) { - buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (projects.length === 0) { - // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." - addProject("."); - } - var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); - if (clean) { - return builder.cleanAllProjects(); - } - if (watch) { - builder.buildAllProjects(); - builder.startWatching(); - return undefined; - } - return builder.buildAllProjects(); - function addProject(projectSpecification) { - var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); - var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); - if (!compilerHost.fileExists(refPath)) { - return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); - } - projects.push(refPath); - } + ts.createBuilderStatusReporter = createBuilderStatusReporter; + function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; + host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; + host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); + host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); + return host; + } + ts.createSolutionBuilderHost = createSolutionBuilderHost; + function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus); + var watchHost = ts.createWatchHost(system, reportWatchStatus); + host.onWatchStatusChange = watchHost.onWatchStatusChange; + host.watchFile = watchHost.watchFile; + host.watchDirectory = watchHost.watchDirectory; + host.setTimeout = watchHost.setTimeout; + host.clearTimeout = watchHost.clearTimeout; + return host; + } + ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; + function getCompilerOptionsOfBuildOptions(buildOptions) { + var result = {}; + ts.commonOptionsWithBuild.forEach(function (option) { + result[option.name] = buildOptions[option.name]; + }); + return result; } - ts.performBuild = performBuild; /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references + * TODO: use SolutionBuilderWithWatchHost => watchedSolution + * use SolutionBuilderHost => Solution */ - function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { - if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { - throw new Error("Host must support timestamp APIs"); - } - var configFileCache = createConfigFileCache(compilerHost); - var context = createBuildContext(defaultOptions); - var existingWatchersForWildcards = ts.createMap(); - var upToDateHost = { - fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, - getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, - getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, - getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, - setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, - parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } - }; + function createSolutionBuilder(host, rootNames, defaultOptions) { + var hostWithWatch = host; + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + // State of the solution + var options = defaultOptions; + var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + var configFileCache = createFileMap(toPath); + /** Map from output file name to its pre-build timestamp */ + var unchangedOutputs = createFileMap(toPath); + /** Map from config file name to up-to-date status */ + var projectStatus = createFileMap(toPath); + var missingRoots = ts.createMap(); + var globalDependencyGraph; + var writeFileName = function (s) { return host.trace && host.trace(s); }; + // Watch state + var diagnostics = createFileMap(toPath); + var projectPendingBuild = createFileMap(toPath); + var projectErrorsReported = createFileMap(toPath); + var invalidatedProjectQueue = []; + var nextProjectToBuild = 0; + var timerToBuildInvalidatedProject; + var reportFileChangeDetected = false; + // Watches for the solution + var allWatchedWildcardDirectories = createFileMap(toPath); + var allWatchedInputFiles = createFileMap(toPath); + var allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects: buildAllProjects, - getUpToDateStatus: getUpToDateStatus, getUpToDateStatusOfFile: getUpToDateStatusOfFile, cleanAllProjects: cleanAllProjects, resetBuildContext: resetBuildContext, getBuildGraph: getBuildGraph, invalidateProject: invalidateProject, - buildInvalidatedProjects: buildInvalidatedProjects, - buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + buildInvalidatedProject: buildInvalidatedProject, resolveProjectName: resolveProjectName, startWatching: startWatching }; - function startWatching() { - if (!system) - throw new Error("System host must be provided if using --watch"); - if (!system.watchFile || !system.watchDirectory || !system.setTimeout) - throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); - var graph = getGlobalDependencyGraph(); - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - var _loop_10 = function (resolved) { - var cfg = configFileCache.parseConfigFile(resolved); - if (cfg) { - // Watch this file - system.watchFile(resolved, function () { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); - }); - // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { - return system.watchDirectory(dir, function () { - invalidateProjectAndScheduleBuilds(resolved); - }, !!(flags & 1 /* Recursive */)); - }); - } - // Watch input files - for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { - var input = _a[_i]; - system.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved); - }); - } - } - }; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var resolved = _a[_i]; - _loop_10(resolved); - } - function invalidateProjectAndScheduleBuilds(resolved) { - invalidateProject(resolved); - system.setTimeout(buildInvalidatedProjects, 100); - system.setTimeout(buildDependentInvalidatedProjects, 3000); - } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function resetBuildContext(opts) { if (opts === void 0) { opts = defaultOptions; } - context = createBuildContext(opts); + options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + globalDependencyGraph = undefined; + diagnostics.clear(); + projectPendingBuild.clear(); + projectErrorsReported.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); + ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); + ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + } + function isParsedCommandLine(entry) { + return !!entry.options; + } + function parseConfigFile(configFilePath) { + var value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + var diagnostic; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; }; + var parsed = ts.getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop; + configFileCache.setValue(configFilePath, parsed || diagnostic); + return parsed; + } + function reportStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args))); + } + function reportWatchStatus(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + if (hostWithWatch.onWatchStatusChange) { + hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)), host.getNewLine(), baseCompilerOptions); + } + } + function startWatching() { + var graph = getGlobalDependencyGraph(); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + // Watch this file + watchConfigFile(resolved); + var cfg = parseConfigFile(resolved); + if (cfg) { + // Update watchers for wildcard directories + watchWildCardDirectories(resolved, cfg); + // Watch input files + watchInputFiles(resolved, cfg); + } + } + } + function watchConfigFile(resolved) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); + })); + } + } + function watchWildCardDirectories(resolved, parsed) { + if (!options.watch) + return; + ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { + return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + var fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); + }, !!(flags & 1 /* Recursive */)); + }); + } + function watchInputFiles(resolved, parsed) { + if (!options.watch) + return; + ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { + createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); + }); }, + onDeleteValue: ts.closeFileWatcher, + }); + } + function isOutputFile(fileName, configFile) { + if (configFile.options.noEmit) + return false; + // ts or tsx files are not output + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && + (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) { + return false; + } + // If options have --outFile or --out, check if its that + var out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) { + return true; + } + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(fileName, inputFile); }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + function invalidateProjectAndScheduleBuilds(resolved, reloadLevel) { + reportFileChangeDetected = true; + invalidateResolvedProject(resolved, reloadLevel); + scheduleBuildInvalidatedProject(); } function getUpToDateStatusOfFile(configFileName) { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project) { - return ts.getUpToDateStatus(upToDateHost, project); + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = projectStatus.getValue(project.options.configFilePath); + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(project); + projectStatus.setValue(project.options.configFilePath, actual); + return actual; } - function invalidateProject(configFileName) { - var resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - // TODO: do those things - return; + function getUpToDateStatusWorker(project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } } - configFileCache.removeKey(resolved); - context.invalidatedProjects.setValue(resolved, true); - context.projectStatus.removeKey(resolved); - var graph = getGlobalDependencyGraph(); - if (graph) { - queueBuildForDownstreamReferences(resolved); + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root) { - var deps = graph.dependencyMap.getReferencesTo(root); - for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { - var ref = deps_1[_i]; - // Can skip circular references - if (!context.queuedProjects.hasKey(ref)) { - context.queuedProjects.setValue(ref, true); - queueBuildForDownstreamReferences(ref); + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) { + var output = outputs_1[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = unchangedOutputs.getValue(output); + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return; - var graph = createDependencyGraph(resolvedNames); - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; - if (!predicate(next)) - continue; - var resolved = resolveProjectName(next); - if (!resolved) - continue; // ?? - var proj = configFileCache.parseConfigFile(resolved); - if (!proj) - continue; // ? - var status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath, { type: UpToDateStatusType.ComputingUpstream }); + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(ref); + var refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date + return { + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName + }; + } + function invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); + } + addProjToQueue(resolved, reloadLevel); + } + /** + * return true if new addition + */ + function addProjToQueue(proj, reloadLevel) { + var value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + } + else if (value < (reloadLevel || ts.ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ts.ConfigFileProgramReloadLevel.None); + } + } + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + var project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + var reloadLevel = projectPendingBuild.getValue(project); + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project: project, reloadLevel: reloadLevel }; + } + } + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + function scheduleBuildInvalidatedProject() { + if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { + return; + } + if (timerToBuildInvalidatedProject) { + hostWithWatch.clearTimeout(timerToBuildInvalidatedProject); + } + timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildInvalidatedProject, 250); + } + function buildInvalidatedProject() { + timerToBuildInvalidatedProject = undefined; + if (reportFileChangeDetected) { + reportFileChangeDetected = false; + projectErrorsReported.clear(); + reportWatchStatus(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } + var buildProject = getNextInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (hasPendingInvalidatedProjects()) { + if (options.watch && !timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); + } + } + } + function reportErrorSummary() { + if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(function (project) { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || ts.emptyArray); + } + }); + var totalErrors_1 = 0; + diagnostics.forEach(function (singleProjectErrors) { return totalErrors_1 += singleProjectErrors.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length; }); + reportWatchStatus(totalErrors_1 === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors_1); + } + } + function buildSingleInvalidatedProject(resolved, reloadLevel) { + var proj = parseConfigFile(resolved); + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) { + // Update file names + var result = ts.getFileNamesFromConfigSpecs(proj.configFileSpecs, ts.getDirectoryPath(resolved), proj.options, parseConfigFileHost); + ts.updateErrorForNoInputFiles(result, resolved, proj.configFileSpecs, proj.errors, ts.canJsonReportNoInutFiles(proj.raw)); + proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(resolved, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + var buildResult = buildSingleProject(resolved); + var dependencyGraph = getGlobalDependencyGraph(); + var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) + return; + // Always use build order to queue projects + for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { + var project = _a[_i]; + var prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } - buildSingleProject(next); } } function createDependencyGraph(roots) { - var temporaryMarks = {}; - var permanentMarks = {}; + var temporaryMarks = createFileMap(toPath); + var permanentMarks = createFileMap(toPath); var circularityReportStack = []; var buildOrder = []; - var graph = createDependencyMapper(); - var hadError = false; + var referencingProjectsMap = createFileMap(toPath); for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { var root = roots_1[_i]; visit(root); } - if (hadError) { - return undefined; - } return { buildQueue: buildOrder, - dependencyMap: graph + referencingProjectsMap: referencingProjectsMap }; function visit(projPath, inCircularContext) { - if (inCircularContext === void 0) { inCircularContext = false; } // Already visited - if (permanentMarks[projPath]) + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; + // TODO:: Do we report this as error? + reportStatus(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); } - } - temporaryMarks[projPath] = true; - circularityReportStack.push(projPath); - var parsed = configFileCache.parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; return; } - if (parsed.projectReferences) { + temporaryMarks.setValue(projPath, true); + circularityReportStack.push(projPath); + var parsed = parseConfigFile(projPath); + if (parsed && parsed.projectReferences) { for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { var ref = _a[_i]; var resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + var referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, function () { return createFileMap(toPath); }); + referencingProjects.setValue(projPath, !!ref.prepend); } } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } function buildSingleProject(proj) { - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + if (options.verbose) + reportStatus(ts.Diagnostics.Building_project_0, proj); var resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - var configFile = configFileCache.parseConfigFile(proj); + var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + reportParseConfigFileDiagnostic(proj); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } if (configFile.fileNames.length === 0) { + reportAndStoreErrors(proj, configFile.errors); // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } var programOptions = { projectReferences: configFile.projectReferences, - host: compilerHost, + host: host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; var program = ts.createProgram(programOptions); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { - var diag = syntaxDiagnostics_1[_i]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (ts.getEmitDeclarations(program.getCompilerOptions())) { var declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { - var diag = declDiagnostics_1[_a]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { - var diag = semanticDiagnostics_1[_b]; - buildHost.errorDiagnostic(diag); - } - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var emitDiagnostics; + var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; + ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { - if (compilerHost.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; - priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { + priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + if (options.watch) { + diagnostics.removeKey(proj); + } + projectStatus.setValue(proj, status); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + return resultFlags; + } } function updateOutputTimestamps(proj) { - if (context.options.dry) { - return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + if (options.dry) { + return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (context.options.verbose) { - buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + if (options.verbose) { + reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); } var now = new Date(); var outputs = getAllProjectOutputs(proj); var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { - var file = outputs_1[_i]; + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file) || ts.missingFileModifiedTime); + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); } - compilerHost.setModifiedTime(file, now); + host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } - function getFilesToClean(configFileNames) { - var resolvedNames = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) - return undefined; + function getFilesToClean() { // Get the same graph for cleaning we'd use for building - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; + var graph = getGlobalDependencyGraph(); var filesToDelete = []; for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { var proj = _a[_i]; - var parsed = configFileCache.parseConfigFile(proj); + var parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } var outputs = getAllProjectOutputs(parsed); - for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { - var output = outputs_2[_b]; - if (compilerHost.fileExists(output)) { + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + if (host.fileExists(output)) { filesToDelete.push(output); } } } return filesToDelete; } - function getAllProjectsInScope() { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - return undefined; - var graph = createDependencyGraph(resolvedNames); - if (graph === undefined) - return undefined; - return graph.buildQueue; - } function cleanAllProjects() { - var resolvedNames = getAllProjectsInScope(); - if (resolvedNames === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - var filesToDelete = getFilesToClean(resolvedNames); - if (filesToDelete === undefined) { - buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (context.options.dry) { - buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + var filesToDelete = getFilesToClean(); + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); return ts.ExitStatus.Success; } - // Do this check later to allow --clean --dry to function even if the host can't delete files - if (!compilerHost.deleteFile) { - throw new Error("Host does not support deleting files"); - } for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { var output = filesToDelete_1[_i]; - compilerHost.deleteFile(output); + host.deleteFile(output); } return ts.ExitStatus.Success; } function resolveProjectName(name) { - var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); - if (compilerHost.fileExists(fullPath)) { - return fullPath; - } - var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); - if (compilerHost.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig; - } - buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); - return undefined; + return resolveConfigFileProjectName(ts.resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames) { - var resolvedNames = []; - for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { - var name = configFileNames_1[_i]; - var resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects() { + if (options.watch) { + reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); + } var graph = getGlobalDependencyGraph(); - if (graph === undefined) - return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; - var queue = graph.buildQueue; reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { - var next = queue_1[_i]; - var proj = configFileCache.parseConfigFile(next); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + var proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } + // report errors early when using continue or break statements + var errors = proj.errors; var status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); var projName = proj.options.configFilePath; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact - buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + reportStatus(ts.Diagnostics.Project_0_is_up_to_date, projName); } continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + reportAndStoreErrors(next, errors); + if (options.verbose) + reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportAndStoreErrors(next, errors); // Do nothing continue; } var buildResult = buildSingleProject(next); anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } + reportErrorSummary(); return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function reportParseConfigFileDiagnostic(proj) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); + } + function reportAndStoreErrors(proj, errors) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + function reportErrors(errors) { + errors.forEach(function (err) { return host.reportDiagnostic(err); }); + } /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph) { - if (!context.options.verbose) - return; - var names = []; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var name = _a[_i]; - names.push(name); + if (options.verbose) { + reportStatus(ts.Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(function (s) { return "\r\n * " + relName(s); }).join("")); } - if (context.options.verbose) - buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); } function relName(path) { - return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); - } - function reportVerbose(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - buildHost.verbose.apply(buildHost, [message].concat(args)); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName, status) { - if (!context.options.verbose) + if (!options.verbose) return; - return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } ts.createSolutionBuilder = createSolutionBuilder; - /** - * Gets the UpToDateStatus for a project - */ - function getUpToDateStatus(host, project) { - if (project === undefined) { - return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + function resolveConfigFileProjectName(project) { + if (ts.fileExtensionIs(project, ".json" /* Json */)) { + return project; } - var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; - if (prior !== undefined) { - return prior; - } - var actual = getUpToDateStatusWorker(host, project); - if (host.setLastStatus) { - host.setLastStatus(project.options.configFilePath, actual); - } - return actual; - } - ts.getUpToDateStatus = getUpToDateStatus; - function getUpToDateStatusWorker(host, project) { - var newestInputFileName = undefined; - var newestInputFileTime = minimumDate; - // Get timestamps of input files - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - if (!host.fileExists(inputFile)) { - return { - type: UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" - }; - } - var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime; - if (inputTime > newestInputFileTime) { - newestInputFileName = inputFile; - newestInputFileTime = inputTime; - } - } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { - return { - type: UpToDateStatusType.ContainerOnly - }; - } - // Now see if all outputs are newer than the newest input - var oldestOutputFileName = "(none)"; - var oldestOutputFileTime = maximumDate; - var newestOutputFileName = "(none)"; - var newestOutputFileTime = minimumDate; - var missingOutputFileName; - var newestDeclarationFileContentChangedTime = minimumDate; - var isOutOfDateWithInputs = false; - for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { - var output = outputs_3[_b]; - // Output is missing; can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (!host.fileExists(output)) { - missingOutputFileName = output; - break; - } - var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - if (outputTime < oldestOutputFileTime) { - oldestOutputFileTime = outputTime; - oldestOutputFileName = output; - } - // If an output is older than the newest input, we can stop checking - // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status - if (outputTime < newestInputFileTime) { - isOutOfDateWithInputs = true; - break; - } - if (outputTime > newestOutputFileTime) { - newestOutputFileTime = outputTime; - newestOutputFileName = output; - } - // Keep track of when the most recent time a .d.ts file was changed. - // In addition to file timestamps, we also keep track of when a .d.ts file - // had its file touched but not had its contents changed - this allows us - // to skip a downstream typecheck - if (isDeclarationFile(output)) { - var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; - if (unchangedTime !== undefined) { - newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); - } - else { - var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime; - newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime); - } - } - } - var pseudoUpToDate = false; - var usesPrepend = false; - var upstreamChangedProject; - if (project.projectReferences && host.parseConfigFile) { - for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { - var ref = _d[_c]; - usesPrepend = usesPrepend || !!(ref.prepend); - var resolvedRef = ts.resolveProjectReferencePath(host, ref); - var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); - // An upstream project is blocked - if (refStatus.type === UpToDateStatusType.Unbuildable) { - return { - type: UpToDateStatusType.UpstreamBlocked, - upstreamProjectName: ref.path - }; - } - // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) - if (refStatus.type !== UpToDateStatusType.UpToDate) { - return { - type: UpToDateStatusType.UpstreamOutOfDate, - upstreamProjectName: ref.path - }; - } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; - } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; - } - } - if (missingOutputFileName !== undefined) { - return { - type: UpToDateStatusType.OutputMissing, - missingOutputFileName: missingOutputFileName - }; - } - if (isOutOfDateWithInputs) { - return { - type: UpToDateStatusType.OutOfDateWithSelf, - outOfDateOutputFileName: oldestOutputFileName, - newerInputFileName: newestInputFileName - }; - } - if (usesPrepend && pseudoUpToDate) { - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: upstreamChangedProject - }; - } - // Up to date - return { - type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, - newestInputFileTime: newestInputFileTime, - newestOutputFileTime: newestOutputFileTime, - newestInputFileName: newestInputFileName, - newestOutputFileName: newestOutputFileName, - oldestOutputFileName: oldestOutputFileName - }; + return ts.combinePaths(project, "tsconfig.json"); } + ts.resolveConfigFileProjectName = resolveConfigFileProjectName; function getAllProjectOutputs(project) { - if (project.options.outFile) { + if (project.options.outFile || project.options.out) { return getOutFileOutputs(project); } else { @@ -88652,7 +90531,9 @@ var ts; case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); case UpToDateStatusType.ContainerOnly: - // Don't report status on "solution" projects + // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: ts.assertType(status); @@ -88660,6 +90541,142 @@ var ts; } ts.formatUpToDateStatus = formatUpToDateStatus; })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var ValueKind; + (function (ValueKind) { + ValueKind[ValueKind["Const"] = 0] = "Const"; + ValueKind[ValueKind["Array"] = 1] = "Array"; + ValueKind[ValueKind["FunctionOrClass"] = 2] = "FunctionOrClass"; + ValueKind[ValueKind["Object"] = 3] = "Object"; + })(ValueKind = ts.ValueKind || (ts.ValueKind = {})); + function inspectModule(fileNameToRequire) { + return inspectValue(ts.removeFileExtension(ts.getBaseFileName(fileNameToRequire)), tryRequire(fileNameToRequire)); + } + ts.inspectModule = inspectModule; + function inspectValue(name, value) { + return getValueInfo(name, value, getRecurser()); + } + ts.inspectValue = inspectValue; + function getRecurser() { + var seen = new Set(); + var nameStack = []; + return function (obj, name, cbOk, cbFail) { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + seen.add(obj); + nameStack.push(name); + var res = cbOk(); + nameStack.pop(); + seen.delete(obj); + return res; + }; + } + function getValueInfo(name, value, recurser) { + return recurser(value, name, function () { + if (typeof value === "function") + return getFunctionOrClassInfo(value, name, recurser); + if (typeof value === "object") { + var builtin = getBuiltinType(name, value, recurser); + if (builtin !== undefined) + return builtin; + var entries = getEntriesOfObject(value); + return { kind: 3 /* Object */, name: name, members: ts.flatMap(entries, function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }) }; + } + return { kind: 0 /* Const */, name: name, typeName: isNullOrUndefined(value) ? "any" : typeof value }; + }, function (isCircularReference, keyStack) { return anyValue(name, " " + (isCircularReference ? "Circular reference" : "Too-deep object hierarchy") + " from " + keyStack.join(".")); }); + } + function getFunctionOrClassInfo(fn, name, recurser) { + var prototypeMembers = getPrototypeMembers(fn, recurser); + var namespaceMembers = ts.flatMap(getEntriesOfObject(fn), function (_a) { + var key = _a.key, value = _a.value; + return getValueInfo(key, value, recurser); + }); + var toString = ts.cast(Function.prototype.toString.call(fn), ts.isString); + var source = ts.stringContains(toString, "{ [native code] }") ? getFunctionLength(fn) : toString; + return { kind: 2 /* FunctionOrClass */, name: name, source: source, namespaceMembers: namespaceMembers, prototypeMembers: prototypeMembers }; + } + var builtins = ts.memoize(function () { + var map = ts.createMap(); + for (var _i = 0, _a = getEntriesOfObject(global); _i < _a.length; _i++) { + var _b = _a[_i], key = _b.key, value = _b.value; + if (typeof value === "function" && typeof value.prototype === "object" && value !== Object) { + map.set(key, value); + } + } + return map; + }); + function getBuiltinType(name, value, recurser) { + return ts.isArray(value) + ? { name: name, kind: 1 /* Array */, inner: value.length && getValueInfo("element", ts.first(value), recurser) || anyValue(name) } + : ts.forEachEntry(builtins(), function (builtin, builtinName) { + return value instanceof builtin ? { kind: 0 /* Const */, name: name, typeName: builtinName } : undefined; + }); + } + function getPrototypeMembers(fn, recurser) { + var prototype = fn.prototype; + // tslint:disable-next-line no-unnecessary-type-assertion (TODO: update LKG and it will really be unnecessary) + return typeof prototype !== "object" || prototype === null ? ts.emptyArray : ts.mapDefined(getEntriesOfObject(prototype), function (_a) { + var key = _a.key, value = _a.value; + return key === "constructor" ? undefined : getValueInfo(key, value, recurser); + }); + } + var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + function getEntriesOfObject(obj) { + var seen = ts.createMap(); + var entries = []; + var chain = obj; + while (!isNullOrUndefined(chain) && chain !== Object.prototype && chain !== Function.prototype) { + for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { + var key = _a[_i]; + if (!isJsPrivate(key) && + !ignoredProperties.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // Don't add property from a higher prototype if it already exists in a lower one + ts.addToSeen(seen, key)) { + var value = safeGetPropertyOfObject(chain, key); + // Don't repeat "toString" that matches signature from Object.prototype + if (!(key === "toString" && typeof value === "function" && value.length === 0)) { + entries.push({ key: key, value: value }); + } + } + } + chain = Object.getPrototypeOf(chain); + } + return entries.sort(function (e1, e2) { return ts.compareStringsCaseSensitive(e1.key, e2.key); }); + } + function getFunctionLength(fn) { + return ts.tryCast(safeGetPropertyOfObject(fn, "length"), ts.isNumber) || 0; + } + function safeGetPropertyOfObject(obj, key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && desc.value; + } + function isNullOrUndefined(value) { + return value == null; // tslint:disable-line + } + function anyValue(name, comment) { + return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; + } + function isJsPrivate(name) { + return name.startsWith("_"); + } + ts.isJsPrivate = isJsPrivate; + function tryRequire(fileNameToRequire) { + try { + return require(fileNameToRequire); + } + catch (_a) { + return undefined; + } + } +})(ts || (ts = {})); //# sourceMappingURL=compiler.js.map "use strict"; /* @internal */ @@ -88671,6 +90688,7 @@ var ts; server.ActionSet = "action::set"; server.ActionInvalidate = "action::invalidate"; server.ActionPackageInstalled = "action::packageInstalled"; + server.ActionValueInspected = "action::valueInspected"; server.EventTypesRegistry = "event::typesRegistry"; server.EventBeginInstallTypes = "event::beginInstallTypes"; server.EventEndInstallTypes = "event::endInstallTypes"; @@ -88715,8 +90733,8 @@ var ts; (function (JsTyping) { /* @internal */ function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; /* @internal */ @@ -88791,7 +90809,7 @@ var ts; // Only infer typings for .js and .jsx files fileNames = ts.mapDefined(fileNames, function (fileName) { var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { + if (ts.hasJSFileExtension(path)) { return path; } }); @@ -88876,7 +90894,7 @@ var ts; */ function getTypingNamesFromSourceFileNames(fileNames) { var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) + if (!ts.hasJSFileExtension(j)) return undefined; var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); @@ -89005,71 +91023,6 @@ var ts; JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); //# sourceMappingURL=jsTyping.js.map "use strict"; var ts; @@ -89277,8 +91230,10 @@ var ts; } var info = ts.getProperty(npmLock.dependencies, key); var version_1 = info && info.version; - var semver = ts.Semver.parse(version_1); // TODO: GH#18217 - var newTyping = { typingLocation: typingFile, version: semver }; + if (!version_1) { + continue; + } + var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -89380,7 +91335,7 @@ var ts; } // packageName is guaranteed to exist in typesRegistry by filterTypings var distTags = _this.typesRegistry.get(packageName); - var newVersion = ts.Semver.parse(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); + var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]); var newTyping = { typingLocation: typingFile, version: newVersion }; _this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -89559,16 +91514,17 @@ var ts; function FileLog(logFile) { var _this = this; this.logFile = logFile; - this.logEnabled = true; this.isEnabled = function () { - return _this.logEnabled && _this.logFile !== undefined; + return typeof _this.logFile === "string"; }; this.writeLine = function (text) { + if (typeof _this.logFile !== "string") + return; try { fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine); } catch (e) { - _this.logEnabled = false; + _this.logFile = undefined; } }; } @@ -89678,6 +91634,11 @@ var ts; } break; } + case "inspectValue": { + var response = { kind: server.ActionValueInspected, result: ts.inspectModule(req.options.fileNameToRequire) }; + _this.sendResponse(response); + break; + } default: ts.Debug.assertNever(req); } diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index aaf6a7101a8..23d0bae7b27 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -68,7 +68,7 @@ "A_rest_parameter_cannot_have_an_initializer_1048": "rest 参数不能具有初始化表达式。", "A_rest_parameter_must_be_last_in_a_parameter_list_1014": "rest 参数必须是参数列表中的最后一个参数。", "A_rest_parameter_must_be_of_an_array_type_2370": "rest 参数必须是数组类型。", - "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式可能不具有尾随逗号。", + "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013": "Rest 参数或绑定模式不可带尾随逗号。", "A_return_statement_can_only_be_used_within_a_function_body_1108": "\"return\" 语句只能在函数体中使用。", "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167": "一系列条目,这些条目将重新映射导入内容,以查找与 \"baseUrl\" 有关的位置。", "A_set_accessor_cannot_have_a_return_type_annotation_1095": "\"set\" 访问器不能具有返回类型批注。", @@ -161,7 +161,7 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", - "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改为编写“[{0}: {1}]:{2}”。", "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", @@ -628,7 +628,7 @@ "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。", "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。", "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。", - "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", + "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "在没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。", "Options_0_and_1_cannot_be_combined_6370": "选项“{0}”与“{1}”不能组合在一起。", "Options_Colon_6027": "选项:", "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 884042a9c8f..439cff15c63 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -97,7 +97,7 @@ namespace ts.tscWatch { const tests = subProjectFiles(SubProject.tests); const ui = subProjectFiles(SubProject.ui); const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; - const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); + const testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)]; function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { @@ -244,7 +244,7 @@ export class someClass2 { }`); const allFiles = [libFile, ...core, logic[1], ...tests]; const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); - checkWatchedFiles(host, [core[0], core[1], core[2], logic[0], ...tests].map(f => f.path)); + checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path)); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary) checkWatchedDirectories(host, emptyArray, /*recursive*/ false); checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true); checkOutputErrorsInitial(host, [ From 7b5ef64e760101bbd3553d991f51f6cd56cf2e5b Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 16 Oct 2018 20:16:00 -0400 Subject: [PATCH 068/262] Unify JSX And Normal Call Checking Codepaths (#27627) * Unify JSX Call Checking Codepaths * Add tests for fixed issues * Fix lint, move all error checking into the only-run-once resolveSignature call * Remove unused (unreachable?) code path * Consolidate a little more duplicated logic into signature checking * Fix #19775 a bit more * Cosmetic changes from CR --- src/compiler/checker.ts | 789 +++++------------- src/compiler/types.ts | 5 +- src/services/completions.ts | 6 +- .../reference/api/tsserverlibrary.d.ts | 1 - tests/baselines/reference/api/typescript.d.ts | 1 - .../checkJsxChildrenProperty14.errors.txt | 18 +- .../checkJsxChildrenProperty2.errors.txt | 98 ++- .../checkJsxChildrenProperty5.errors.txt | 46 +- .../checkJsxChildrenProperty7.errors.txt | 62 +- ...xGenericTagHasCorrectInferences.errors.txt | 12 +- ...TypedStringLiteralsInJsxAttributes01.types | 4 +- ...StringLiteralsInJsxAttributes02.errors.txt | 48 +- ...TypedStringLiteralsInJsxAttributes02.types | 10 +- .../excessPropertyCheckWithSpread.errors.txt | 30 - ...sxFactoryDeclarationsLocalTypes.errors.txt | 11 +- ...xChildrenGenericContextualTypes.errors.txt | 12 +- .../jsxChildrenGenericContextualTypes.types | 16 +- ...actDefaultPropsInferenceSuccess.errors.txt | 4 +- .../tsxAttributeResolution1.errors.txt | 18 +- .../tsxAttributeResolution11.errors.txt | 6 +- .../tsxAttributeResolution15.errors.txt | 6 +- .../tsxElementResolution10.errors.txt | 7 +- .../tsxElementResolution11.errors.txt | 6 +- .../tsxElementResolution12.errors.txt | 8 +- .../tsxElementResolution3.errors.txt | 4 +- .../tsxElementResolution4.errors.txt | 4 +- .../tsxElementResolution9.errors.txt | 18 +- .../tsxGenericAttributesType2.errors.txt | 11 - .../tsxIntrinsicAttributeErrors.errors.txt | 8 +- .../tsxLibraryManagedAttributes.errors.txt | 32 +- .../tsxNotUsingApparentTypeOfSFC.errors.txt | 32 + .../reference/tsxNotUsingApparentTypeOfSFC.js | 72 ++ .../tsxNotUsingApparentTypeOfSFC.symbols | 50 ++ .../tsxNotUsingApparentTypeOfSFC.types | 54 ++ ...ponentWithDefaultTypeParameter3.errors.txt | 10 +- .../tsxSpreadAttributesResolution10.types | 4 +- ...tsxSpreadAttributesResolution12.errors.txt | 14 +- .../tsxSpreadAttributesResolution12.types | 10 +- ...tsxSpreadAttributesResolution14.errors.txt | 8 +- .../tsxSpreadAttributesResolution2.errors.txt | 31 +- .../tsxSpreadAttributesResolution2.js | 5 + .../tsxSpreadAttributesResolution2.symbols | 30 +- .../tsxSpreadAttributesResolution2.types | 18 +- .../tsxSpreadAttributesResolution6.errors.txt | 10 +- .../tsxSpreadAttributesResolution6.types | 2 +- .../tsxSpreadDoesNotReportExcessProps.js | 54 ++ .../tsxSpreadDoesNotReportExcessProps.symbols | 27 + .../tsxSpreadDoesNotReportExcessProps.types | 29 + .../tsxStatelessComponentDefaultProps.js | 32 + .../tsxStatelessComponentDefaultProps.symbols | 34 + .../tsxStatelessComponentDefaultProps.types | 36 + ...elessFunctionComponentOverload4.errors.txt | 42 +- ...elessFunctionComponentOverload5.errors.txt | 30 +- ...tsxStatelessFunctionComponents1.errors.txt | 36 +- ...tsxStatelessFunctionComponents2.errors.txt | 6 +- ...ionComponentsWithTypeArguments4.errors.txt | 10 +- ...ionComponentsWithTypeArguments5.errors.txt | 24 - .../tsxTypeArgumentResolution.errors.txt | 22 +- .../reference/tsxTypeErrors.errors.txt | 16 +- .../reference/tsxUnionElementType1.errors.txt | 18 + .../reference/tsxUnionElementType2.errors.txt | 7 +- .../reference/tsxUnionElementType3.errors.txt | 42 + .../reference/tsxUnionElementType4.errors.txt | 19 +- .../reference/tsxUnionElementType6.errors.txt | 26 +- .../tsxUnionTypeComponent1.errors.txt | 29 + .../compiler/tsxNotUsingApparentTypeOfSFC.tsx | 22 + .../tsxSpreadDoesNotReportExcessProps.tsx | 13 + .../tsxStatelessComponentDefaultProps.tsx | 17 + .../jsx/tsxAttributeResolution15.tsx | 1 + .../jsx/tsxSpreadAttributesResolution2.tsx | 3 + tests/cases/fourslash/tsxCompletion13.ts | 2 +- .../tsxCompletionUnionElementType.ts | 4 +- .../tsxGoToDefinitionStatelessFunction2.ts | 6 +- .../tsxGoToDefinitionUnionElementType1.ts | 2 +- tests/cases/fourslash/tsxQuickInfo7.ts | 4 +- 75 files changed, 1241 insertions(+), 1023 deletions(-) delete mode 100644 tests/baselines/reference/excessPropertyCheckWithSpread.errors.txt delete mode 100644 tests/baselines/reference/tsxGenericAttributesType2.errors.txt create mode 100644 tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.errors.txt create mode 100644 tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.js create mode 100644 tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.symbols create mode 100644 tests/baselines/reference/tsxNotUsingApparentTypeOfSFC.types create mode 100644 tests/baselines/reference/tsxSpreadDoesNotReportExcessProps.js create mode 100644 tests/baselines/reference/tsxSpreadDoesNotReportExcessProps.symbols create mode 100644 tests/baselines/reference/tsxSpreadDoesNotReportExcessProps.types create mode 100644 tests/baselines/reference/tsxStatelessComponentDefaultProps.js create mode 100644 tests/baselines/reference/tsxStatelessComponentDefaultProps.symbols create mode 100644 tests/baselines/reference/tsxStatelessComponentDefaultProps.types delete mode 100644 tests/baselines/reference/tsxStatelessFunctionComponentsWithTypeArguments5.errors.txt create mode 100644 tests/baselines/reference/tsxUnionElementType1.errors.txt create mode 100644 tests/baselines/reference/tsxUnionElementType3.errors.txt create mode 100644 tests/baselines/reference/tsxUnionTypeComponent1.errors.txt create mode 100644 tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx create mode 100644 tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx create mode 100644 tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9a443e6c444..604805545a4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -269,10 +269,6 @@ namespace ts { getFirstIdentifier, ), getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: nodeIn => { - const node = getParseTreeNode(nodeIn, isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, getJsxIntrinsicTagNamesAt, isOptionalParameter: nodeIn => { const node = getParseTreeNode(nodeIn, isParameter); @@ -460,7 +456,6 @@ namespace ts { const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const resolvingSignaturesArray = [resolvingSignature]; const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); @@ -6990,8 +6985,9 @@ namespace ts { getPropertiesOfObjectType(type); } - function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean { - return obj.properties.some(property => { + function isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean { + const list = obj.properties as NodeArray; + return list.some(property => { const name = property.name && getTextOfPropertyName(property.name); const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); @@ -10543,7 +10539,7 @@ namespace ts { // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. - function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean { + function isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike | JsxChild): boolean { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -10565,7 +10561,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return isContextSensitive((node).expression); case SyntaxKind.JsxAttributes: - return some((node).properties, isContextSensitive); + return some((node).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); case SyntaxKind.JsxAttribute: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. const { initializer } = node as JsxAttribute; @@ -11265,7 +11261,6 @@ namespace ts { let depth = 0; let expandingFlags = ExpandingFlags.None; let overflow = false; - let isIntersectionConstituent = false; Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); @@ -11368,7 +11363,7 @@ namespace ts { * * Ternary.Maybe if they are related with assumptions of other relationships, or * * Ternary.False if they are not related. */ - function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage): Ternary { + function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage, isApparentIntersectionConstituent?: boolean): Ternary { if (source.flags & TypeFlags.Literal && source.flags & TypeFlags.FreshLiteral) { source = (source).regularType; } @@ -11415,6 +11410,7 @@ namespace ts { if (relation === comparableRelation && !(target.flags & TypeFlags.Never) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; + const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); if (isObjectLiteralType(source) && source.flags & TypeFlags.FreshLiteral) { const discriminantType = target.flags & TypeFlags.Union ? findMatchingDiscriminantType(source, target as UnionType) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { @@ -11432,11 +11428,11 @@ namespace ts { } } - if (relation !== comparableRelation && !isIntersectionConstituent && + if (relation !== comparableRelation && !isApparentIntersectionConstituent && source.flags & (TypeFlags.Primitive | TypeFlags.Object | TypeFlags.Intersection) && source !== globalObjectType && target.flags & (TypeFlags.Object | TypeFlags.Intersection) && isWeakType(target) && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && - !hasCommonProperties(source, target)) { + !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { const calls = getSignaturesOfType(source, SignatureKind.Call); const constructs = getSignaturesOfType(source, SignatureKind.Construct); @@ -11453,8 +11449,7 @@ namespace ts { let result = Ternary.False; const saveErrorInfo = errorInfo; - const saveIsIntersectionConstituent = isIntersectionConstituent; - isIntersectionConstituent = false; + let isIntersectionConstituent = !!isApparentIntersectionConstituent; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), @@ -11469,7 +11464,7 @@ namespace ts { result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & TypeFlags.Primitive) && !(target.flags & TypeFlags.Primitive)); } else if (target.flags & TypeFlags.Intersection) { - isIntersectionConstituent = true; + isIntersectionConstituent = true; // set here to affect the following trio of checks result = typeRelatedToEachType(source, target as IntersectionType, reportErrors); } else if (source.flags & TypeFlags.Intersection) { @@ -11489,7 +11484,7 @@ namespace ts { result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } if (!result && (source.flags & TypeFlags.StructuredOrInstantiable || target.flags & TypeFlags.StructuredOrInstantiable)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } @@ -11506,14 +11501,12 @@ namespace ts { // 'string & number | number & number' which reduces to just 'number'. const constraint = getUnionConstraintOfIntersection(source, !!(target.flags & TypeFlags.Union)); if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { + if (result = isRelatedTo(constraint, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; } } } - isIntersectionConstituent = saveIsIntersectionConstituent; - if (!result && reportErrors) { if (source.flags & TypeFlags.Object && target.flags & TypeFlags.Primitive) { tryElaborateErrorsForPrimitivesAndObjects(source, target); @@ -11540,7 +11533,7 @@ namespace ts { let result: Ternary; const flags = source.flags & target.flags; if (flags & TypeFlags.Object || flags & TypeFlags.IndexedAccess || flags & TypeFlags.Conditional || flags & TypeFlags.Index || flags & TypeFlags.Substitution) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, /*isIntersectionConstituent*/ false); } if (flags & (TypeFlags.Union | TypeFlags.Intersection)) { if (result = eachTypeRelatedToSomeType(source, target)) { @@ -11567,15 +11560,16 @@ namespace ts { return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } for (const prop of getPropertiesOfObjectType(source)) { - if (!isPropertyFromSpread(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. if (!errorNode) return Debug.fail(); - if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode)) { + if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -11611,8 +11605,8 @@ namespace ts { return false; } - function isPropertyFromSpread(prop: Symbol, container: Symbol) { - return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent !== container.valueDeclaration; + function shouldCheckAsExcessProperty(prop: Symbol, container: Symbol) { + return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { @@ -11700,7 +11694,7 @@ namespace ts { let result = Ternary.True; const targetTypes = target.types; for (const targetType of targetTypes) { - const related = isRelatedTo(source, targetType, reportErrors); + const related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, /*isIntersectionConstituent*/ true); if (!related) { return Ternary.False; } @@ -11794,7 +11788,7 @@ namespace ts { // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function recursiveTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { if (overflow) { return Ternary.False; } @@ -11835,7 +11829,7 @@ namespace ts { const saveExpandingFlags = expandingFlags; if (!(expandingFlags & ExpandingFlags.Source) && isDeeplyNestedType(source, sourceStack, depth)) expandingFlags |= ExpandingFlags.Source; if (!(expandingFlags & ExpandingFlags.Target) && isDeeplyNestedType(target, targetStack, depth)) expandingFlags |= ExpandingFlags.Target; - const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors) : Ternary.Maybe; + const result = expandingFlags !== ExpandingFlags.Both ? structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) : Ternary.Maybe; expandingFlags = saveExpandingFlags; depth--; if (result) { @@ -11860,7 +11854,7 @@ namespace ts { return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); } - function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { + function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, isIntersectionConstituent: boolean): Ternary { const flags = source.flags & target.flags; if (relation === identityRelation && !(flags & TypeFlags.Object)) { if (flags & TypeFlags.Index) { @@ -11983,7 +11977,7 @@ namespace ts { } else { const instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors)) { + if (result = isRelatedTo(instantiated, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; return result; } @@ -12545,8 +12539,7 @@ namespace ts { return false; } - function hasCommonProperties(source: Type, target: Type) { - const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); + function hasCommonProperties(source: Type, target: Type, isComparingJsxAttributes: boolean) { for (const prop of getPropertiesOfType(source)) { if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { return true; @@ -16620,6 +16613,9 @@ namespace ts { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { + return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); + } return getTypeAtPosition(signature, argIndex); } @@ -16984,72 +16980,11 @@ namespace ts { // (as below) instead! return node.parent.contextualType; } - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - const valueType = checkExpression(node.tagName); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - - const isJs = isInJSFile(node); - return mapType(valueType, t => getJsxSignaturesParameterTypes(t, isJs, node)); + return getContextualTypeForArgumentAtIndex(node, 0); } - function getJsxSignaturesParameterTypes(valueType: Type, isJs: boolean, context: JsxOpeningLikeElement) { - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & TypeFlags.String) { - return anyType; - } - else if (valueType.flags & TypeFlags.StringLiteral) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (valueType).value; - const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); - if (indexSignatureType) { - return indexSignatureType; - } - } - return anyType; - } - - // Resolve the signatures, preferring constructor - let signatures = getSignaturesOfType(valueType, SignatureKind.Construct); - let ctor = true; - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, SignatureKind.Call); - ctor = false; - if (signatures.length === 0) { - // We found no signatures at all, which is an error - return errorType; - } - } - - const links = getNodeLinks(context); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(valueType); - const cachedResolved = links.resolvedSignatures.get(cacheKey); - if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { - signatures = cachedResolved; - } - else if (!cachedResolved) { - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); - links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); - } - - return getUnionType(map(signatures, ctor ? t => getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false) : t => getJsxPropsTypeFromCallSignature(t, context)), UnionReduction.None); + function getEffectiveFirstArgumentForJsxSignature(signature: Signature, node: JsxOpeningLikeElement) { + return isJsxStatelessFunctionReference(node) ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig: Signature, context: JsxOpeningLikeElement) { @@ -17067,23 +17002,42 @@ namespace ts { return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } + function getStaticTypeOfReferencedJsxConstructor(context: JsxOpeningLikeElement) { + if (isJsxIntrinsicIdentifier(context.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + const tagType = checkExpressionCached(context.tagName); + if (tagType.flags & TypeFlags.StringLiteral) { + const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType as StringLiteralType, context); + if (!result) { + return errorType; + } + const fakeSignature = createSignatureForJSXIntrinsic(context, result); + return getOrCreateTypeFromSignature(fakeSignature); + } + return tagType; + } + function getJsxManagedAttributesFromLocatedAttributes(context: JsxOpeningLikeElement, ns: Symbol, attributesType: Type) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + const ctorType = getStaticTypeOfReferencedJsxConstructor(context); if (length((declaredManagedType as GenericType).typeParameters) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJSFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJSFile(context)); return createTypeReference((declaredManagedType as GenericType), args); } else if (length(declaredManagedType.aliasTypeArguments) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); + const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol!, args); } } return attributesType; } - function getJsxPropsTypeFromClassType(sig: Signature, isJs: boolean, context: JsxOpeningLikeElement, reportErrors: boolean) { + function getJsxPropsTypeFromClassType(sig: Signature, context: JsxOpeningLikeElement) { const ns = getJsxNamespaceAt(context); const forcedLookupLocation = getJsxElementPropertiesName(ns); let attributesType = forcedLookupLocation === undefined @@ -17097,7 +17051,7 @@ namespace ts { if (!attributesType) { // There is no property named 'props' on this instance type - if (reportErrors && !!forcedLookupLocation && !!length(context.attributes.properties)) { + if (!!forcedLookupLocation && !!length(context.attributes.properties)) { error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation)); } return emptyObjectType; @@ -17118,7 +17072,7 @@ namespace ts { const hostClassType = getReturnTypeOfSignature(sig); apparentAttributesType = intersectTypes( typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context))) : intrinsicClassAttribs, apparentAttributesType ); @@ -17601,7 +17555,7 @@ namespace ts { } function checkJsxSelfClosingElementDeferred(node: JsxSelfClosingElement) { - checkJsxOpeningLikeElementOrOpeningFragment(node, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node); } function checkJsxSelfClosingElement(node: JsxSelfClosingElement, _checkMode: CheckMode | undefined): Type { @@ -17611,7 +17565,7 @@ namespace ts { function checkJsxElementDeferred(node: JsxElement) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, CheckMode.Normal); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { @@ -17620,6 +17574,8 @@ namespace ts { else { checkExpression(node.closingElement.tagName); } + + checkJsxChildren(node); } function checkJsxElement(node: JsxElement, _checkMode: CheckMode | undefined): Type { @@ -17628,8 +17584,8 @@ namespace ts { return getJsxElementTypeAt(node) || anyType; } - function checkJsxFragment(node: JsxFragment, checkMode: CheckMode | undefined): Type { - checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment, checkMode); + function checkJsxFragment(node: JsxFragment): Type { + checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment); if (compilerOptions.jsx === JsxEmit.React && (compilerOptions.jsxFactory || getSourceFileOfNode(node).pragmas.has("jsx"))) { error(node, compilerOptions.jsxFactory @@ -17637,6 +17593,7 @@ namespace ts { : Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } @@ -17710,7 +17667,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, exprType, attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -17768,7 +17725,8 @@ namespace ts { */ function createJsxAttributesType() { const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= (propagatingFlags |= TypeFlags.ContainsObjectLiteral); + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; + result.flags |= (propagatingFlags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag); result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.JsxAttributes; return result; } @@ -17847,57 +17805,6 @@ namespace ts { return links.resolvedSymbol; } - function instantiateJsxSignatures(node: JsxOpeningLikeElement, signatures: ReadonlyArray) { - const instantiatedSignatures = []; - let candidateForTypeArgumentError: Signature | undefined; - let hasTypeArgumentError: boolean = !!node.typeArguments; - for (const signature of signatures) { - if (signature.typeParameters) { - const isJavascript = isInJSFile(node); - const typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); - if (typeArgumentInstantiated) { - hasTypeArgumentError = false; - instantiatedSignatures.push(typeArgumentInstantiated); - } - else { - if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - candidateForTypeArgumentError = signature; - } - const inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? InferenceFlags.AnyDefault : InferenceFlags.None); - const typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); - } - } - else { - instantiatedSignatures.push(signature); - } - } - if (node.typeArguments && hasTypeArgumentError) { - if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); - } - // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine - else if (node.typeArguments.length !== 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); - } - } - return instantiatedSignatures; - } - - function getJsxSignatureTypeArgumentInstantiation(signature: Signature, node: JsxOpeningLikeElement, isJavascript: boolean, reportErrors = false) { - if (!node.typeArguments) { - return; - } - if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { - return; - } - const args = checkTypeArguments(signature, node.typeArguments, reportErrors); - if (!args) { - return; - } - return getSignatureInstantiation(signature, args, isJavascript); - } - function getJsxNamespaceAt(location: Node | undefined): Symbol { const links = location && getNodeLinks(location); if (links && links.jsxNamespace) { @@ -17973,193 +17880,24 @@ namespace ts { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType: Type | undefined): Type | undefined { - if (!propsType) { - return undefined; - } - if (propsType.flags & TypeFlags.Intersection) { - const propsApparentType: Type[] = []; - for (const t of (propsType).types) { - propsApparentType.push(getApparentType(t)); - } - return getIntersectionType(propsApparentType); - } - return getApparentType(propsType); - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return only attributes type of successfully resolved call signature. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - const callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined, /*isForSignatureHelp*/ false); - if (callSignature !== unknownSignature) { - const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); - let paramType = callReturnType && (callSignature!.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature!.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement: JsxOpeningLikeElement, elementType: Type, elemInstanceType: Type, elementClassType?: Type): Type | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - const jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - const candidatesOutArray: Signature[] = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray, /*isForSignatureHelp*/ false); - let result: Type | undefined; - let allMatchingAttributesType: Type | undefined; - for (const candidate of candidatesOutArray) { - const callReturnType = getReturnTypeOfSignature(candidate); - // TODO: GH#18217: callReturnType should always be defined... - let paramType: Type | undefined = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); - paramType = getApparentTypeOfJsxPropsType(paramType); - if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { - let shouldBeCandidate = true; - for (const attribute of openingLikeElement.attributes.properties) { - if (isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType!, attribute.name.escapedText)) { // TODO: GH#18217 - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== errorType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - - function getInstantiatedJsxSignatures(openingLikeElement: JsxOpeningLikeElement, elementType: Type, reportErrors?: boolean) { - const links = getNodeLinks(openingLikeElement); - if (!links.resolvedSignatures) { - links.resolvedSignatures = createMap(); - } - const cacheKey = "" + getTypeId(elementType); - if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { - return; - } - else if (links.resolvedSignatures.get(cacheKey)) { - return links.resolvedSignatures.get(cacheKey); - } - - links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + function getUninstantiatedJsxSignaturesOfType(elementType: Type) { // Resolve the signatures, preferring constructor let signatures = getSignaturesOfType(elementType, SignatureKind.Construct); if (signatures.length === 0) { // No construct signatures, try call signatures signatures = getSignaturesOfType(elementType, SignatureKind.Call); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - if (reportErrors) { - error(openingLikeElement.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(openingLikeElement.tagName)); - } - return; - } } - - // Instantiate in context of source type - const results = instantiateJsxSignatures(openingLikeElement, signatures); - links.resolvedSignatures.set(cacheKey, results); - return results; + return signatures; } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param sourceAttributesType Is the attributes type the user passed, and is used to create inferences in the target type if present - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement: JsxOpeningLikeElement, - shouldIncludeAllStatelessAttributesType: boolean, - elementType: Type, - elementClassType?: Type): Type { - - if (elementType.flags & TypeFlags.Union) { - const types = (elementType as UnionType).types; - return getUnionType(types.map(type => { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), UnionReduction.Subtype); - } - - // Shortcircuit any - if (isTypeAny(elementType)) { - return elementType; - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - else if (elementType.flags & TypeFlags.String) { - return anyType; - } - else if (elementType.flags & TypeFlags.StringLiteral) { + function getIntrinsicAttributesTypeFromStringLiteralType(type: StringLiteralType, location: Node): Type | undefined { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World - const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location); if (intrinsicElementsType !== errorType) { - const stringLiteralTypeName = (elementType).value; + const stringLiteralTypeName = type.value; const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { return getTypeOfSymbol(intrinsicProp); @@ -18168,37 +17906,26 @@ namespace ts { if (indexSignatureType) { return indexSignatureType; } - error(openingLikeElement, Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); + return undefined; } // If we need to report an error, we already done so here. So just return any to prevent any more error downstream return anyType; + } + + function checkJsxReturnAssignableToAppropriateBound(isSFC: boolean, elemInstanceType: Type, openingLikeElement: Node) { + if (isSFC) { + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + if (sfcReturnConstraint) { + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - - // Get the element instance type (the result of newing or invoking this tag) - - const instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); - if (!length(instantiatedSignatures)) { - return errorType; + else { + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (classConstraint) { + // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } - const elemInstanceType = getUnionType(instantiatedSignatures!.map(getReturnTypeOfSignature), UnionReduction.Subtype); - - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - const statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - - if (statelessAttributesType) { - return statelessAttributesType; - } - - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - - const isJs = isInJSFile(openingLikeElement); - return getUnionType(instantiatedSignatures!.map(sig => getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true))); } /** @@ -18224,57 +17951,6 @@ namespace ts { return links.resolvedJsxElementAttributesType; } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node: JsxOpeningLikeElement, shouldIncludeAllStatelessAttributesType: boolean): Type { - return resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, checkExpression(node.tagName), getJsxElementClassTypeAt(node)); - } - - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node: JsxOpeningLikeElement): Type { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { - const attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent as JsxOpeningElement); - const prop = getPropertyOfType(attributesType, attrib.name.escapedText); - return prop || unknownSymbol; - } - function getJsxElementClassTypeAt(location: Node): Type | undefined { const type = getJsxType(JsxNames.ElementClass, location); if (type === errorType) return undefined; @@ -18313,7 +17989,7 @@ namespace ts { } } - function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment, checkMode: CheckMode | undefined) { + function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { @@ -18338,10 +18014,8 @@ namespace ts { } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren((node as JsxOpeningFragment).parent); + const sig = getResolvedSignature(node as JsxOpeningLikeElement); + checkJsxReturnAssignableToAppropriateBound(isJsxStatelessFunctionReference(node as JsxOpeningLikeElement), getReturnTypeOfSignature(sig), node); } } @@ -18383,53 +18057,6 @@ namespace ts { return false; } - /** - * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. - * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement: JsxOpeningLikeElement, checkMode: CheckMode | undefined) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - - - // targetAttributesType is a type of an attribute from resolving tagName of an opening-like JSX element. - const targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - const sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); - - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - const isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (const attribute of openingLikeElement.attributes.properties) { - if (!isJsxAttribute(attribute)) { - continue; - } - const attrName = attribute.name; - const isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } - } - } - else if (!isSourceAttributeTypeAssignableToTarget) { - checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); - } - } - function checkJsxExpression(node: JsxExpression, checkMode?: CheckMode) { if (node.expression) { const type = checkExpression(node.expression, checkMode); @@ -19075,9 +18702,8 @@ namespace ts { return true; } - function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression { - // TODO: Also include tagged templates (https://github.com/Microsoft/TypeScript/issues/11947) - return isCallOrNewExpression(node); + function callLikeExpressionMayHaveTypeArguments(node: CallLikeExpression): node is CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement { + return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node); } function resolveUntypedCall(node: CallLikeExpression): Signature { @@ -19090,6 +18716,9 @@ namespace ts { if (node.kind === SyntaxKind.TaggedTemplateExpression) { checkExpression(node.template); } + else if (isJsxOpeningLikeElement(node)) { + checkExpression(node.attributes); + } else if (node.kind !== SyntaxKind.Decorator) { forEach((node).arguments, argument => { checkExpression(argument); @@ -19166,13 +18795,10 @@ namespace ts { } function hasCorrectArity(node: CallLikeExpression, args: ReadonlyArray, signature: Signature, signatureHelpTrailingComma = false) { - if (isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - let argCount: number; let callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments + let effectiveParameterCount = getParameterCount(signature); + let effectiveMinimumArguments = getMinArgumentCount(signature); if (node.kind === SyntaxKind.TaggedTemplateExpression) { argCount = args.length; @@ -19194,6 +18820,15 @@ namespace ts { else if (node.kind === SyntaxKind.Decorator) { argCount = getDecoratorArgumentCount(node, signature); } + else if (isJsxOpeningLikeElement(node)) { + callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + argCount = effectiveMinimumArguments === 0 ? args.length : 1; + effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type + effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked + } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' @@ -19214,12 +18849,13 @@ namespace ts { } // Too many arguments implies incorrect arity. - if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) { return false; } // If the call is incomplete, we should skip the lower bound check. - const hasEnoughArguments = argCount >= getMinArgumentCount(signature); + // JSX signatures can have extra parameters provided by the library which we don't check + const hasEnoughArguments = argCount >= effectiveMinimumArguments; return callIsIncomplete || hasEnoughArguments; } @@ -19258,15 +18894,10 @@ namespace ts { return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(signature: Signature, node: JsxOpeningLikeElement, context: InferenceContext): Type[] { - // Skip context sensitive pass - const skipContextParamType = getTypeAtPosition(signature, 0); - const checkAttrTypeSkipContextSensitive = checkExpressionWithContextualType(node.attributes, skipContextParamType, identityMapper); - inferTypes(context.inferences, checkAttrTypeSkipContextSensitive, skipContextParamType); + function inferJsxTypeArguments(node: JsxOpeningLikeElement, signature: Signature, excludeArgument: ReadonlyArray | undefined, context: InferenceContext): Type[] { + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - // Standard pass - const paramType = getTypeAtPosition(signature, 0); - const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context); + const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); @@ -19284,6 +18915,10 @@ namespace ts { } } + if (isJsxOpeningLikeElement(node)) { + return inferJsxTypeArguments(node, signature, excludeArgument, context); + } + // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the @@ -19403,6 +19038,14 @@ namespace ts { return typeArgumentTypes; } + function isJsxStatelessFunctionReference(node: JsxOpeningLikeElement) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return true; + } + const tagType = checkExpression(node.tagName); + return !length(getSignaturesOfType(getApparentType(tagType), SignatureKind.Construct)); + } + /** * Check if the given signature can possibly be a signature called by the JSX opening-like element. * @param node a JSX opening-like element we are trying to figure its call signature @@ -19410,31 +19053,13 @@ namespace ts { * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - - const callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - - const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map, reportErrors: boolean) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. - const paramType = getTypeAtPosition(signature, 0); + const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - const argProperties = getPropertiesOfType(attributesType); - for (const arg of argProperties) { - if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } function checkApplicableSignature( @@ -19445,7 +19070,7 @@ namespace ts { excludeArgument: boolean[] | undefined, reportErrors: boolean) { if (isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, reportErrors); } const thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { @@ -19523,7 +19148,7 @@ namespace ts { return getEffectiveDecoratorArguments(node); } if (isJsxOpeningLikeElement(node)) { - return node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; + return node.attributes.properties.length > 0 || (isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : emptyArray; } const args = node.arguments || emptyArray; const length = args.length; @@ -19674,6 +19299,7 @@ namespace ts { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const reportErrors = !candidatesOutArray; let typeArguments: NodeArray | undefined; @@ -19690,7 +19316,9 @@ namespace ts { // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { - diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + if (reportErrors) { + diagnostics.add(createDiagnosticForNode(node, Diagnostics.Call_target_does_not_contain_any_signatures)); + } return resolveErrorCall(node); } @@ -19766,34 +19394,32 @@ namespace ts { // no arguments excluded from assignability checks. // If candidate is undefined, it means that no candidates had a suitable arity. In that case, // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; + if (reportErrors) { + if (candidateForArgumentError) { + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForArgumentArityError) { - diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); - } - else if (candidateForTypeArgumentError) { - checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression).typeArguments!, /*reportErrors*/ true, fallbackError); - } - else { - const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); - if (signaturesWithCorrectTypeArgumentArity.length === 0) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); } - else if (!isDecorator) { - diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + else if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression | JsxOpeningLikeElement).typeArguments!, /*reportErrors*/ true, fallbackError); } - else if (fallbackError) { - diagnostics.add(createDiagnosticForNode(node, fallbackError)); + else { + const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); + } } } @@ -20368,6 +19994,74 @@ namespace ts { return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); } + function createSignatureForJSXIntrinsic(node: JsxOpeningLikeElement, result: Type): Signature { + const namespace = getJsxNamespaceAt(node); + const exports = namespace && getExportsOfSymbol(namespace); + // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration + // file would probably be preferable. + const typeSymbol = exports && getSymbol(exports, JsxNames.Element, SymbolFlags.Type); + const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, SymbolFlags.Type, node); + const declaration = createFunctionTypeNode(/*typeParameters*/ undefined, + [createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], + returnNode ? createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : createKeywordTypeNode(SyntaxKind.AnyKeyword) + ); + const parameterSymbol = createSymbol(SymbolFlags.FunctionScopedVariable, "props" as __String); + parameterSymbol.type = result; + return createSignature( + declaration, + /*typeParameters*/ undefined, + /*thisParameter*/ undefined, + [parameterSymbol], + typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, + /*returnTypePredicate*/ undefined, + 1, + /*hasRestparameter*/ false, + /*hasLiteralTypes*/ false + ); + } + + function resolveJsxOpeningLikeElement(node: JsxOpeningLikeElement, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { + if (isJsxIntrinsicIdentifier(node.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + const fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + return fakeSignature; + } + const exprTypes = checkExpression(node.tagName); + const apparentType = getApparentType(exprTypes); + if (apparentType === errorType) { + return resolveErrorCall(node); + } + + if (exprTypes.flags & TypeFlags.StringLiteral) { + const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes as StringLiteralType, node); + if (!intrinsicType) { + error(node, Diagnostics.Property_0_does_not_exist_on_type_1, (exprTypes as StringLiteralType).value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + const fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + if (exprTypes.flags & TypeFlags.String || isUntypedFunctionCall(exprTypes, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + + const signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + return resolveErrorCall(node); + } + + return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + } + /** * Sometimes, we have a decorator that could accept zero arguments, * but is receiving too many arguments as part of the decorator invocation. @@ -20380,26 +20074,6 @@ namespace ts { signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement: JsxOpeningLikeElement, elementType: Type, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature | undefined { - Debug.assert(!(elementType.flags & TypeFlags.Union)); - const callSignatures = elementType && getSignaturesOfType(elementType, SignatureKind.Call); - if (callSignatures && callSignatures.length > 0) { - return resolveCall(openingLikeElement, callSignatures, candidatesOutArray, isForSignatureHelp); - } - - return undefined; - } - function resolveSignature(node: CallLikeExpression, candidatesOutArray: Signature[] | undefined, isForSignatureHelp: boolean): Signature { switch (node.kind) { case SyntaxKind.CallExpression: @@ -20412,19 +20086,7 @@ namespace ts { return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - // This code-path is called by language service - const exprTypes = checkExpression(node.tagName); - return forEachType(exprTypes, exprType => { - const sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray, isForSignatureHelp); - if (sfcResult && sfcResult !== unknownSignature) { - return sfcResult; - } - const sigs = getInstantiatedJsxSignatures(node, exprType); - if (candidatesOutArray && length(sigs)) { - candidatesOutArray.push(...sigs!); - } - return length(sigs) ? sigs![0] : unknownSignature; - }) || unknownSignature; + return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); } throw Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -22606,7 +22268,7 @@ namespace ts { case SyntaxKind.JsxSelfClosingElement: return checkJsxSelfClosingElement(node, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node, checkMode); + return checkJsxFragment(node); case SyntaxKind.JsxAttributes: return checkJsxAttributes(node, checkMode); case SyntaxKind.JsxOpeningElement: @@ -27917,9 +27579,6 @@ namespace ts { const meaning = entityName.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === SyntaxKind.JsxAttribute) { - return getJsxAttributePropertySymbol(entityName.parent); - } if (entityName.parent.kind === SyntaxKind.TypePredicate) { return resolveEntityName(entityName, /*meaning*/ SymbolFlags.FunctionScopedVariable); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5763ab3eff0..f2c9238aace 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3103,8 +3103,6 @@ namespace ts { getExportsOfModule(moduleSymbol: Symbol): Symbol[]; /** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */ /* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; @@ -3171,7 +3169,7 @@ namespace ts { * True if `contextualType` should not be considered for completions because * e.g. it specifies `kind: "a"` and obj has `kind: "b"`. */ - /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression): boolean; + /* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean; /** * For a union, will include a property if it's defined in *any* of the member types. * So for `{ a } | { b }`, this will include both `a` and `b`. @@ -3769,7 +3767,6 @@ namespace ts { resolvedType?: Type; // Cached type of type node resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag resolvedSignature?: Signature; // Cached signature of signature node or call expression - resolvedSignatures?: Map; // Cached signatures of jsx node resolvedSymbol?: Symbol; // Cached name resolution result resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate diff --git a/src/services/completions.ts b/src/services/completions.ts index afadbf64f42..e2c7be0298a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1200,9 +1200,9 @@ namespace ts.Completions { function tryGetJsxCompletionSymbols(): GlobalsSearch { const jsxContainer = tryGetContainingJsxElement(contextToken); // Cursor is inside a JSX self-closing element or opening element - const attrsType = jsxContainer && typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); + const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); if (!attrsType) return GlobalsSearch.Continue; - symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer!.attributes.properties); + symbols = filterJsxAttributes(getPropertiesForObjectExpression(attrsType, jsxContainer!.attributes, typeChecker), jsxContainer!.attributes.properties); completionKind = CompletionKind.MemberLike; isNewIdentifierLocation = false; return GlobalsSearch.Success; @@ -2211,7 +2211,7 @@ namespace ts.Completions { return jsdoc && jsdoc.tags && (rangeContainsPosition(jsdoc, position) ? findLast(jsdoc.tags, tag => tag.pos < position) : undefined); } - function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression, checker: TypeChecker): Symbol[] { + function getPropertiesForObjectExpression(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes, checker: TypeChecker): Symbol[] { return contextualType.isUnion() ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(memberType => // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index d8306559986..a4cb439e623 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1941,7 +1941,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index fdd11aa3484..89007faa746 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1941,7 +1941,6 @@ declare namespace ts { /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; - getAllAttributesTypeFromJsxOpeningLikeElement(elementNode: JsxOpeningLikeElement): Type | undefined; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; diff --git a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt index cf999188ebc..6878372be8b 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt @@ -1,7 +1,8 @@ -tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. - Types of property 'children' are incompatible. - Type 'Element[]' is not assignable to type 'Element'. - Property 'type' is missing in type 'Element[]'. +tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'IntrinsicAttributes & SingleChildProp'. + Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. + Types of property 'children' are incompatible. + Type 'Element[]' is not assignable to type 'Element'. + Property 'type' is missing in type 'Element[]'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -48,7 +49,8 @@ tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Ele // Error let k5 = <>}/> + + // Component Class as Props + class MyButtonComponent extends React.Component<{},{}> { + } + + + + \ No newline at end of file diff --git a/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx b/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx new file mode 100644 index 00000000000..beb6844117f --- /dev/null +++ b/tests/cases/compiler/tsxNotUsingApparentTypeOfSFC.tsx @@ -0,0 +1,22 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; + +function test

(wrappedProps: P) { + let MySFC = function(props: P) { + return <>hello; + }; + class MyComponent extends React.Component

{ + render() { + return <>hello; + } + } + let x = ; // should error + let y = ; // should error + + let z = // should work + let q = // should work +} \ No newline at end of file diff --git a/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx b/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx new file mode 100644 index 00000000000..3e7e4d1a480 --- /dev/null +++ b/tests/cases/compiler/tsxSpreadDoesNotReportExcessProps.tsx @@ -0,0 +1,13 @@ +// @esModuleInterop: true +// @skipLibCheck: true +// @jsx: react +// @strict: true +/// + +import React from "react"; + +class MyComponent extends React.Component<{dataSource: number[], onClick?: any}, {}> { + render() { + return (

); + } +} diff --git a/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx b/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx new file mode 100644 index 00000000000..fcbf58e8873 --- /dev/null +++ b/tests/cases/compiler/tsxStatelessComponentDefaultProps.tsx @@ -0,0 +1,17 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; +interface Props { + text: string; +} + +function BackButton(_props: Props) { + return
+} +BackButton.defaultProps = { + text: 'Go Back', +}; +let a = diff --git a/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx b/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx index 01dedf4711e..92bb9f50e7c 100644 --- a/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx +++ b/tests/cases/conformance/jsx/tsxAttributeResolution15.tsx @@ -2,6 +2,7 @@ // @jsx: preserve // @noLib: true // @skipLibCheck: true +// @noImplicitAny: true // @libFiles: react.d.ts,lib.d.ts import React = require('react'); diff --git a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx index f32b367b718..ad8461bc1a7 100644 --- a/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx +++ b/tests/cases/conformance/jsx/tsxSpreadAttributesResolution2.tsx @@ -19,6 +19,9 @@ class Poisoned extends React.Component { const obj = {}; +// OK +; + // Error let p = ; let y = ; diff --git a/tests/cases/fourslash/tsxCompletion13.ts b/tests/cases/fourslash/tsxCompletion13.ts index 60964acbc55..9a79de927d2 100644 --- a/tests/cases/fourslash/tsxCompletion13.ts +++ b/tests/cases/fourslash/tsxCompletion13.ts @@ -2,7 +2,7 @@ //@Filename: file.tsx // @jsx: preserve -// @noLib: true +// @skipLibCheck: true //// declare module JSX { //// interface Element { } diff --git a/tests/cases/fourslash/tsxCompletionUnionElementType.ts b/tests/cases/fourslash/tsxCompletionUnionElementType.ts index 4a1044e20ac..5669f188f5b 100644 --- a/tests/cases/fourslash/tsxCompletionUnionElementType.ts +++ b/tests/cases/fourslash/tsxCompletionUnionElementType.ts @@ -2,7 +2,7 @@ //@Filename: file.tsx // @jsx: preserve -// @noLib: true +// @skipLibCheck: true //// declare module JSX { //// interface Element { } @@ -20,4 +20,4 @@ //// goTo.marker(); -verify.completionListContains("x", "(property) x: number | boolean"); \ No newline at end of file +verify.completionListIsEmpty(); \ No newline at end of file diff --git a/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts b/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts index a85c240e450..8541e3c391b 100644 --- a/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts +++ b/tests/cases/fourslash/tsxGoToDefinitionStatelessFunction2.ts @@ -31,10 +31,10 @@ //// let opt = <[|Main/*sixthTarget*/Button|] wrong />; verify.goToDefinition({ - firstTarget: "thirdSource", - secondTarget: "thirdSource", + firstTarget: "firstSource", + secondTarget: "firstSource", thirdTarget: "firstSource", fourthTarget: "firstSource", fifthTarget: "secondSource", - sixthTarget: "thirdSource" + sixthTarget: "firstSource" }); diff --git a/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts b/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts index 957b6b811e0..9e4cb4e1b1b 100644 --- a/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts +++ b/tests/cases/fourslash/tsxGoToDefinitionUnionElementType1.ts @@ -22,5 +22,5 @@ //// <[|SFC/*one*/Comp|] x /> verify.goToDefinition({ - "one": ["def", "pt1"], + "one": ["def"], }); diff --git a/tests/cases/fourslash/tsxQuickInfo7.ts b/tests/cases/fourslash/tsxQuickInfo7.ts index 72de1128049..8b3493dd8d4 100644 --- a/tests/cases/fourslash/tsxQuickInfo7.ts +++ b/tests/cases/fourslash/tsxQuickInfo7.ts @@ -4,9 +4,9 @@ // @jsx: preserve // @noLib: true -//// declare function OverloadComponent(): JSX.Element; //// declare function OverloadComponent(attr: {b: U, a?: string, "ignore-prop": boolean}): JSX.Element; //// declare function OverloadComponent(attr: {b: U, a: T}): JSX.Element; +//// declare function OverloadComponent(): JSX.Element; // effective argument type of `{}`, needs to be last //// function Baz(arg1: T, arg2: U) { //// let a0 = ; @@ -22,7 +22,7 @@ verify.quickInfos({ 1: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", 2: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", 3: "function OverloadComponent(attr: {\n b: string;\n a: boolean;\n}): any (+2 overloads)", - 4: "function OverloadComponent(attr: {\n b: number;\n a?: string;\n \"ignore-prop\": boolean;\n}): any (+2 overloads)", + 4: "function OverloadComponent(): any (+2 overloads)", // Subtype pass chooses this overload, since `a` is missing from the top overload, and `ignore-prop` is missing from the second (while T & {ignore-prop: true} is a proper subtype of `{}`) 5: "function OverloadComponent(): any (+2 overloads)", 6: "function OverloadComponent(attr: {\n b: string & number;\n a: boolean;\n}): any (+2 overloads)", 7: "function OverloadComponent(attr: {\n b: number & string;\n a: boolean;\n}): any (+2 overloads)", From 31f4053d3eb873560c217771c1a6c81635008503 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 17 Oct 2018 14:15:56 -0700 Subject: [PATCH 069/262] When contextual type doesnt find property, use the index signature from unit type(fix the incorrectly used union type to get the signature) Fixes #27949 --- src/compiler/checker.ts | 4 ++-- .../unionTypeWithIndexAndMethodSignature.js | 15 ++++++++++++ ...ionTypeWithIndexAndMethodSignature.symbols | 24 +++++++++++++++++++ ...unionTypeWithIndexAndMethodSignature.types | 23 ++++++++++++++++++ .../unionTypeWithIndexAndMethodSignature.ts | 9 +++++++ 5 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js create mode 100644 tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols create mode 100644 tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types create mode 100644 tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 604805545a4..8b6b71fa613 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16732,8 +16732,8 @@ namespace ts { return restType; } } - return isNumericLiteralName(name) && getIndexTypeOfContextualType(type, IndexKind.Number) || - getIndexTypeOfContextualType(type, IndexKind.String); + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, IndexKind.Number) || + getIndexTypeOfContextualType(t, IndexKind.String); } return undefined; }, /*noReductions*/ true); diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js new file mode 100644 index 00000000000..c78435ef0ce --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.js @@ -0,0 +1,15 @@ +//// [unionTypeWithIndexAndMethodSignature.ts] +interface Options { + m(x: number): void; + [key: string]: unknown; +} +declare function f(options: number | Options): void; +f({ + m(x) { }, +}); + +//// [unionTypeWithIndexAndMethodSignature.js] +"use strict"; +f({ + m: function (x) { } +}); diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols new file mode 100644 index 00000000000..3eaae1f320d --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.symbols @@ -0,0 +1,24 @@ +=== tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts === +interface Options { +>Options : Symbol(Options, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 0)) + + m(x: number): void; +>m : Symbol(Options.m, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 19)) +>x : Symbol(x, Decl(unionTypeWithIndexAndMethodSignature.ts, 1, 6)) + + [key: string]: unknown; +>key : Symbol(key, Decl(unionTypeWithIndexAndMethodSignature.ts, 2, 5)) +} +declare function f(options: number | Options): void; +>f : Symbol(f, Decl(unionTypeWithIndexAndMethodSignature.ts, 3, 1)) +>options : Symbol(options, Decl(unionTypeWithIndexAndMethodSignature.ts, 4, 19)) +>Options : Symbol(Options, Decl(unionTypeWithIndexAndMethodSignature.ts, 0, 0)) + +f({ +>f : Symbol(f, Decl(unionTypeWithIndexAndMethodSignature.ts, 3, 1)) + + m(x) { }, +>m : Symbol(m, Decl(unionTypeWithIndexAndMethodSignature.ts, 5, 3)) +>x : Symbol(x, Decl(unionTypeWithIndexAndMethodSignature.ts, 6, 6)) + +}); diff --git a/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types new file mode 100644 index 00000000000..76607a40167 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndMethodSignature.types @@ -0,0 +1,23 @@ +=== tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts === +interface Options { + m(x: number): void; +>m : (x: number) => void +>x : number + + [key: string]: unknown; +>key : string +} +declare function f(options: number | Options): void; +>f : (options: number | Options) => void +>options : number | Options + +f({ +>f({ m(x) { },}) : void +>f : (options: number | Options) => void +>{ m(x) { },} : { m(x: number): void; } + + m(x) { }, +>m : (x: number) => void +>x : number + +}); diff --git a/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts b/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts new file mode 100644 index 00000000000..f8504b3ce22 --- /dev/null +++ b/tests/cases/compiler/unionTypeWithIndexAndMethodSignature.ts @@ -0,0 +1,9 @@ +// @strict: true +interface Options { + m(x: number): void; + [key: string]: unknown; +} +declare function f(options: number | Options): void; +f({ + m(x) { }, +}); \ No newline at end of file From 9554f09d0924c477f120fd331b4f3b37551c3345 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 17 Oct 2018 14:44:39 -0700 Subject: [PATCH 070/262] Add ability to infer to the simplified form of a type variable (#27953) * Add ability to infer to the simplified form of a type variable * Add test --- src/compiler/checker.ts | 11 +++ ...edIndexesOfIntersectionsAreInferencable.js | 33 +++++++++ ...exesOfIntersectionsAreInferencable.symbols | 74 +++++++++++++++++++ ...ndexesOfIntersectionsAreInferencable.types | 49 ++++++++++++ ...edIndexesOfIntersectionsAreInferencable.ts | 22 ++++++ 5 files changed, 189 insertions(+) create mode 100644 tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.js create mode 100644 tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.symbols create mode 100644 tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.types create mode 100644 tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 604805545a4..b8f20f5b9ad 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13644,6 +13644,17 @@ namespace ts { } return; } + else { + // 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); + if (simplified !== target) { + const key = source.id + "," + simplified.id; + if (!visited || !visited.get(key)) { + (visited || (visited = createMap())).set(key, true); + inferFromTypes(source, simplified); + } + } + } } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments diff --git a/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.js b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.js new file mode 100644 index 00000000000..46e537bc64a --- /dev/null +++ b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.js @@ -0,0 +1,33 @@ +//// [complicatedIndexesOfIntersectionsAreInferencable.ts] +interface FormikConfig { + initialValues: Values; + validate?: (props: Values) => void; + validateOnChange?: boolean; +} + +declare function Func( + x: (string extends "validate" | "initialValues" | keyof ExtraProps + ? Readonly & ExtraProps> + : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> + & Partial & ExtraProps>, "validateOnChange" | Extract>>) +): void; + +Func({ + initialValues: { + foo: "" + }, + validate: props => { + props.foo; + } +}); + +//// [complicatedIndexesOfIntersectionsAreInferencable.js] +"use strict"; +Func({ + initialValues: { + foo: "" + }, + validate: function (props) { + props.foo; + } +}); diff --git a/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.symbols b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.symbols new file mode 100644 index 00000000000..d6ad3f1c3cd --- /dev/null +++ b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.symbols @@ -0,0 +1,74 @@ +=== tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts === +interface FormikConfig { +>FormikConfig : Symbol(FormikConfig, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 0)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 23)) + + initialValues: Values; +>initialValues : Symbol(FormikConfig.initialValues, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 32)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 23)) + + validate?: (props: Values) => void; +>validate : Symbol(FormikConfig.validate, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 1, 26)) +>props : Symbol(props, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 2, 16)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 23)) + + validateOnChange?: boolean; +>validateOnChange : Symbol(FormikConfig.validateOnChange, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 2, 39)) +} + +declare function Func( +>Func : Symbol(Func, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 4, 1)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 22)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) + + x: (string extends "validate" | "initialValues" | keyof ExtraProps +>x : Symbol(x, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 56)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) + + ? Readonly & ExtraProps> +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>FormikConfig : Symbol(FormikConfig, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 0)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 22)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) + + : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>FormikConfig : Symbol(FormikConfig, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 0)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 22)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) + + & Partial & ExtraProps>, "validateOnChange" | Extract>>) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>FormikConfig : Symbol(FormikConfig, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 0, 0)) +>Values : Symbol(Values, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 22)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) +>Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) +>ExtraProps : Symbol(ExtraProps, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 6, 38)) + +): void; + +Func({ +>Func : Symbol(Func, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 4, 1)) + + initialValues: { +>initialValues : Symbol(initialValues, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 13, 6)) + + foo: "" +>foo : Symbol(foo, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 14, 20)) + + }, + validate: props => { +>validate : Symbol(validate, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 16, 6)) +>props : Symbol(props, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 17, 13)) + + props.foo; +>props.foo : Symbol(foo, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 14, 20)) +>props : Symbol(props, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 17, 13)) +>foo : Symbol(foo, Decl(complicatedIndexesOfIntersectionsAreInferencable.ts, 14, 20)) + } +}); diff --git a/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.types b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.types new file mode 100644 index 00000000000..64511cb9df2 --- /dev/null +++ b/tests/baselines/reference/complicatedIndexesOfIntersectionsAreInferencable.types @@ -0,0 +1,49 @@ +=== tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts === +interface FormikConfig { + initialValues: Values; +>initialValues : Values + + validate?: (props: Values) => void; +>validate : ((props: Values) => void) | undefined +>props : Values + + validateOnChange?: boolean; +>validateOnChange : boolean | undefined +} + +declare function Func( +>Func : (x: string extends "validate" | "initialValues" | keyof ExtraProps ? Readonly & ExtraProps> : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> & Partial & ExtraProps>, "validateOnChange" | Extract>>) => void + + x: (string extends "validate" | "initialValues" | keyof ExtraProps +>x : string extends "validate" | "initialValues" | keyof ExtraProps ? Readonly & ExtraProps> : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> & Partial & ExtraProps>, "validateOnChange" | Extract>> + + ? Readonly & ExtraProps> + : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> + & Partial & ExtraProps>, "validateOnChange" | Extract>>) +): void; + +Func({ +>Func({ initialValues: { foo: "" }, validate: props => { props.foo; }}) : void +>Func : (x: string extends "validate" | "initialValues" | keyof ExtraProps ? Readonly & ExtraProps> : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> & Partial & ExtraProps>, "validateOnChange" | Extract>>) => void +>{ initialValues: { foo: "" }, validate: props => { props.foo; }} : { initialValues: { foo: string; }; validate: (props: { foo: string; }) => void; } + + initialValues: { +>initialValues : { foo: string; } +>{ foo: "" } : { foo: string; } + + foo: "" +>foo : string +>"" : "" + + }, + validate: props => { +>validate : (props: { foo: string; }) => void +>props => { props.foo; } : (props: { foo: string; }) => void +>props : { foo: string; } + + props.foo; +>props.foo : string +>props : { foo: string; } +>foo : string + } +}); diff --git a/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts b/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts new file mode 100644 index 00000000000..650d8886cae --- /dev/null +++ b/tests/cases/compiler/complicatedIndexesOfIntersectionsAreInferencable.ts @@ -0,0 +1,22 @@ +// @strict: true +interface FormikConfig { + initialValues: Values; + validate?: (props: Values) => void; + validateOnChange?: boolean; +} + +declare function Func( + x: (string extends "validate" | "initialValues" | keyof ExtraProps + ? Readonly & ExtraProps> + : Pick & ExtraProps>, "validate" | "initialValues" | Exclude> + & Partial & ExtraProps>, "validateOnChange" | Extract>>) +): void; + +Func({ + initialValues: { + foo: "" + }, + validate: props => { + props.foo; + } +}); \ No newline at end of file From e58371e03aaf7e3435d12fcfd04751588ea7ed7d Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 17 Oct 2018 15:17:21 -0700 Subject: [PATCH 071/262] Remove now unnessesary casts (#27954) --- src/compiler/commandLineParser.ts | 10 +++++----- src/harness/harness.ts | 2 +- src/services/getEditsForFileRename.ts | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 56767b9420b..160debf72e6 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1013,7 +1013,7 @@ namespace ts { i++; break; case "list": - const result = parseListTypeOption(opt, args[i], errors); + const result = parseListTypeOption(opt, args[i], errors); options[opt.name] = result || []; if (result) { i++; @@ -1667,7 +1667,7 @@ namespace ts { return undefined; } else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption((optionDefinition).element); + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); } else { return (optionDefinition).type; @@ -1731,7 +1731,7 @@ namespace ts { case "object": return {}; default: - return (option as CommandLineOptionOfCustomType).type.keys().next().value; + return option.type.keys().next().value; } } @@ -2338,7 +2338,7 @@ namespace ts { function normalizeOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (isNullOrUndefined(value)) return undefined; if (option.type === "list") { - const listOption = option; + const listOption = option; if (listOption.element.isFilePath || !isString(listOption.element.type)) { return filter(map(value, v => normalizeOptionValue(listOption.element, basePath, v)), v => !!v); } @@ -2745,7 +2745,7 @@ namespace ts { case "boolean": return typeof value === "boolean" ? value : ""; case "list": - const elementType = (option as CommandLineOptionOfListType).element; + const elementType = option.element; return isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : ""; default: return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 23ee10d7412..5896ff3a782 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1159,7 +1159,7 @@ namespace Harness { } // If not a primitive, the possible types are specified in what is effectively a map of options. case "list": - return ts.parseListTypeOption(option, value, errors); + return ts.parseListTypeOption(option, value, errors); default: return ts.parseCustomTypeOption(option, value, errors); } diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index a18fab4766f..5872ade5652 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -72,7 +72,7 @@ namespace ts { case "compilerOptions": forEachProperty(property.initializer, (property, propertyName) => { const option = getOptionFromName(propertyName); - if (option && (option.isFilePath || option.type === "list" && (option as CommandLineOptionOfListType).element.isFilePath)) { + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { updatePaths(property); } else if (propertyName === "paths") { From b1fbff8b980cc12b29fcbd552948de4e09b6a623 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Thu, 18 Oct 2018 00:31:09 -0700 Subject: [PATCH 072/262] Add broken test for issue #27854 --- src/testRunner/unittests/transform.ts | 23 +++++++++++++++++++ .../transformsCorrectly.issue27854.js | 3 +++ 2 files changed, 26 insertions(+) create mode 100644 tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index e975e10c09c..7ed6e9760fd 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -40,6 +40,17 @@ namespace ts { return (file: SourceFile) => file; } + function replaceIdentifiersNamedOldNameWithNewName2(context: TransformationContext) { + const visitor: Visitor = (node) => { + if (isIdentifier(node) && node.text === "oldName") { + return createIdentifier("newName"); + } + + return visitEachChild(node, visitor, context); + } + return (node: SourceFile) => visitNode(node, visitor); + } + function transformSourceFile(sourceText: string, transformers: TransformerFactory[]) { const transformed = transform(createSourceFile("source.ts", sourceText, ScriptTarget.ES2015), transformers); const printer = createPrinter({ newLine: NewLineKind.CarriageReturnLineFeed }, { @@ -81,6 +92,18 @@ namespace ts { }).outputText; }); + testBaseline("issue27854", () => { + return transpileModule(`oldName<{ a: string; }>\` ... \`;`, { + transformers: { + before: [replaceIdentifiersNamedOldNameWithNewName2] + }, + compilerOptions: { + newLine: NewLineKind.CarriageReturnLineFeed, + target: ts.ScriptTarget.Latest + } + }).outputText; + }); + testBaseline("rewrittenNamespace", () => { return transpileModule(`namespace Reflect { const x = 1; }`, { transformers: { diff --git a/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js b/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js new file mode 100644 index 00000000000..5afec3fccae --- /dev/null +++ b/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js @@ -0,0 +1,3 @@ +newName<{ + a: string; +}> ` ... `; From b2cbbbd1d37cdb602483f0d6b908b0152c05540e Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Thu, 18 Oct 2018 01:34:04 -0700 Subject: [PATCH 073/262] Fix bug in reduceEachChild (fixes #27854) - add reducing of type arguments in tagged template expression --- src/compiler/visitor.ts | 1 + src/testRunner/unittests/transform.ts | 5 ++--- .../reference/transformApi/transformsCorrectly.issue27854.js | 4 +--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index 2cfb469f152..fbed806a8ad 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -1111,6 +1111,7 @@ namespace ts { case SyntaxKind.TaggedTemplateExpression: result = reduceNode((node).tag, cbNode, result); + result = reduceNodes((node).typeArguments, cbNodes, result); result = reduceNode((node).template, cbNode, result); break; diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index 7ed6e9760fd..f219fb6c683 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -45,9 +45,8 @@ namespace ts { if (isIdentifier(node) && node.text === "oldName") { return createIdentifier("newName"); } - return visitEachChild(node, visitor, context); - } + }; return (node: SourceFile) => visitNode(node, visitor); } @@ -99,7 +98,7 @@ namespace ts { }, compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed, - target: ts.ScriptTarget.Latest + target: ScriptTarget.Latest } }).outputText; }); diff --git a/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js b/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js index 5afec3fccae..d1948143086 100644 --- a/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js +++ b/tests/baselines/reference/transformApi/transformsCorrectly.issue27854.js @@ -1,3 +1 @@ -newName<{ - a: string; -}> ` ... `; +newName ` ... `; From b930d5730fdf0b84cb211ea0dbd7a3c1a39bebb3 Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Thu, 18 Oct 2018 01:36:05 -0700 Subject: [PATCH 074/262] Change cast to the proper type --- src/compiler/visitor.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index fbed806a8ad..b2ab3b19b47 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -1111,7 +1111,7 @@ namespace ts { case SyntaxKind.TaggedTemplateExpression: result = reduceNode((node).tag, cbNode, result); - result = reduceNodes((node).typeArguments, cbNodes, result); + result = reduceNodes((node).typeArguments, cbNodes, result); result = reduceNode((node).template, cbNode, result); break; From d352b8c2c769358330e265933f7dda49cd083ffc Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 18 Oct 2018 12:04:14 -0700 Subject: [PATCH 075/262] Use reference map from declaration file as exported map to handle deep import semantic diagnostics invalidation Fixes #27973 --- src/compiler/builderState.ts | 5 +++ src/testRunner/unittests/tscWatchMode.ts | 43 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 1689733fac6..7cd67d99f72 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -292,6 +292,11 @@ namespace ts.BuilderState { let latestSignature: string; if (sourceFile.isDeclarationFile) { latestSignature = sourceFile.version; + if (exportedModulesMapCache && latestSignature !== prevSignature) { + // All the references in this file are exported + const references = state.referencedMap ? state.referencedMap.get(sourceFile.path) : undefined; + exportedModulesMapCache.set(sourceFile.path, references || false); + } } else { const emitOutput = getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index 7678bfe0625..55fc32d4bde 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1350,6 +1350,49 @@ export class B assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); }); + it("updates errors when deep import through declaration file changes", () => { + const currentDirectory = "/user/username/projects/myproject"; + const aFile: File = { + path: `${currentDirectory}/a.ts`, + content: `import {B} from './b'; +declare var console: any; +let b = new B(); +console.log(b.c.d);` + }; + const bFile: File = { + path: `${currentDirectory}/b.d.ts`, + content: `import {C} from './c'; +export class B +{ + c: C; +}` + }; + const cFile: File = { + path: `${currentDirectory}/c.d.ts`, + content: `export class C +{ + d: number; +}` + }; + const config: File = { + path: `${currentDirectory}/tsconfig.json`, + content: `{}` + }; + const files = [aFile, bFile, cFile, config, libFile]; + const host = createWatchedSystem(files, { currentDirectory }); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkProgramActualFiles(watch(), [aFile.path, bFile.path, cFile.path, libFile.path]); + checkOutputErrorsInitial(host, emptyArray); + const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); + host.writeFile(cFile.path, cFile.content.replace("d", "d2")); + host.runQueuedTimeoutCallbacks(); + checkOutputErrorsIncremental(host, [ + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("d"), 1, Diagnostics.Property_0_does_not_exist_on_type_1, "d", "C") + ]); + // File a need not be rewritten + assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + }); + it("updates errors when strictNullChecks changes", () => { const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { From a3c22683ab7462dc71935b3219098a3a3c98c9ea Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 18 Oct 2018 14:27:21 -0700 Subject: [PATCH 076/262] findAllRefs: Fix bug when symbol.declarations is undefined (#27977) --- src/services/findAllReferences.ts | 2 +- .../fourslash/findAllRefsMappedType_nonHomomorphic.ts | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/findAllRefsMappedType_nonHomomorphic.ts diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 9fde734049c..2a3e4de87b1 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -143,7 +143,7 @@ namespace ts.FindAllReferences { function getDefinitionKindAndDisplayParts(symbol: Symbol, checker: TypeChecker, node: Node): { displayParts: SymbolDisplayPart[], kind: ScriptElementKind } { const meaning = Core.getIntersectingMeaningFromDeclarations(node, symbol); - const enclosingDeclaration = firstOrUndefined(symbol.declarations) || node; + const enclosingDeclaration = symbol.declarations && firstOrUndefined(symbol.declarations) || node; const { displayParts, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; diff --git a/tests/cases/fourslash/findAllRefsMappedType_nonHomomorphic.ts b/tests/cases/fourslash/findAllRefsMappedType_nonHomomorphic.ts new file mode 100644 index 00000000000..4dca721d614 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsMappedType_nonHomomorphic.ts @@ -0,0 +1,10 @@ +/// + +// @strict: true + +////function f(x: { [K in "m"]: number; }) { +//// x.[|m|]; +//// x.[|m|] +////} + +verify.singleReferenceGroup("(property) m: number"); From 8779d4ca888426b58c2c2d76626137c2d6976721 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 19 Oct 2018 09:23:05 -0700 Subject: [PATCH 077/262] Fix JS merge crashes from lovefield (#27989) 1. Merge enum with expando. 2. Merge enum member with property assignment. 3. Merge interface-declared method declaration with prototype-property-assignment method declaration. The reason that the enum merges crash is that getTypeOfSymbol assumes that symbol flags are (basically) mutually exclusive. This assumption is shredded, badly, for JS merges. One fix is to drop the assumption of exclusivity and instead order cases by least to most likely. This has the highest chance of working, but is also slow, since you would prefer to order cases by most likely *first*, not *last*. The other fix, which is what I did here, is to add a last-chance re-dispatch at the bottom of `getTypeOfVariableOrParameterOrPropertyWorker`. This dispatch uses the valueDeclaration instead of the symbol flags. --- src/compiler/checker.ts | 11 ++++ .../reference/enumMergeWithExpando.errors.txt | 19 ++++++ .../reference/enumMergeWithExpando.symbols | 31 ++++++++++ .../reference/enumMergeWithExpando.types | 37 +++++++++++ ...ignmentMergeWithInterfaceMethod.errors.txt | 40 ++++++++++++ ...AssignmentMergeWithInterfaceMethod.symbols | 61 +++++++++++++++++++ ...tyAssignmentMergeWithInterfaceMethod.types | 53 ++++++++++++++++ .../conformance/salsa/enumMergeWithExpando.ts | 13 ++++ ...pertyAssignmentMergeWithInterfaceMethod.ts | 22 +++++++ 9 files changed, 287 insertions(+) create mode 100644 tests/baselines/reference/enumMergeWithExpando.errors.txt create mode 100644 tests/baselines/reference/enumMergeWithExpando.symbols create mode 100644 tests/baselines/reference/enumMergeWithExpando.types create mode 100644 tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.errors.txt create mode 100644 tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.symbols create mode 100644 tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.types create mode 100644 tests/cases/conformance/salsa/enumMergeWithExpando.ts create mode 100644 tests/cases/conformance/salsa/prototypePropertyAssignmentMergeWithInterfaceMethod.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d85a46bd74f..df817c3a795 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2214,6 +2214,9 @@ namespace ts { function getDeclarationOfJSPrototypeContainer(symbol: Symbol) { const decl = symbol.parent!.valueDeclaration; + if (!decl) { + return undefined; + } const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : undefined; @@ -5241,6 +5244,14 @@ namespace ts { || isBindingElement(declaration)) { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); } + // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive. + // Re-dispatch based on valueDeclaration.kind instead. + else if (isEnumDeclaration(declaration)) { + type = getTypeOfFuncClassEnumModule(symbol); + } + else if (isEnumMember(declaration)) { + type = getTypeOfEnumMember(symbol); + } else { return Debug.fail("Unhandled declaration kind! " + Debug.showSyntaxKind(declaration) + " for " + Debug.showSymbol(symbol)); } diff --git a/tests/baselines/reference/enumMergeWithExpando.errors.txt b/tests/baselines/reference/enumMergeWithExpando.errors.txt new file mode 100644 index 00000000000..7911206650c --- /dev/null +++ b/tests/baselines/reference/enumMergeWithExpando.errors.txt @@ -0,0 +1,19 @@ +tests/cases/conformance/salsa/enums.js(2,10): error TS2540: Cannot assign to 'DESC' because it is a constant or a read-only property. +tests/cases/conformance/salsa/enums.js(3,10): error TS2540: Cannot assign to 'ASC' because it is a constant or a read-only property. + + +==== tests/cases/conformance/salsa/lovefield-ts.d.ts (0 errors) ==== + // bug #27352, crashes from github.com/google/lovefield + declare namespace lf { + export enum Order { ASC, DESC } + } + +==== tests/cases/conformance/salsa/enums.js (2 errors) ==== + lf.Order = {} + lf.Order.DESC = 0; + ~~~~ +!!! error TS2540: Cannot assign to 'DESC' because it is a constant or a read-only property. + lf.Order.ASC = 1; + ~~~ +!!! error TS2540: Cannot assign to 'ASC' because it is a constant or a read-only property. + \ No newline at end of file diff --git a/tests/baselines/reference/enumMergeWithExpando.symbols b/tests/baselines/reference/enumMergeWithExpando.symbols new file mode 100644 index 00000000000..854bf6b5169 --- /dev/null +++ b/tests/baselines/reference/enumMergeWithExpando.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/salsa/lovefield-ts.d.ts === +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(enums.js, 0, 0), Decl(enums.js, 0, 13)) + + export enum Order { ASC, DESC } +>Order : Symbol(Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>ASC : Symbol(Order.ASC, Decl(lovefield-ts.d.ts, 2, 23), Decl(enums.js, 1, 18)) +>DESC : Symbol(Order.DESC, Decl(lovefield-ts.d.ts, 2, 28), Decl(enums.js, 0, 13)) +} + +=== tests/cases/conformance/salsa/enums.js === +lf.Order = {} +>lf.Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(enums.js, 0, 0), Decl(enums.js, 0, 13)) +>Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) + +lf.Order.DESC = 0; +>lf.Order.DESC : Symbol(lf.Order.DESC, Decl(lovefield-ts.d.ts, 2, 28), Decl(enums.js, 0, 13)) +>lf.Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(enums.js, 0, 0), Decl(enums.js, 0, 13)) +>Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>DESC : Symbol(lf.Order.DESC, Decl(lovefield-ts.d.ts, 2, 28), Decl(enums.js, 0, 13)) + +lf.Order.ASC = 1; +>lf.Order.ASC : Symbol(lf.Order.ASC, Decl(lovefield-ts.d.ts, 2, 23), Decl(enums.js, 1, 18)) +>lf.Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(enums.js, 0, 0), Decl(enums.js, 0, 13)) +>Order : Symbol(lf.Order, Decl(lovefield-ts.d.ts, 1, 22), Decl(enums.js, 0, 0), Decl(enums.js, 1, 3)) +>ASC : Symbol(lf.Order.ASC, Decl(lovefield-ts.d.ts, 2, 23), Decl(enums.js, 1, 18)) + diff --git a/tests/baselines/reference/enumMergeWithExpando.types b/tests/baselines/reference/enumMergeWithExpando.types new file mode 100644 index 00000000000..0e5925782ac --- /dev/null +++ b/tests/baselines/reference/enumMergeWithExpando.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/salsa/lovefield-ts.d.ts === +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { +>lf : typeof lf + + export enum Order { ASC, DESC } +>Order : Order +>ASC : Order +>DESC : Order +} + +=== tests/cases/conformance/salsa/enums.js === +lf.Order = {} +>lf.Order = {} : typeof lf.Order +>lf.Order : typeof lf.Order +>lf : typeof lf +>Order : typeof lf.Order +>{} : {} + +lf.Order.DESC = 0; +>lf.Order.DESC = 0 : 0 +>lf.Order.DESC : any +>lf.Order : typeof lf.Order +>lf : typeof lf +>Order : typeof lf.Order +>DESC : any +>0 : 0 + +lf.Order.ASC = 1; +>lf.Order.ASC = 1 : 1 +>lf.Order.ASC : any +>lf.Order : typeof lf.Order +>lf : typeof lf +>Order : typeof lf.Order +>ASC : any +>1 : 1 + diff --git a/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.errors.txt b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.errors.txt new file mode 100644 index 00000000000..eeb83673ab3 --- /dev/null +++ b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.errors.txt @@ -0,0 +1,40 @@ +tests/cases/conformance/salsa/lovefield-ts.d.ts(4,19): error TS2503: Cannot find namespace 'query'. +tests/cases/conformance/salsa/lovefield-ts.d.ts(5,24): error TS2503: Cannot find namespace 'schema'. +tests/cases/conformance/salsa/lovefield-ts.d.ts(7,25): error TS2503: Cannot find namespace 'query'. +tests/cases/conformance/salsa/lovefield-ts.d.ts(9,14): error TS2304: Cannot find name 'TransactionStats'. +tests/cases/conformance/salsa/lovefield.js(3,23): error TS2694: Namespace 'lf' has no exported member 'schema'. +tests/cases/conformance/salsa/lovefield.js(4,14): error TS2304: Cannot find name 'IThenable'. + + +==== tests/cases/conformance/salsa/lovefield-ts.d.ts (4 errors) ==== + // bug #27352, crashes from github.com/google/lovefield + declare namespace lf { + export interface Transaction { + attach(query: query.Builder): Promise> + ~~~~~ +!!! error TS2503: Cannot find namespace 'query'. + begin(scope: Array): Promise + ~~~~~~ +!!! error TS2503: Cannot find namespace 'schema'. + commit(): Promise + exec(queries: Array): Promise>> + ~~~~~ +!!! error TS2503: Cannot find namespace 'query'. + rollback(): Promise + stats(): TransactionStats + ~~~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'TransactionStats'. + } + } +==== tests/cases/conformance/salsa/lovefield.js (2 errors) ==== + lf.Transaction = function() {}; + /** + * @param {!Array} scope + ~~~~~~ +!!! error TS2694: Namespace 'lf' has no exported member 'schema'. + * @return {!IThenable} + ~~~~~~~~~ +!!! error TS2304: Cannot find name 'IThenable'. + */ + lf.Transaction.prototype.begin = function(scope) {}; + \ No newline at end of file diff --git a/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.symbols b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.symbols new file mode 100644 index 00000000000..4b27813082e --- /dev/null +++ b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/salsa/lovefield-ts.d.ts === +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(lovefield.js, 0, 0)) + + export interface Transaction { +>Transaction : Symbol(Transaction, Decl(lovefield-ts.d.ts, 1, 22), Decl(lovefield.js, 0, 0)) + + attach(query: query.Builder): Promise> +>attach : Symbol(Transaction.attach, Decl(lovefield-ts.d.ts, 2, 32)) +>query : Symbol(query, Decl(lovefield-ts.d.ts, 3, 11)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + begin(scope: Array): Promise +>begin : Symbol(Transaction.begin, Decl(lovefield-ts.d.ts, 3, 56), Decl(lovefield.js, 0, 31)) +>scope : Symbol(scope, Decl(lovefield-ts.d.ts, 4, 10)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) + + commit(): Promise +>commit : Symbol(Transaction.commit, Decl(lovefield-ts.d.ts, 4, 52)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) + + exec(queries: Array): Promise>> +>exec : Symbol(Transaction.exec, Decl(lovefield-ts.d.ts, 5, 27)) +>queries : Symbol(queries, Decl(lovefield-ts.d.ts, 6, 9)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + rollback(): Promise +>rollback : Symbol(Transaction.rollback, Decl(lovefield-ts.d.ts, 6, 70)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) + + stats(): TransactionStats +>stats : Symbol(Transaction.stats, Decl(lovefield-ts.d.ts, 7, 29)) + } +} +=== tests/cases/conformance/salsa/lovefield.js === +lf.Transaction = function() {}; +>lf.Transaction : Symbol(lf.Transaction, Decl(lovefield-ts.d.ts, 1, 22), Decl(lovefield.js, 0, 0)) +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(lovefield.js, 0, 0)) +>Transaction : Symbol(lf.Transaction, Decl(lovefield-ts.d.ts, 1, 22), Decl(lovefield.js, 0, 0)) + +/** + * @param {!Array} scope + * @return {!IThenable} + */ +lf.Transaction.prototype.begin = function(scope) {}; +>lf.Transaction.prototype : Symbol(lf.Transaction.begin, Decl(lovefield-ts.d.ts, 3, 56), Decl(lovefield.js, 0, 31)) +>lf.Transaction : Symbol(lf.Transaction, Decl(lovefield-ts.d.ts, 1, 22), Decl(lovefield.js, 0, 0)) +>lf : Symbol(lf, Decl(lovefield-ts.d.ts, 0, 0), Decl(lovefield.js, 0, 0)) +>Transaction : Symbol(lf.Transaction, Decl(lovefield-ts.d.ts, 1, 22), Decl(lovefield.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>begin : Symbol(lf.Transaction.begin, Decl(lovefield-ts.d.ts, 3, 56), Decl(lovefield.js, 0, 31)) +>scope : Symbol(scope, Decl(lovefield.js, 5, 42)) + diff --git a/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.types b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.types new file mode 100644 index 00000000000..9776e40ac24 --- /dev/null +++ b/tests/baselines/reference/prototypePropertyAssignmentMergeWithInterfaceMethod.types @@ -0,0 +1,53 @@ +=== tests/cases/conformance/salsa/lovefield-ts.d.ts === +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { + export interface Transaction { + attach(query: query.Builder): Promise> +>attach : (query: any) => Promise +>query : any +>query : any + + begin(scope: Array): Promise +>begin : (scope: any[]) => Promise +>scope : any[] +>schema : any + + commit(): Promise +>commit : () => Promise + + exec(queries: Array): Promise>> +>exec : (queries: any[]) => Promise +>queries : any[] +>query : any + + rollback(): Promise +>rollback : () => Promise + + stats(): TransactionStats +>stats : () => any + } +} +=== tests/cases/conformance/salsa/lovefield.js === +lf.Transaction = function() {}; +>lf.Transaction = function() {} : typeof Transaction +>lf.Transaction : typeof Transaction +>lf : typeof lf +>Transaction : typeof Transaction +>function() {} : typeof Transaction + +/** + * @param {!Array} scope + * @return {!IThenable} + */ +lf.Transaction.prototype.begin = function(scope) {}; +>lf.Transaction.prototype.begin = function(scope) {} : (scope: any[]) => any +>lf.Transaction.prototype.begin : any +>lf.Transaction.prototype : any +>lf.Transaction : typeof Transaction +>lf : typeof lf +>Transaction : typeof Transaction +>prototype : any +>begin : any +>function(scope) {} : (scope: any[]) => any +>scope : any[] + diff --git a/tests/cases/conformance/salsa/enumMergeWithExpando.ts b/tests/cases/conformance/salsa/enumMergeWithExpando.ts new file mode 100644 index 00000000000..a0367aff318 --- /dev/null +++ b/tests/cases/conformance/salsa/enumMergeWithExpando.ts @@ -0,0 +1,13 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: lovefield-ts.d.ts +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { + export enum Order { ASC, DESC } +} + +// @Filename: enums.js +lf.Order = {} +lf.Order.DESC = 0; +lf.Order.ASC = 1; diff --git a/tests/cases/conformance/salsa/prototypePropertyAssignmentMergeWithInterfaceMethod.ts b/tests/cases/conformance/salsa/prototypePropertyAssignmentMergeWithInterfaceMethod.ts new file mode 100644 index 00000000000..4f9181e5daa --- /dev/null +++ b/tests/cases/conformance/salsa/prototypePropertyAssignmentMergeWithInterfaceMethod.ts @@ -0,0 +1,22 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: lovefield-ts.d.ts +// bug #27352, crashes from github.com/google/lovefield +declare namespace lf { + export interface Transaction { + attach(query: query.Builder): Promise> + begin(scope: Array): Promise + commit(): Promise + exec(queries: Array): Promise>> + rollback(): Promise + stats(): TransactionStats + } +} +// @Filename: lovefield.js +lf.Transaction = function() {}; +/** + * @param {!Array} scope + * @return {!IThenable} + */ +lf.Transaction.prototype.begin = function(scope) {}; From e379aeb151ea072f4afc89cc58f2e3658b00fa3e Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 19 Oct 2018 13:50:38 -0700 Subject: [PATCH 078/262] Fix alias of module.exports->exports->IIFE (#27992) In JS, when you assign `module.exports = exports` and the entire module is wrapped in an IIFE, the resulting `export=` symbol, after following aliases, is the module itself. This results in trying to merge the file's exports with itself inside `getCommonJsExportEquals`, since it thinks that it has found new exports, possibly in an object literal, that need to be merged with the file's exports. For example: ```js (function() { exports.a = 1 module.exports = exports })() ``` --- src/compiler/checker.ts | 9 ++++-- .../moduleExportAliasExports.symbols | 21 +++++++++++++ .../reference/moduleExportAliasExports.types | 30 +++++++++++++++++++ .../salsa/moduleExportAliasExports.ts | 10 +++++++ 4 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/moduleExportAliasExports.symbols create mode 100644 tests/baselines/reference/moduleExportAliasExports.types create mode 100644 tests/cases/conformance/salsa/moduleExportAliasExports.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 07c45176860..eca967ce828 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2353,11 +2353,16 @@ namespace ts { function resolveExternalModuleSymbol(moduleSymbol: Symbol, dontResolveAlias?: boolean): Symbol; function resolveExternalModuleSymbol(moduleSymbol: Symbol | undefined, dontResolveAlias?: boolean): Symbol | undefined; function resolveExternalModuleSymbol(moduleSymbol: Symbol, dontResolveAlias?: boolean): Symbol { - return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports!.get(InternalSymbolName.ExportEquals), dontResolveAlias), moduleSymbol)) || moduleSymbol; + if (moduleSymbol) { + const exportEquals = resolveSymbol(moduleSymbol.exports!.get(InternalSymbolName.ExportEquals), dontResolveAlias); + const exported = getCommonJsExportEquals(exportEquals, moduleSymbol); + return getMergedSymbol(exported) || moduleSymbol; + } + return undefined!; } function getCommonJsExportEquals(exported: Symbol | undefined, moduleSymbol: Symbol): Symbol | undefined { - if (!exported || exported === unknownSymbol || moduleSymbol.exports!.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports!.size === 1) { return exported; } const merged = cloneSymbol(exported); diff --git a/tests/baselines/reference/moduleExportAliasExports.symbols b/tests/baselines/reference/moduleExportAliasExports.symbols new file mode 100644 index 00000000000..7253e7ed5f3 --- /dev/null +++ b/tests/baselines/reference/moduleExportAliasExports.symbols @@ -0,0 +1,21 @@ +=== tests/cases/conformance/salsa/Eloquent.js === +// bug #27365, crashes from github.com/marijnh/Eloquent-JavaScript +(function() { +exports.bigOak = 1 +>exports.bigOak : Symbol(bigOak, Decl(Eloquent.js, 1, 13)) +>exports : Symbol(bigOak, Decl(Eloquent.js, 1, 13)) +>bigOak : Symbol(bigOak, Decl(Eloquent.js, 1, 13)) + +exports.everywhere = 2 +>exports.everywhere : Symbol(everywhere, Decl(Eloquent.js, 2, 18)) +>exports : Symbol(everywhere, Decl(Eloquent.js, 2, 18)) +>everywhere : Symbol(everywhere, Decl(Eloquent.js, 2, 18)) + +module.exports = exports +>module.exports : Symbol("tests/cases/conformance/salsa/Eloquent", Decl(Eloquent.js, 0, 0)) +>module : Symbol(export=, Decl(Eloquent.js, 3, 22)) +>exports : Symbol(export=, Decl(Eloquent.js, 3, 22)) +>exports : Symbol("tests/cases/conformance/salsa/Eloquent", Decl(Eloquent.js, 0, 0)) + +})() + diff --git a/tests/baselines/reference/moduleExportAliasExports.types b/tests/baselines/reference/moduleExportAliasExports.types new file mode 100644 index 00000000000..06640be0b6e --- /dev/null +++ b/tests/baselines/reference/moduleExportAliasExports.types @@ -0,0 +1,30 @@ +=== tests/cases/conformance/salsa/Eloquent.js === +// bug #27365, crashes from github.com/marijnh/Eloquent-JavaScript +(function() { +>(function() {exports.bigOak = 1exports.everywhere = 2module.exports = exports})() : void +>(function() {exports.bigOak = 1exports.everywhere = 2module.exports = exports}) : () => void +>function() {exports.bigOak = 1exports.everywhere = 2module.exports = exports} : () => void + +exports.bigOak = 1 +>exports.bigOak = 1 : 1 +>exports.bigOak : number +>exports : typeof import("tests/cases/conformance/salsa/Eloquent") +>bigOak : number +>1 : 1 + +exports.everywhere = 2 +>exports.everywhere = 2 : 2 +>exports.everywhere : number +>exports : typeof import("tests/cases/conformance/salsa/Eloquent") +>everywhere : number +>2 : 2 + +module.exports = exports +>module.exports = exports : typeof import("tests/cases/conformance/salsa/Eloquent") +>module.exports : typeof import("tests/cases/conformance/salsa/Eloquent") +>module : { "tests/cases/conformance/salsa/Eloquent": typeof import("tests/cases/conformance/salsa/Eloquent"); } +>exports : typeof import("tests/cases/conformance/salsa/Eloquent") +>exports : typeof import("tests/cases/conformance/salsa/Eloquent") + +})() + diff --git a/tests/cases/conformance/salsa/moduleExportAliasExports.ts b/tests/cases/conformance/salsa/moduleExportAliasExports.ts new file mode 100644 index 00000000000..d716060e1bf --- /dev/null +++ b/tests/cases/conformance/salsa/moduleExportAliasExports.ts @@ -0,0 +1,10 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: Eloquent.js +// bug #27365, crashes from github.com/marijnh/Eloquent-JavaScript +(function() { +exports.bigOak = 1 +exports.everywhere = 2 +module.exports = exports +})() From 69b1cb5bace928065f597566344495898c2caf46 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 19 Oct 2018 14:31:55 -0700 Subject: [PATCH 079/262] Add new special assignment kinds for recognizing Object.defineProperty calls (#27208) * Add new special assignment kinds for recognizing Object.defineProperty calls * Add support for prototype assignments, fix nits * Fix code review comments * Add test documenting behavior in a few more odd scenarios --- src/compiler/binder.ts | 67 +++- src/compiler/checker.ts | 102 ++++- src/compiler/types.ts | 14 +- src/compiler/utilities.ts | 43 ++- src/services/navigationBar.ts | 3 + src/services/utilities.ts | 3 + .../reference/api/tsserverlibrary.d.ts | 2 +- tests/baselines/reference/api/typescript.d.ts | 2 +- ...heckExportsObjectAssignProperty.errors.txt | 110 ++++++ .../checkExportsObjectAssignProperty.symbols | 276 ++++++++++++++ .../checkExportsObjectAssignProperty.types | 360 ++++++++++++++++++ ...tsObjectAssignPrototypeProperty.errors.txt | 66 ++++ ...portsObjectAssignPrototypeProperty.symbols | 172 +++++++++ ...ExportsObjectAssignPrototypeProperty.types | 220 +++++++++++ .../checkObjectDefineProperty.errors.txt | 79 ++++ .../checkObjectDefineProperty.symbols | 197 ++++++++++ .../reference/checkObjectDefineProperty.types | 255 +++++++++++++ .../checkOtherObjectAssignProperty.errors.txt | 58 +++ .../checkOtherObjectAssignProperty.symbols | 121 ++++++ .../checkOtherObjectAssignProperty.types | 170 +++++++++ ...ntDefineProperrtyPotentialMerge.errors.txt | 23 ++ ...nmentDefineProperrtyPotentialMerge.symbols | 59 +++ ...ignmentDefineProperrtyPotentialMerge.types | 79 ++++ ...AssignmentDefineProperrtyPotentialMerge.ts | 17 + .../jsdoc/checkExportsObjectAssignProperty.ts | 82 ++++ ...eckExportsObjectAssignPrototypeProperty.ts | 52 +++ .../jsdoc/checkObjectDefineProperty.ts | 68 ++++ .../jsdoc/checkOtherObjectAssignProperty.ts | 39 ++ .../syntheticImportFromBabelGeneratedFile1.ts | 20 + .../syntheticImportFromBabelGeneratedFile2.ts | 22 ++ 30 files changed, 2756 insertions(+), 25 deletions(-) create mode 100644 tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt create mode 100644 tests/baselines/reference/checkExportsObjectAssignProperty.symbols create mode 100644 tests/baselines/reference/checkExportsObjectAssignProperty.types create mode 100644 tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt create mode 100644 tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols create mode 100644 tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types create mode 100644 tests/baselines/reference/checkObjectDefineProperty.errors.txt create mode 100644 tests/baselines/reference/checkObjectDefineProperty.symbols create mode 100644 tests/baselines/reference/checkObjectDefineProperty.types create mode 100644 tests/baselines/reference/checkOtherObjectAssignProperty.errors.txt create mode 100644 tests/baselines/reference/checkOtherObjectAssignProperty.symbols create mode 100644 tests/baselines/reference/checkOtherObjectAssignProperty.types create mode 100644 tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.errors.txt create mode 100644 tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols create mode 100644 tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.types create mode 100644 tests/cases/compiler/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.ts create mode 100644 tests/cases/conformance/jsdoc/checkExportsObjectAssignProperty.ts create mode 100644 tests/cases/conformance/jsdoc/checkExportsObjectAssignPrototypeProperty.ts create mode 100644 tests/cases/conformance/jsdoc/checkObjectDefineProperty.ts create mode 100644 tests/cases/conformance/jsdoc/checkOtherObjectAssignProperty.ts create mode 100644 tests/cases/fourslash/syntheticImportFromBabelGeneratedFile1.ts create mode 100644 tests/cases/fourslash/syntheticImportFromBabelGeneratedFile2.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 292bfe51340..3fba2894002 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2112,7 +2112,7 @@ namespace ts { // Nothing to do break; default: - Debug.fail("Unknown special property assignment kind"); + Debug.fail("Unknown binary expression special property assignment kind"); } return checkStrictModeBinaryExpression(node); case SyntaxKind.CatchClause: @@ -2188,6 +2188,19 @@ namespace ts { return bindFunctionExpression(node); case SyntaxKind.CallExpression: + const assignmentKind = getAssignmentDeclarationKind(node as CallExpression); + switch (assignmentKind) { + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + return bindObjectDefinePropertyAssignment(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + return bindObjectDefinePropertyExport(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return bindObjectDefinePrototypeProperty(node as BindableObjectDefinePropertyCall); + case AssignmentDeclarationKind.None: + break; // Nothing to do + default: + return Debug.fail("Unknown call expression assignment declaration kind"); + } if (isInJSFile(node)) { bindCallExpression(node); } @@ -2351,6 +2364,22 @@ namespace ts { return true; } + function bindObjectDefinePropertyExport(node: BindableObjectDefinePropertyCall) { + if (!setCommonJsModuleIndicator(node)) { + return; + } + const symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, (id, symbol) => { + if (symbol) { + addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); + } + return symbol; + }); + if (symbol) { + const flags = SymbolFlags.Property | SymbolFlags.ExportValue; + declareSymbol(symbol.exports!, symbol, node, flags, SymbolFlags.None); + } + } + function bindExportsPropertyAssignment(node: BinaryExpression) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration @@ -2458,6 +2487,11 @@ namespace ts { bindPropertyAssignment(lhs.expression, lhs, /*isPrototypeProperty*/ false); } + function bindObjectDefinePrototypeProperty(node: BindableObjectDefinePropertyCall) { + const namespaceSymbol = lookupSymbolForPropertyAccess((node.arguments[0] as PropertyAccessExpression).expression as EntityNameExpression); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); + } + /** * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. @@ -2476,6 +2510,12 @@ namespace ts { bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); } + function bindObjectDefinePropertyAssignment(node: BindableObjectDefinePropertyCall) { + let namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); + const isToplevel = node.parent.parent.kind === SyntaxKind.SourceFile; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); + bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); + } function bindSpecialPropertyAssignment(node: BinaryExpression) { const lhs = node.left as PropertyAccessEntityNameExpression; @@ -2507,16 +2547,12 @@ namespace ts { bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); } - function bindPropertyAssignment(name: EntityNameExpression, propertyAccess: PropertyAccessEntityNameExpression, isPrototypeProperty: boolean) { - let namespaceSymbol = lookupSymbolForPropertyAccess(name); - const isToplevel = isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === SyntaxKind.SourceFile - : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; + function bindPotentiallyMissingNamespaces(namespaceSymbol: Symbol | undefined, entityName: EntityNameExpression, isToplevel: boolean, isPrototypeProperty: boolean) { if (isToplevel && !isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace))) { // make symbols or add declarations for intermediate containers const flags = SymbolFlags.Module | SymbolFlags.Assignment; const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => { + namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, (id, symbol, parent) => { if (symbol) { addDeclarationToSymbol(symbol, id, flags); return symbol; @@ -2528,6 +2564,10 @@ namespace ts { } }); } + return namespaceSymbol; + } + + function bindPotentiallyNewExpandoMemberToNamespace(declaration: PropertyAccessEntityNameExpression | CallExpression, namespaceSymbol: Symbol | undefined, isPrototypeProperty: boolean) { if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } @@ -2537,10 +2577,19 @@ namespace ts { (namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable())); - const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(propertyAccess)!); + const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(declaration)!); const includes = isMethod ? SymbolFlags.Method : SymbolFlags.Property; const excludes = isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment); + declareSymbol(symbolTable, namespaceSymbol, declaration, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment); + } + + function bindPropertyAssignment(name: EntityNameExpression, propertyAccess: PropertyAccessEntityNameExpression, isPrototypeProperty: boolean) { + let namespaceSymbol = lookupSymbolForPropertyAccess(name); + const isToplevel = isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === SyntaxKind.SourceFile + : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; + namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); + bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } /** diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eca967ce828..ea5e27c2c9e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4881,7 +4881,7 @@ namespace ts { let jsdocType: Type | undefined; let types: Type[] | undefined; for (const declaration of symbol.declarations) { - const expression = isBinaryExpression(declaration) ? declaration : + const expression = (isBinaryExpression(declaration) || isCallExpression(declaration)) ? declaration : isPropertyAccessExpression(declaration) ? isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { @@ -4897,9 +4897,11 @@ namespace ts { definedInMethod = true; } } - jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + if (!isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } let type = jsdocType; @@ -4960,7 +4962,32 @@ namespace ts { } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, kind: AssignmentDeclarationKind) { + function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression | CallExpression, kind: AssignmentDeclarationKind) { + if (isCallExpression(expression)) { + if (resolvedSymbol) { + return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments + } + const objectLitType = checkExpressionCached((expression as BindableObjectDefinePropertyCall).arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value" as __String); + if (valueType) { + return valueType; + } + const getFunc = getTypeOfPropertyOfType(objectLitType, "get" as __String); + if (getFunc) { + const getSig = getSingleCallSignature(getFunc); + if (getSig) { + return getReturnTypeOfSignature(getSig); + } + } + const setFunc = getTypeOfPropertyOfType(objectLitType, "set" as __String); + if (setFunc) { + const setSig = getSingleCallSignature(setFunc); + if (setSig) { + return getTypeOfFirstParameterOfSignature(setSig); + } + } + return anyType; + } const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & TypeFlags.Object && kind === AssignmentDeclarationKind.ModuleExports && @@ -5212,7 +5239,7 @@ namespace ts { } let type: Type | undefined; if (isInJSFile(declaration) && - (isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { + (isCallExpression(declaration) || isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) @@ -16179,6 +16206,31 @@ namespace ts { getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) { return (container.parent.parent.parent.left as PropertyAccessExpression).expression; } + // Object.defineProperty(x, "method", { value: function() { } }); + // Object.defineProperty(x, "method", { set: (x: () => void) => void }); + // Object.defineProperty(x, "method", { get: () => function() { }) }); + else if (container.kind === SyntaxKind.FunctionExpression && + isPropertyAssignment(container.parent) && + isIdentifier(container.parent.name) && + (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && + isObjectLiteralExpression(container.parent.parent) && + isCallExpression(container.parent.parent.parent) && + container.parent.parent.parent.arguments[2] === container.parent.parent && + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + return (container.parent.parent.parent.arguments[0] as PropertyAccessExpression).expression; + } + // Object.defineProperty(x, "method", { value() { } }); + // Object.defineProperty(x, "method", { set(x: () => void) {} }); + // Object.defineProperty(x, "method", { get() { return () => {} } }); + else if (isMethodDeclaration(container) && + isIdentifier(container.name) && + (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && + isObjectLiteralExpression(container.parent) && + isCallExpression(container.parent.parent) && + container.parent.parent.arguments[2] === container.parent && + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.ObjectDefinePrototypeProperty) { + return (container.parent.parent.arguments[0] as PropertyAccessExpression).expression; + } } function getTypeForThisExpressionFromJSDoc(node: Node) { @@ -16741,6 +16793,10 @@ namespace ts { } const thisType = checkThisExpression(thisAccess.expression); return thisType && getTypeOfPropertyOfContextualType(thisType, thisAccess.name.escapedText) || false; + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return Debug.fail("Does not apply"); default: return Debug.assertNever(kind); } @@ -21132,18 +21188,52 @@ namespace ts { return true; } + function isReadonlyAssignmentDeclaration(d: Declaration) { + if (!isCallExpression(d)) { + return false; + } + if (!isBindableObjectDefinePropertyCall(d)) { + return false; + } + const objectLitType = checkExpressionCached(d.arguments[2]); + const valueType = getTypeOfPropertyOfType(objectLitType, "value" as __String); + if (valueType) { + const writableProp = getPropertyOfType(objectLitType, "writable" as __String); + const writableType = writableProp && getTypeOfSymbol(writableProp); + if (!writableType || writableType === falseType || writableType === regularFalseType) { + return true; + } + // We include this definition whereupon we walk back and check the type at the declaration because + // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the + // argument types, should the type be contextualized by the call itself. + if (writableProp && writableProp.valueDeclaration && isPropertyAssignment(writableProp.valueDeclaration)) { + const initializer = writableProp.valueDeclaration.initializer; + const rawOriginalType = checkExpression(initializer); + if (rawOriginalType === falseType || rawOriginalType === regularFalseType) { + return true; + } + } + return false; + } + const setProp = getPropertyOfType(objectLitType, "set" as __String); + return !setProp; + } + function isReadonlySymbol(symbol: Symbol): boolean { // The following symbols are considered read-only: // Properties with a 'readonly' modifier // Variables declared with 'const' // Get accessors without matching set accessors // Enum members + // Object.defineProperty assignments with writable false or no setter // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) return !!(getCheckFlags(symbol) & CheckFlags.Readonly || symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly || symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || - symbol.flags & SymbolFlags.EnumMember); + symbol.flags & SymbolFlags.EnumMember || + some(symbol.declarations, isReadonlyAssignmentDeclaration) + ); } function isReferenceToReadonlyEntity(expr: Expression, symbol: Symbol): boolean { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 610cc4e61c7..fe31a30a30f 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -790,7 +790,7 @@ namespace ts { export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + export type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; export interface Declaration extends Node { _declarationBrand: any; @@ -1774,6 +1774,9 @@ namespace ts { arguments: NodeArray; } + /** @internal */ + export type BindableObjectDefinePropertyCall = CallExpression & { arguments: { 0: EntityNameExpression, 1: StringLiteralLike | NumericLiteral, 2: ObjectLiteralExpression } }; + // see: https://tc39.github.io/ecma262/#prod-SuperCall export interface SuperCall extends CallExpression { expression: SuperExpression; @@ -4347,6 +4350,15 @@ namespace ts { Property, // F.prototype = { ... } Prototype, + // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) }); + // Object.defineProperty(x, 'name', { get: Function, set: Function }); + // Object.defineProperty(x, 'name', { get: Function }); + // Object.defineProperty(x, 'name', { set: Function }); + ObjectDefinePropertyValue, + // Object.defineProperty(exports || module.exports, 'name', ...); + ObjectDefinePropertyExports, + // Object.defineProperty(Foo.prototype, 'name', ...); + ObjectDefinePrototypeProperty, } /** @deprecated Use FileExtensionInfo instead. */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index acaabdab9c7..6310d299b42 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -765,12 +765,13 @@ namespace ts { return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } - export function getTextOfPropertyName(name: PropertyName): __String { + export function getTextOfPropertyName(name: PropertyName | NoSubstitutionTemplateLiteral): __String { switch (name.kind) { case SyntaxKind.Identifier: return name.escapedText; case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: return escapeLeadingUnderscores(name.text); case SyntaxKind.ComputedPropertyName: return isStringOrNumericLiteralLike(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined!; // TODO: GH#18217 Almost all uses of this assume the result to be defined! @@ -1770,7 +1771,7 @@ namespace ts { } export function isAssignmentDeclaration(decl: Declaration) { - return isBinaryExpression(decl) || isPropertyAccessExpression(decl) || isIdentifier(decl); + return isBinaryExpression(decl) || isPropertyAccessExpression(decl) || isIdentifier(decl) || isCallExpression(decl); } /** Get the initializer, taking into account defaulted Javascript initializers */ @@ -1905,12 +1906,35 @@ namespace ts { /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - export function getAssignmentDeclarationKind(expr: BinaryExpression): AssignmentDeclarationKind { + export function getAssignmentDeclarationKind(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { const special = getAssignmentDeclarationKindWorker(expr); return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None; } - function getAssignmentDeclarationKindWorker(expr: BinaryExpression): AssignmentDeclarationKind { + export function isBindableObjectDefinePropertyCall(expr: CallExpression): expr is BindableObjectDefinePropertyCall { + return length(expr.arguments) === 3 && + isPropertyAccessExpression(expr.expression) && + isIdentifier(expr.expression.expression) && + idText(expr.expression.expression) === "Object" && + idText(expr.expression.name) === "defineProperty" && + isStringOrNumericLiteralLike(expr.arguments[1]) && + isEntityNameExpression(expr.arguments[0]); + } + + function getAssignmentDeclarationKindWorker(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { + if (isCallExpression(expr)) { + if (!isBindableObjectDefinePropertyCall(expr)) { + return AssignmentDeclarationKind.None; + } + const entityName = expr.arguments[0]; + if (isExportsIdentifier(entityName) || isModuleExportsPropertyAccessExpression(entityName)) { + return AssignmentDeclarationKind.ObjectDefinePropertyExports; + } + if (isPropertyAccessExpression(entityName) && entityName.name.escapedText === "prototype" && isEntityNameExpression(entityName.expression)) { + return AssignmentDeclarationKind.ObjectDefinePrototypeProperty; + } + return AssignmentDeclarationKind.ObjectDefinePropertyValue; + } if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || !isPropertyAccessExpression(expr.left)) { return AssignmentDeclarationKind.None; @@ -1927,7 +1951,7 @@ namespace ts { if (lhs.expression.kind === SyntaxKind.ThisKeyword) { return AssignmentDeclarationKind.ThisProperty; } - else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return AssignmentDeclarationKind.ModuleExports; } @@ -4977,14 +5001,19 @@ namespace ts { } break; } + case SyntaxKind.CallExpression: case SyntaxKind.BinaryExpression: { - const expr = declaration as BinaryExpression; + const expr = declaration as BinaryExpression | CallExpression; switch (getAssignmentDeclarationKind(expr)) { case AssignmentDeclarationKind.ExportsProperty: case AssignmentDeclarationKind.ThisProperty: case AssignmentDeclarationKind.Property: case AssignmentDeclarationKind.PrototypeProperty: - return (expr.left as PropertyAccessExpression).name; + return ((expr as BinaryExpression).left as PropertyAccessExpression).name; + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: + return (expr as BindableObjectDefinePropertyCall).arguments[1]; default: return undefined; } diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 03d2aec13c5..760d6e71031 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -281,6 +281,9 @@ namespace ts.NavigationBar { case AssignmentDeclarationKind.ThisProperty: case AssignmentDeclarationKind.Property: case AssignmentDeclarationKind.None: + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: break; default: Debug.assertNever(special); diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 427c31e5384..e53f568c0f4 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -368,6 +368,9 @@ namespace ts { const kind = getAssignmentDeclarationKind(node as BinaryExpression); const { right } = node as BinaryExpression; switch (kind) { + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: case AssignmentDeclarationKind.None: return ScriptElementKind.unknown; case AssignmentDeclarationKind.ExportsProperty: diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 00b93acbba5..a7e8d3e5690 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -526,7 +526,7 @@ declare namespace ts { } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 34b5ade8841..0c2485d1a25 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -526,7 +526,7 @@ declare namespace ts { } type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName; - type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; + type DeclarationName = Identifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; } diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt b/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt new file mode 100644 index 00000000000..266c2180a68 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt @@ -0,0 +1,110 @@ +tests/cases/conformance/jsdoc/validator.ts(17,4): error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(18,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(19,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(20,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(21,1): error TS2322: Type '0' is not assignable to type 'string'. +tests/cases/conformance/jsdoc/validator.ts(37,4): error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(38,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(39,1): error TS2322: Type '0' is not assignable to type 'string'. +tests/cases/conformance/jsdoc/validator.ts(40,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(41,1): error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/validator.ts (10 errors) ==== + import "./"; + + import m1 = require("./mod1"); + + m1.thing; + m1.readonlyProp; + m1.rwAccessors; + m1.readonlyAccessor; + m1.setonlyAccessor; + + // allowed assignments + m1.thing = 10; + m1.rwAccessors = 11; + m1.setonlyAccessor = "yes"; + + // disallowed assignments + m1.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. + m1.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. + m1.thing = "no"; + ~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + + import m2 = require("./mod2"); + + m2.thing; + m2.readonlyProp; + m2.rwAccessors; + m2.readonlyAccessor; + m2.setonlyAccessor; + + // allowed assignments + m2.thing = "ok"; + m2.rwAccessors = 11; + m2.setonlyAccessor = "yes"; + + // disallowed assignments + m2.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. + m2.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. + m2.thing = 0; + ~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + m2.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m2.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + +==== tests/cases/conformance/jsdoc/mod1.js (0 errors) ==== + Object.defineProperty(exports, "thing", { value: 42, writable: true }); + Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + +==== tests/cases/conformance/jsdoc/mod2.js (0 errors) ==== + Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); + Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(module.exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + +==== tests/cases/conformance/jsdoc/index.js (0 errors) ==== + /** + * @type {number} + */ + const q = require("./mod1").thing; + + /** + * @type {string} + */ + const u = require("./mod2").thing; + \ No newline at end of file diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols new file mode 100644 index 00000000000..d33e2de1e20 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols @@ -0,0 +1,276 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import m1 = require("./mod1"); +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) + +m1.thing; +>m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) + +m1.readonlyProp; +>m1.readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) + +m1.rwAccessors; +>m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) + +m1.readonlyAccessor; +>m1.readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) + +m1.setonlyAccessor; +>m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) + +// allowed assignments +m1.thing = 10; +>m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) + +m1.rwAccessors = 11; +>m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) + +m1.thing = "no"; +>m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) + +m1.rwAccessors = "no"; +>m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) + +import m2 = require("./mod2"); +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) + +m2.thing; +>m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) + +m2.readonlyProp; +>m2.readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) + +m2.rwAccessors; +>m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) + +m2.readonlyAccessor; +>m2.readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) + +m2.setonlyAccessor; +>m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) + +// allowed assignments +m2.thing = "ok"; +>m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) + +m2.rwAccessors = 11; +>m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) + +m2.setonlyAccessor = "yes"; +>m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) + +// disallowed assignments +m2.readonlyProp = "name"; +>m2.readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) + +m2.readonlyAccessor = 12; +>m2.readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) + +m2.thing = 0; +>m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) + +m2.rwAccessors = "no"; +>m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) + +m2.setonlyAccessor = 0; +>m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) + +=== tests/cases/conformance/jsdoc/mod1.js === +Object.defineProperty(exports, "thing", { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>value : Symbol(value, Decl(mod1.js, 0, 41)) +>writable : Symbol(writable, Decl(mod1.js, 0, 52)) + +Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>value : Symbol(value, Decl(mod1.js, 1, 48)) +>writable : Symbol(writable, Decl(mod1.js, 1, 64)) + +Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>get : Symbol(get, Decl(mod1.js, 2, 47)) +>set : Symbol(set, Decl(mod1.js, 2, 71)) +>_ : Symbol(_, Decl(mod1.js, 2, 76)) + +Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>get : Symbol(get, Decl(mod1.js, 3, 52)) + +Object.defineProperty(exports, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod1.js, 4, 51)) +>str : Symbol(str, Decl(mod1.js, 6, 8)) + + this.rwAccessors = Number(str) +>rwAccessors : Symbol(rwAccessors, Decl(mod1.js, 6, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod1.js, 6, 8)) + } +}); + +=== tests/cases/conformance/jsdoc/mod2.js === +Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>value : Symbol(value, Decl(mod2.js, 0, 48)) +>writable : Symbol(writable, Decl(mod2.js, 0, 62)) + +Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>value : Symbol(value, Decl(mod2.js, 1, 55)) +>writable : Symbol(writable, Decl(mod2.js, 1, 71)) + +Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>get : Symbol(get, Decl(mod2.js, 2, 54)) +>set : Symbol(set, Decl(mod2.js, 2, 78)) +>_ : Symbol(_, Decl(mod2.js, 2, 83)) + +Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>get : Symbol(get, Decl(mod2.js, 3, 59)) + +Object.defineProperty(module.exports, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod2.js, 4, 58)) +>str : Symbol(str, Decl(mod2.js, 6, 8)) + + this.rwAccessors = Number(str) +>rwAccessors : Symbol(rwAccessors, Decl(mod2.js, 6, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod2.js, 6, 8)) + } +}); + +=== tests/cases/conformance/jsdoc/index.js === +/** + * @type {number} + */ +const q = require("./mod1").thing; +>q : Symbol(q, Decl(index.js, 3, 5)) +>require("./mod1").thing : Symbol("thing", Decl(mod1.js, 0, 0)) +>require : Symbol(require) +>"./mod1" : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>thing : Symbol("thing", Decl(mod1.js, 0, 0)) + +/** + * @type {string} + */ +const u = require("./mod2").thing; +>u : Symbol(u, Decl(index.js, 8, 5)) +>require("./mod2").thing : Symbol("thing", Decl(mod2.js, 0, 0)) +>require : Symbol(require) +>"./mod2" : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>thing : Symbol("thing", Decl(mod2.js, 0, 0)) + diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.types b/tests/baselines/reference/checkExportsObjectAssignProperty.types new file mode 100644 index 00000000000..847ac720d75 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.types @@ -0,0 +1,360 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import m1 = require("./mod1"); +>m1 : typeof m1 + +m1.thing; +>m1.thing : number +>m1 : typeof m1 +>thing : number + +m1.readonlyProp; +>m1.readonlyProp : string +>m1 : typeof m1 +>readonlyProp : string + +m1.rwAccessors; +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number + +m1.readonlyAccessor; +>m1.readonlyAccessor : number +>m1 : typeof m1 +>readonlyAccessor : number + +m1.setonlyAccessor; +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string + +// allowed assignments +m1.thing = 10; +>m1.thing = 10 : 10 +>m1.thing : number +>m1 : typeof m1 +>thing : number +>10 : 10 + +m1.rwAccessors = 11; +>m1.rwAccessors = 11 : 11 +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number +>11 : 11 + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor = "yes" : "yes" +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp = "name" : "name" +>m1.readonlyProp : any +>m1 : typeof m1 +>readonlyProp : any +>"name" : "name" + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor = 12 : 12 +>m1.readonlyAccessor : any +>m1 : typeof m1 +>readonlyAccessor : any +>12 : 12 + +m1.thing = "no"; +>m1.thing = "no" : "no" +>m1.thing : number +>m1 : typeof m1 +>thing : number +>"no" : "no" + +m1.rwAccessors = "no"; +>m1.rwAccessors = "no" : "no" +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number +>"no" : "no" + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor = 0 : 0 +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string +>0 : 0 + +import m2 = require("./mod2"); +>m2 : typeof m2 + +m2.thing; +>m2.thing : string +>m2 : typeof m2 +>thing : string + +m2.readonlyProp; +>m2.readonlyProp : string +>m2 : typeof m2 +>readonlyProp : string + +m2.rwAccessors; +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number + +m2.readonlyAccessor; +>m2.readonlyAccessor : number +>m2 : typeof m2 +>readonlyAccessor : number + +m2.setonlyAccessor; +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string + +// allowed assignments +m2.thing = "ok"; +>m2.thing = "ok" : "ok" +>m2.thing : string +>m2 : typeof m2 +>thing : string +>"ok" : "ok" + +m2.rwAccessors = 11; +>m2.rwAccessors = 11 : 11 +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number +>11 : 11 + +m2.setonlyAccessor = "yes"; +>m2.setonlyAccessor = "yes" : "yes" +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m2.readonlyProp = "name"; +>m2.readonlyProp = "name" : "name" +>m2.readonlyProp : any +>m2 : typeof m2 +>readonlyProp : any +>"name" : "name" + +m2.readonlyAccessor = 12; +>m2.readonlyAccessor = 12 : 12 +>m2.readonlyAccessor : any +>m2 : typeof m2 +>readonlyAccessor : any +>12 : 12 + +m2.thing = 0; +>m2.thing = 0 : 0 +>m2.thing : string +>m2 : typeof m2 +>thing : string +>0 : 0 + +m2.rwAccessors = "no"; +>m2.rwAccessors = "no" : "no" +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number +>"no" : "no" + +m2.setonlyAccessor = 0; +>m2.setonlyAccessor = 0 : 0 +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string +>0 : 0 + +=== tests/cases/conformance/jsdoc/mod1.js === +Object.defineProperty(exports, "thing", { value: 42, writable: true }); +>Object.defineProperty(exports, "thing", { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"thing" : "thing" +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + +Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(exports, "setonlyAccessor", { +>Object.defineProperty(exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : any +>this : any +>rwAccessors : any +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); + +=== tests/cases/conformance/jsdoc/mod2.js === +Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); +>Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"thing" : "thing" +>{ value: "yes", writable: true } : { value: string; writable: true; } +>value : string +>"yes" : "yes" +>writable : true +>true : true + +Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(module.exports, "setonlyAccessor", { +>Object.defineProperty(module.exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : any +>this : any +>rwAccessors : any +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); + +=== tests/cases/conformance/jsdoc/index.js === +/** + * @type {number} + */ +const q = require("./mod1").thing; +>q : number +>require("./mod1").thing : number +>require("./mod1") : typeof import("tests/cases/conformance/jsdoc/mod1") +>require : any +>"./mod1" : "./mod1" +>thing : number + +/** + * @type {string} + */ +const u = require("./mod2").thing; +>u : string +>require("./mod2").thing : string +>require("./mod2") : typeof import("tests/cases/conformance/jsdoc/mod2") +>require : any +>"./mod2" : "./mod2" +>thing : string + diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt new file mode 100644 index 00000000000..c2621a71b99 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt @@ -0,0 +1,66 @@ +tests/cases/conformance/jsdoc/validator.ts(19,4): error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(20,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validator.ts(21,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(22,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(23,1): error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/validator.ts (5 errors) ==== + import "./"; + + import Person = require("./mod1"); + + const m1 = new Person("Name") + + m1.thing; + m1.readonlyProp; + m1.rwAccessors; + m1.readonlyAccessor; + m1.setonlyAccessor; + + // allowed assignments + m1.thing = 10; + m1.rwAccessors = 11; + m1.setonlyAccessor = "yes"; + + // disallowed assignments + m1.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a constant or a read-only property. + m1.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a constant or a read-only property. + m1.thing = "no"; + ~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/mod1.js (0 errors) ==== + /** + * @constructor + * @param {string} name + */ + function Person(name) { + this.name = name; + } + Person.prototype.describe = function () { + return "Person called " + this.name; + }; + Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); + Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(Person.prototype, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + module.exports = Person; + \ No newline at end of file diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols new file mode 100644 index 00000000000..9f04a3600cc --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols @@ -0,0 +1,172 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import Person = require("./mod1"); +>Person : Symbol(Person, Decl(validator.ts, 0, 12)) + +const m1 = new Person("Name") +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>Person : Symbol(Person, Decl(validator.ts, 0, 12)) + +m1.thing; +>m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) + +m1.readonlyProp; +>m1.readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) + +m1.rwAccessors; +>m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) + +m1.readonlyAccessor; +>m1.readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) + +m1.setonlyAccessor; +>m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) + +// allowed assignments +m1.thing = 10; +>m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) + +m1.rwAccessors = 11; +>m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) + +m1.thing = "no"; +>m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) + +m1.rwAccessors = "no"; +>m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) + + +=== tests/cases/conformance/jsdoc/mod1.js === +/** + * @constructor + * @param {string} name + */ +function Person(name) { +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(name, Decl(mod1.js, 4, 16)) + + this.name = name; +>this.name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>name : Symbol(name, Decl(mod1.js, 4, 16)) +} +Person.prototype.describe = function () { +>Person.prototype : Symbol(Person.describe, Decl(mod1.js, 6, 1)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>describe : Symbol(Person.describe, Decl(mod1.js, 6, 1)) + + return "Person called " + this.name; +>this.name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(Person.name, Decl(mod1.js, 4, 23)) + +}; +Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>value : Symbol(value, Decl(mod1.js, 10, 50)) +>writable : Symbol(writable, Decl(mod1.js, 10, 61)) + +Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>value : Symbol(value, Decl(mod1.js, 11, 57)) +>writable : Symbol(writable, Decl(mod1.js, 11, 73)) + +Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>get : Symbol(get, Decl(mod1.js, 12, 56)) +>set : Symbol(set, Decl(mod1.js, 12, 80)) +>_ : Symbol(_, Decl(mod1.js, 12, 85)) + +Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>get : Symbol(get, Decl(mod1.js, 13, 61)) + +Object.defineProperty(Person.prototype, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod1.js, 14, 60)) +>str : Symbol(str, Decl(mod1.js, 16, 8)) + + this.rwAccessors = Number(str) +>this.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>rwAccessors : Symbol(rwAccessors, Decl(mod1.js, 16, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod1.js, 16, 8)) + } +}); +module.exports = Person; +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>module : Symbol(export=, Decl(mod1.js, 19, 3)) +>exports : Symbol(export=, Decl(mod1.js, 19, 3)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) + diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types new file mode 100644 index 00000000000..662c578701f --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types @@ -0,0 +1,220 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import Person = require("./mod1"); +>Person : typeof Person + +const m1 = new Person("Name") +>m1 : Person +>new Person("Name") : Person +>Person : typeof Person +>"Name" : "Name" + +m1.thing; +>m1.thing : number +>m1 : Person +>thing : number + +m1.readonlyProp; +>m1.readonlyProp : string +>m1 : Person +>readonlyProp : string + +m1.rwAccessors; +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number + +m1.readonlyAccessor; +>m1.readonlyAccessor : number +>m1 : Person +>readonlyAccessor : number + +m1.setonlyAccessor; +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string + +// allowed assignments +m1.thing = 10; +>m1.thing = 10 : 10 +>m1.thing : number +>m1 : Person +>thing : number +>10 : 10 + +m1.rwAccessors = 11; +>m1.rwAccessors = 11 : 11 +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number +>11 : 11 + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor = "yes" : "yes" +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp = "name" : "name" +>m1.readonlyProp : any +>m1 : Person +>readonlyProp : any +>"name" : "name" + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor = 12 : 12 +>m1.readonlyAccessor : any +>m1 : Person +>readonlyAccessor : any +>12 : 12 + +m1.thing = "no"; +>m1.thing = "no" : "no" +>m1.thing : number +>m1 : Person +>thing : number +>"no" : "no" + +m1.rwAccessors = "no"; +>m1.rwAccessors = "no" : "no" +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number +>"no" : "no" + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor = 0 : 0 +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string +>0 : 0 + + +=== tests/cases/conformance/jsdoc/mod1.js === +/** + * @constructor + * @param {string} name + */ +function Person(name) { +>Person : typeof Person +>name : string + + this.name = name; +>this.name = name : string +>this.name : string +>this : Person +>name : string +>name : string +} +Person.prototype.describe = function () { +>Person.prototype.describe = function () { return "Person called " + this.name;} : () => string +>Person.prototype.describe : any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>describe : any +>function () { return "Person called " + this.name;} : () => string + + return "Person called " + this.name; +>"Person called " + this.name : string +>"Person called " : "Person called " +>this.name : string +>this : Person +>name : string + +}; +Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); +>Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"thing" : "thing" +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + +Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(Person.prototype, "setonlyAccessor", { +>Object.defineProperty(Person.prototype, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : number +>this : Person +>rwAccessors : number +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); +module.exports = Person; +>module.exports = Person : typeof Person +>module.exports : typeof Person +>module : { "tests/cases/conformance/jsdoc/mod1": typeof Person; } +>exports : typeof Person +>Person : typeof Person + diff --git a/tests/baselines/reference/checkObjectDefineProperty.errors.txt b/tests/baselines/reference/checkObjectDefineProperty.errors.txt new file mode 100644 index 00000000000..b587955ef2f --- /dev/null +++ b/tests/baselines/reference/checkObjectDefineProperty.errors.txt @@ -0,0 +1,79 @@ +tests/cases/conformance/jsdoc/validate.ts(14,3): error TS2540: Cannot assign to 'lastName' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validate.ts(15,3): error TS2540: Cannot assign to 'houseNumber' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/validate.ts(16,1): error TS2322: Type '12' is not assignable to type 'string'. +tests/cases/conformance/jsdoc/validate.ts(17,3): error TS2540: Cannot assign to 'middleInit' because it is a constant or a read-only property. + + +==== tests/cases/conformance/jsdoc/validate.ts (4 errors) ==== + // Validate in TS as simple validations would usually be interpreted as more special assignments + import x = require("./"); + x.name; + x.middleInit; + x.lastName; + x.zip; + x.houseNumber; + x.zipStr; + + x.name = "Another"; + x.zip = 98123; + x.zipStr = "OK"; + + x.lastName = "should fail"; + ~~~~~~~~ +!!! error TS2540: Cannot assign to 'lastName' because it is a constant or a read-only property. + x.houseNumber = 12; // should also fail + ~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'houseNumber' because it is a constant or a read-only property. + x.zipStr = 12; // should fail + ~~~~~~~~ +!!! error TS2322: Type '12' is not assignable to type 'string'. + x.middleInit = "R"; // should also fail + ~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'middleInit' because it is a constant or a read-only property. + +==== tests/cases/conformance/jsdoc/index.js (0 errors) ==== + const x = {}; + Object.defineProperty(x, "name", { value: "Charles", writable: true }); + Object.defineProperty(x, "middleInit", { value: "H" }); + Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); + Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }); + Object.defineProperty(x, "zipStr", { + /** @param {string} str */ + set(str) { + this.zip = Number(str) + } + }); + + /** + * @param {{name: string}} named + */ + function takeName(named) { return named.name; } + + takeName(x); + /** + * @type {number} + */ + var a = x.zip; + + /** + * @type {number} + */ + var b = x.houseNumber; + + const returnExemplar = () => x; + const needsExemplar = (_ = x) => void 0; + + const expected = /** @type {{name: string, readonly middleInit: string, readonly lastName: string, zip: number, readonly houseNumber: number, zipStr: string}} */(/** @type {*} */(null)); + + /** + * + * @param {typeof returnExemplar} a + * @param {typeof needsExemplar} b + */ + function match(a, b) {} + + match(() => expected, (x = expected) => void 0); + + module.exports = x; + \ No newline at end of file diff --git a/tests/baselines/reference/checkObjectDefineProperty.symbols b/tests/baselines/reference/checkObjectDefineProperty.symbols new file mode 100644 index 00000000000..d3eea1a0a74 --- /dev/null +++ b/tests/baselines/reference/checkObjectDefineProperty.symbols @@ -0,0 +1,197 @@ +=== tests/cases/conformance/jsdoc/validate.ts === +// Validate in TS as simple validations would usually be interpreted as more special assignments +import x = require("./"); +>x : Symbol(x, Decl(validate.ts, 0, 0)) + +x.name; +>x.name : Symbol(x["name"], Decl(index.js, 0, 13)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>name : Symbol(x["name"], Decl(index.js, 0, 13)) + +x.middleInit; +>x.middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) + +x.lastName; +>x.lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) + +x.zip; +>x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>zip : Symbol(x["zip"], Decl(index.js, 3, 74)) + +x.houseNumber; +>x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) + +x.zipStr; +>x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) + +x.name = "Another"; +>x.name : Symbol(x["name"], Decl(index.js, 0, 13)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>name : Symbol(x["name"], Decl(index.js, 0, 13)) + +x.zip = 98123; +>x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>zip : Symbol(x["zip"], Decl(index.js, 3, 74)) + +x.zipStr = "OK"; +>x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) + +x.lastName = "should fail"; +>x.lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) + +x.houseNumber = 12; // should also fail +>x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) + +x.zipStr = 12; // should fail +>x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) + +x.middleInit = "R"; // should also fail +>x.middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>x : Symbol(x, Decl(validate.ts, 0, 0)) +>middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) + +=== tests/cases/conformance/jsdoc/index.js === +const x = {}; +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + +Object.defineProperty(x, "name", { value: "Charles", writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>value : Symbol(value, Decl(index.js, 1, 34)) +>writable : Symbol(writable, Decl(index.js, 1, 52)) + +Object.defineProperty(x, "middleInit", { value: "H" }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>value : Symbol(value, Decl(index.js, 2, 40)) + +Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>value : Symbol(value, Decl(index.js, 3, 38)) +>writable : Symbol(writable, Decl(index.js, 3, 54)) + +Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>get : Symbol(get, Decl(index.js, 4, 33)) +>set : Symbol(set, Decl(index.js, 4, 57)) +>_ : Symbol(_, Decl(index.js, 4, 62)) + +Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>get : Symbol(get, Decl(index.js, 5, 41)) + +Object.defineProperty(x, "zipStr", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(index.js, 6, 36)) +>str : Symbol(str, Decl(index.js, 8, 8)) + + this.zip = Number(str) +>zip : Symbol(zip, Decl(index.js, 8, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(index.js, 8, 8)) + } +}); + +/** + * @param {{name: string}} named + */ +function takeName(named) { return named.name; } +>takeName : Symbol(takeName, Decl(index.js, 11, 3)) +>named : Symbol(named, Decl(index.js, 16, 18)) +>named.name : Symbol(name, Decl(index.js, 14, 12)) +>named : Symbol(named, Decl(index.js, 16, 18)) +>name : Symbol(name, Decl(index.js, 14, 12)) + +takeName(x); +>takeName : Symbol(takeName, Decl(index.js, 11, 3)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + +/** + * @type {number} + */ +var a = x.zip; +>a : Symbol(a, Decl(index.js, 22, 3)) +>x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>zip : Symbol(x["zip"], Decl(index.js, 3, 74)) + +/** + * @type {number} + */ +var b = x.houseNumber; +>b : Symbol(b, Decl(index.js, 27, 3)) +>x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) + +const returnExemplar = () => x; +>returnExemplar : Symbol(returnExemplar, Decl(index.js, 29, 5)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + +const needsExemplar = (_ = x) => void 0; +>needsExemplar : Symbol(needsExemplar, Decl(index.js, 30, 5)) +>_ : Symbol(_, Decl(index.js, 30, 23)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + +const expected = /** @type {{name: string, readonly middleInit: string, readonly lastName: string, zip: number, readonly houseNumber: number, zipStr: string}} */(/** @type {*} */(null)); +>expected : Symbol(expected, Decl(index.js, 32, 5)) + +/** + * + * @param {typeof returnExemplar} a + * @param {typeof needsExemplar} b + */ +function match(a, b) {} +>match : Symbol(match, Decl(index.js, 32, 186)) +>a : Symbol(a, Decl(index.js, 39, 15)) +>b : Symbol(b, Decl(index.js, 39, 17)) + +match(() => expected, (x = expected) => void 0); +>match : Symbol(match, Decl(index.js, 32, 186)) +>expected : Symbol(expected, Decl(index.js, 32, 5)) +>x : Symbol(x, Decl(index.js, 41, 23)) +>expected : Symbol(expected, Decl(index.js, 32, 5)) + +module.exports = x; +>module.exports : Symbol("tests/cases/conformance/jsdoc/index", Decl(index.js, 0, 0)) +>module : Symbol(export=, Decl(index.js, 41, 48)) +>exports : Symbol(export=, Decl(index.js, 41, 48)) +>x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) + diff --git a/tests/baselines/reference/checkObjectDefineProperty.types b/tests/baselines/reference/checkObjectDefineProperty.types new file mode 100644 index 00000000000..88a1e682dfc --- /dev/null +++ b/tests/baselines/reference/checkObjectDefineProperty.types @@ -0,0 +1,255 @@ +=== tests/cases/conformance/jsdoc/validate.ts === +// Validate in TS as simple validations would usually be interpreted as more special assignments +import x = require("./"); +>x : typeof x + +x.name; +>x.name : string +>x : typeof x +>name : string + +x.middleInit; +>x.middleInit : string +>x : typeof x +>middleInit : string + +x.lastName; +>x.lastName : string +>x : typeof x +>lastName : string + +x.zip; +>x.zip : number +>x : typeof x +>zip : number + +x.houseNumber; +>x.houseNumber : number +>x : typeof x +>houseNumber : number + +x.zipStr; +>x.zipStr : string +>x : typeof x +>zipStr : string + +x.name = "Another"; +>x.name = "Another" : "Another" +>x.name : string +>x : typeof x +>name : string +>"Another" : "Another" + +x.zip = 98123; +>x.zip = 98123 : 98123 +>x.zip : number +>x : typeof x +>zip : number +>98123 : 98123 + +x.zipStr = "OK"; +>x.zipStr = "OK" : "OK" +>x.zipStr : string +>x : typeof x +>zipStr : string +>"OK" : "OK" + +x.lastName = "should fail"; +>x.lastName = "should fail" : "should fail" +>x.lastName : any +>x : typeof x +>lastName : any +>"should fail" : "should fail" + +x.houseNumber = 12; // should also fail +>x.houseNumber = 12 : 12 +>x.houseNumber : any +>x : typeof x +>houseNumber : any +>12 : 12 + +x.zipStr = 12; // should fail +>x.zipStr = 12 : 12 +>x.zipStr : string +>x : typeof x +>zipStr : string +>12 : 12 + +x.middleInit = "R"; // should also fail +>x.middleInit = "R" : "R" +>x.middleInit : any +>x : typeof x +>middleInit : any +>"R" : "R" + +=== tests/cases/conformance/jsdoc/index.js === +const x = {}; +>x : typeof x +>{} : {} + +Object.defineProperty(x, "name", { value: "Charles", writable: true }); +>Object.defineProperty(x, "name", { value: "Charles", writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"name" : "name" +>{ value: "Charles", writable: true } : { value: string; writable: true; } +>value : string +>"Charles" : "Charles" +>writable : true +>true : true + +Object.defineProperty(x, "middleInit", { value: "H" }); +>Object.defineProperty(x, "middleInit", { value: "H" }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"middleInit" : "middleInit" +>{ value: "H" } : { value: string; } +>value : string +>"H" : "H" + +Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); +>Object.defineProperty(x, "lastName", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"lastName" : "lastName" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"zip" : "zip" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }); +>Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"houseNumber" : "houseNumber" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(x, "zipStr", { +>Object.defineProperty(x, "zipStr", { /** @param {string} str */ set(str) { this.zip = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>x : typeof x +>"zipStr" : "zipStr" +>{ /** @param {string} str */ set(str) { this.zip = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.zip = Number(str) +>this.zip = Number(str) : number +>this.zip : any +>this : any +>zip : any +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); + +/** + * @param {{name: string}} named + */ +function takeName(named) { return named.name; } +>takeName : (named: { name: string; }) => string +>named : { name: string; } +>named.name : string +>named : { name: string; } +>name : string + +takeName(x); +>takeName(x) : string +>takeName : (named: { name: string; }) => string +>x : typeof x + +/** + * @type {number} + */ +var a = x.zip; +>a : number +>x.zip : number +>x : typeof x +>zip : number + +/** + * @type {number} + */ +var b = x.houseNumber; +>b : number +>x.houseNumber : number +>x : typeof x +>houseNumber : number + +const returnExemplar = () => x; +>returnExemplar : () => typeof x +>() => x : () => typeof x +>x : typeof x + +const needsExemplar = (_ = x) => void 0; +>needsExemplar : (_?: typeof x) => undefined +>(_ = x) => void 0 : (_?: typeof x) => undefined +>_ : typeof x +>x : typeof x +>void 0 : undefined +>0 : 0 + +const expected = /** @type {{name: string, readonly middleInit: string, readonly lastName: string, zip: number, readonly houseNumber: number, zipStr: string}} */(/** @type {*} */(null)); +>expected : { name: string; readonly middleInit: string; readonly lastName: string; zip: number; readonly houseNumber: number; zipStr: string; } +>(/** @type {*} */(null)) : { name: string; readonly middleInit: string; readonly lastName: string; zip: number; readonly houseNumber: number; zipStr: string; } +>(null) : any +>null : null + +/** + * + * @param {typeof returnExemplar} a + * @param {typeof needsExemplar} b + */ +function match(a, b) {} +>match : (a: () => typeof x, b: (_?: typeof x) => undefined) => void +>a : () => typeof x +>b : (_?: typeof x) => undefined + +match(() => expected, (x = expected) => void 0); +>match(() => expected, (x = expected) => void 0) : void +>match : (a: () => typeof x, b: (_?: typeof x) => undefined) => void +>() => expected : () => { name: string; readonly middleInit: string; readonly lastName: string; zip: number; readonly houseNumber: number; zipStr: string; } +>expected : { name: string; readonly middleInit: string; readonly lastName: string; zip: number; readonly houseNumber: number; zipStr: string; } +>(x = expected) => void 0 : (x?: typeof x | undefined) => undefined +>x : typeof x | undefined +>expected : { name: string; readonly middleInit: string; readonly lastName: string; zip: number; readonly houseNumber: number; zipStr: string; } +>void 0 : undefined +>0 : 0 + +module.exports = x; +>module.exports = x : typeof x +>module.exports : typeof x +>module : { "tests/cases/conformance/jsdoc/index": typeof x; } +>exports : typeof x +>x : typeof x + diff --git a/tests/baselines/reference/checkOtherObjectAssignProperty.errors.txt b/tests/baselines/reference/checkOtherObjectAssignProperty.errors.txt new file mode 100644 index 00000000000..146550d6fb6 --- /dev/null +++ b/tests/baselines/reference/checkOtherObjectAssignProperty.errors.txt @@ -0,0 +1,58 @@ +tests/cases/conformance/jsdoc/importer.js(3,5): error TS2339: Property 'other' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. +tests/cases/conformance/jsdoc/importer.js(4,5): error TS2339: Property 'prop' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. +tests/cases/conformance/jsdoc/importer.js(11,5): error TS2339: Property 'other' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. +tests/cases/conformance/jsdoc/importer.js(12,5): error TS2339: Property 'prop' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. +tests/cases/conformance/jsdoc/importer.js(13,5): error TS2540: Cannot assign to 'bad1' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/importer.js(14,5): error TS2540: Cannot assign to 'bad2' because it is a constant or a read-only property. +tests/cases/conformance/jsdoc/importer.js(15,5): error TS2540: Cannot assign to 'bad3' because it is a constant or a read-only property. + + +==== tests/cases/conformance/jsdoc/importer.js (7 errors) ==== + const mod = require("./mod1"); + mod.thing; + mod.other; + ~~~~~ +!!! error TS2339: Property 'other' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. + mod.prop; + ~~~~ +!!! error TS2339: Property 'prop' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. + mod.bad1; + mod.bad2; + mod.bad3; + + + mod.thing = 0; + mod.other = 0; + ~~~~~ +!!! error TS2339: Property 'other' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. + mod.prop = 0; + ~~~~ +!!! error TS2339: Property 'prop' does not exist on type 'typeof import("tests/cases/conformance/jsdoc/mod1")'. + mod.bad1 = 0; + ~~~~ +!!! error TS2540: Cannot assign to 'bad1' because it is a constant or a read-only property. + mod.bad2 = 0; + ~~~~ +!!! error TS2540: Cannot assign to 'bad2' because it is a constant or a read-only property. + mod.bad3 = 0; + ~~~~ +!!! error TS2540: Cannot assign to 'bad3' because it is a constant or a read-only property. + +==== tests/cases/conformance/jsdoc/mod1.js (0 errors) ==== + const obj = { value: 42, writable: true }; + Object.defineProperty(exports, "thing", obj); + + /** + * @type {string} + */ + let str = /** @type {string} */("other"); + Object.defineProperty(exports, str, { value: 42, writable: true }); + + const propName = "prop" + Object.defineProperty(exports, propName, { value: 42, writable: true }); + + + Object.defineProperty(exports, "bad1", { }); + Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }); + Object.defineProperty(exports, "bad3", { writable: true }); + \ No newline at end of file diff --git a/tests/baselines/reference/checkOtherObjectAssignProperty.symbols b/tests/baselines/reference/checkOtherObjectAssignProperty.symbols new file mode 100644 index 00000000000..efc0a463156 --- /dev/null +++ b/tests/baselines/reference/checkOtherObjectAssignProperty.symbols @@ -0,0 +1,121 @@ +=== tests/cases/conformance/jsdoc/importer.js === +const mod = require("./mod1"); +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>require : Symbol(require) +>"./mod1" : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) + +mod.thing; +>mod.thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>thing : Symbol("thing", Decl(mod1.js, 0, 42)) + +mod.other; +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) + +mod.prop; +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) + +mod.bad1; +>mod.bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) + +mod.bad2; +>mod.bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) + +mod.bad3; +>mod.bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) + + +mod.thing = 0; +>mod.thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>thing : Symbol("thing", Decl(mod1.js, 0, 42)) + +mod.other = 0; +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) + +mod.prop = 0; +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) + +mod.bad1 = 0; +>mod.bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) + +mod.bad2 = 0; +>mod.bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) + +mod.bad3 = 0; +>mod.bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) +>bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) + +=== tests/cases/conformance/jsdoc/mod1.js === +const obj = { value: 42, writable: true }; +>obj : Symbol(obj, Decl(mod1.js, 0, 5)) +>value : Symbol(value, Decl(mod1.js, 0, 13)) +>writable : Symbol(writable, Decl(mod1.js, 0, 24)) + +Object.defineProperty(exports, "thing", obj); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>obj : Symbol(obj, Decl(mod1.js, 0, 5)) + +/** + * @type {string} + */ +let str = /** @type {string} */("other"); +>str : Symbol(str, Decl(mod1.js, 6, 3)) + +Object.defineProperty(exports, str, { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>str : Symbol(str, Decl(mod1.js, 6, 3)) +>value : Symbol(value, Decl(mod1.js, 7, 37)) +>writable : Symbol(writable, Decl(mod1.js, 7, 48)) + +const propName = "prop" +>propName : Symbol(propName, Decl(mod1.js, 9, 5)) + +Object.defineProperty(exports, propName, { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>propName : Symbol(propName, Decl(mod1.js, 9, 5)) +>value : Symbol(value, Decl(mod1.js, 10, 42)) +>writable : Symbol(writable, Decl(mod1.js, 10, 53)) + + +Object.defineProperty(exports, "bad1", { }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) + +Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>get : Symbol(get, Decl(mod1.js, 14, 40)) +>value : Symbol(value, Decl(mod1.js, 14, 61)) + +Object.defineProperty(exports, "bad3", { writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>writable : Symbol(writable, Decl(mod1.js, 15, 40)) + diff --git a/tests/baselines/reference/checkOtherObjectAssignProperty.types b/tests/baselines/reference/checkOtherObjectAssignProperty.types new file mode 100644 index 00000000000..d9b68d71745 --- /dev/null +++ b/tests/baselines/reference/checkOtherObjectAssignProperty.types @@ -0,0 +1,170 @@ +=== tests/cases/conformance/jsdoc/importer.js === +const mod = require("./mod1"); +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>require("./mod1") : typeof import("tests/cases/conformance/jsdoc/mod1") +>require : any +>"./mod1" : "./mod1" + +mod.thing; +>mod.thing : number +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>thing : number + +mod.other; +>mod.other : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>other : any + +mod.prop; +>mod.prop : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>prop : any + +mod.bad1; +>mod.bad1 : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad1 : any + +mod.bad2; +>mod.bad2 : string +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad2 : string + +mod.bad3; +>mod.bad3 : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad3 : any + + +mod.thing = 0; +>mod.thing = 0 : 0 +>mod.thing : number +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>thing : number +>0 : 0 + +mod.other = 0; +>mod.other = 0 : 0 +>mod.other : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>other : any +>0 : 0 + +mod.prop = 0; +>mod.prop = 0 : 0 +>mod.prop : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>prop : any +>0 : 0 + +mod.bad1 = 0; +>mod.bad1 = 0 : 0 +>mod.bad1 : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad1 : any +>0 : 0 + +mod.bad2 = 0; +>mod.bad2 = 0 : 0 +>mod.bad2 : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad2 : any +>0 : 0 + +mod.bad3 = 0; +>mod.bad3 = 0 : 0 +>mod.bad3 : any +>mod : typeof import("tests/cases/conformance/jsdoc/mod1") +>bad3 : any +>0 : 0 + +=== tests/cases/conformance/jsdoc/mod1.js === +const obj = { value: 42, writable: true }; +>obj : { value: number; writable: boolean; } +>{ value: 42, writable: true } : { value: number; writable: boolean; } +>value : number +>42 : 42 +>writable : boolean +>true : true + +Object.defineProperty(exports, "thing", obj); +>Object.defineProperty(exports, "thing", obj) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"thing" : "thing" +>obj : { value: number; writable: boolean; } + +/** + * @type {string} + */ +let str = /** @type {string} */("other"); +>str : string +>("other") : string +>"other" : "other" + +Object.defineProperty(exports, str, { value: 42, writable: true }); +>Object.defineProperty(exports, str, { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>str : string +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + +const propName = "prop" +>propName : "prop" +>"prop" : "prop" + +Object.defineProperty(exports, propName, { value: 42, writable: true }); +>Object.defineProperty(exports, propName, { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>propName : "prop" +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + + +Object.defineProperty(exports, "bad1", { }); +>Object.defineProperty(exports, "bad1", { }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"bad1" : "bad1" +>{ } : {} + +Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }); +>Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"bad2" : "bad2" +>{ get() { return 12 }, value: "no" } : { get(): number; value: string; } +>get : () => number +>12 : 12 +>value : string +>"no" : "no" + +Object.defineProperty(exports, "bad3", { writable: true }); +>Object.defineProperty(exports, "bad3", { writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"bad3" : "bad3" +>{ writable: true } : { writable: true; } +>writable : true +>true : true + diff --git a/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.errors.txt b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.errors.txt new file mode 100644 index 00000000000..d7c036abacf --- /dev/null +++ b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.errors.txt @@ -0,0 +1,23 @@ +tests/cases/compiler/namespacer.js(2,1): error TS2323: Cannot redeclare exported variable 'NS'. +tests/cases/compiler/namespacer.js(3,1): error TS2323: Cannot redeclare exported variable 'NS'. + + +==== tests/cases/compiler/index.js (0 errors) ==== + const _item = require("./namespacer"); + module.exports = 12; + Object.defineProperty(module, "exports", { value: "oh no" }); + +==== tests/cases/compiler/namespacey.js (0 errors) ==== + const A = {} + A.bar = class Q {} + module.exports = A; +==== tests/cases/compiler/namespacer.js (2 errors) ==== + const B = {} + B.NS = require("./namespacey"); + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'NS'. + Object.defineProperty(B, "NS", { value: "why though", writable: true }); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'NS'. + module.exports = B; + \ No newline at end of file diff --git a/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols new file mode 100644 index 00000000000..5b0883f227a --- /dev/null +++ b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols @@ -0,0 +1,59 @@ +=== tests/cases/compiler/index.js === +const _item = require("./namespacer"); +>_item : Symbol(_item, Decl(index.js, 0, 5)) +>require : Symbol(require) +>"./namespacer" : Symbol("tests/cases/compiler/namespacer", Decl(namespacer.js, 0, 0)) + +module.exports = 12; +>module.exports : Symbol("tests/cases/compiler/index", Decl(index.js, 0, 0)) +>module : Symbol(export=, Decl(index.js, 0, 38)) +>exports : Symbol(export=, Decl(index.js, 0, 38)) + +Object.defineProperty(module, "exports", { value: "oh no" }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module : Symbol(module, Decl(index.js, 0, 38), Decl(index.js, 2, 22)) +>value : Symbol(value, Decl(index.js, 2, 42)) + +=== tests/cases/compiler/namespacey.js === +const A = {} +>A : Symbol(A, Decl(namespacey.js, 0, 5), Decl(namespacey.js, 0, 12)) + +A.bar = class Q {} +>A.bar : Symbol(A.bar, Decl(namespacey.js, 0, 12)) +>A : Symbol(A, Decl(namespacey.js, 0, 5), Decl(namespacey.js, 0, 12)) +>bar : Symbol(A.bar, Decl(namespacey.js, 0, 12)) +>Q : Symbol(Q, Decl(namespacey.js, 1, 7)) + +module.exports = A; +>module.exports : Symbol("tests/cases/compiler/namespacey", Decl(namespacey.js, 0, 0)) +>module : Symbol(export=, Decl(namespacey.js, 1, 18)) +>exports : Symbol(export=, Decl(namespacey.js, 1, 18)) +>A : Symbol(A, Decl(namespacey.js, 0, 5), Decl(namespacey.js, 0, 12)) + +=== tests/cases/compiler/namespacer.js === +const B = {} +>B : Symbol(B, Decl(namespacer.js, 0, 5), Decl(namespacer.js, 0, 12)) + +B.NS = require("./namespacey"); +>B.NS : Symbol(B.NS, Decl(namespacer.js, 0, 12), Decl(namespacer.js, 1, 31)) +>B : Symbol(B, Decl(namespacer.js, 0, 5), Decl(namespacer.js, 0, 12)) +>NS : Symbol(B.NS, Decl(namespacer.js, 0, 12), Decl(namespacer.js, 1, 31)) +>require : Symbol(require) +>"./namespacey" : Symbol("tests/cases/compiler/namespacey", Decl(namespacey.js, 0, 0)) + +Object.defineProperty(B, "NS", { value: "why though", writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>B : Symbol(B, Decl(namespacer.js, 0, 5), Decl(namespacer.js, 0, 12)) +>value : Symbol(value, Decl(namespacer.js, 2, 32)) +>writable : Symbol(writable, Decl(namespacer.js, 2, 53)) + +module.exports = B; +>module.exports : Symbol("tests/cases/compiler/namespacer", Decl(namespacer.js, 0, 0)) +>module : Symbol(export=, Decl(namespacer.js, 2, 72)) +>exports : Symbol(export=, Decl(namespacer.js, 2, 72)) +>B : Symbol(B, Decl(namespacer.js, 0, 5), Decl(namespacer.js, 0, 12)) + diff --git a/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.types b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.types new file mode 100644 index 00000000000..ebd6f7ba434 --- /dev/null +++ b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.types @@ -0,0 +1,79 @@ +=== tests/cases/compiler/index.js === +const _item = require("./namespacer"); +>_item : typeof B +>require("./namespacer") : typeof B +>require : any +>"./namespacer" : "./namespacer" + +module.exports = 12; +>module.exports = 12 : number +>module.exports : number +>module : typeof module +>exports : number +>12 : 12 + +Object.defineProperty(module, "exports", { value: "oh no" }); +>Object.defineProperty(module, "exports", { value: "oh no" }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module : typeof module +>"exports" : "exports" +>{ value: "oh no" } : { value: string; } +>value : string +>"oh no" : "oh no" + +=== tests/cases/compiler/namespacey.js === +const A = {} +>A : typeof A +>{} : {} + +A.bar = class Q {} +>A.bar = class Q {} : typeof Q +>A.bar : typeof Q +>A : typeof A +>bar : typeof Q +>class Q {} : typeof Q +>Q : typeof Q + +module.exports = A; +>module.exports = A : typeof A +>module.exports : typeof A +>module : { "tests/cases/compiler/namespacey": typeof A; } +>exports : typeof A +>A : typeof A + +=== tests/cases/compiler/namespacer.js === +const B = {} +>B : typeof B +>{} : {} + +B.NS = require("./namespacey"); +>B.NS = require("./namespacey") : typeof A +>B.NS : string | typeof A +>B : typeof B +>NS : string | typeof A +>require("./namespacey") : typeof A +>require : any +>"./namespacey" : "./namespacey" + +Object.defineProperty(B, "NS", { value: "why though", writable: true }); +>Object.defineProperty(B, "NS", { value: "why though", writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>B : typeof B +>"NS" : "NS" +>{ value: "why though", writable: true } : { value: string; writable: true; } +>value : string +>"why though" : "why though" +>writable : true +>true : true + +module.exports = B; +>module.exports = B : typeof B +>module.exports : typeof B +>module : { "tests/cases/compiler/namespacer": typeof B; } +>exports : typeof B +>B : typeof B + diff --git a/tests/cases/compiler/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.ts b/tests/cases/compiler/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.ts new file mode 100644 index 00000000000..a0c0b325adf --- /dev/null +++ b/tests/cases/compiler/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.ts @@ -0,0 +1,17 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @filename: namespacey.js +const A = {} +A.bar = class Q {} +module.exports = A; +// @filename: namespacer.js +const B = {} +B.NS = require("./namespacey"); +Object.defineProperty(B, "NS", { value: "why though", writable: true }); +module.exports = B; + +// @filename: index.js +const _item = require("./namespacer"); +module.exports = 12; +Object.defineProperty(module, "exports", { value: "oh no" }); diff --git a/tests/cases/conformance/jsdoc/checkExportsObjectAssignProperty.ts b/tests/cases/conformance/jsdoc/checkExportsObjectAssignProperty.ts new file mode 100644 index 00000000000..132fef04510 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkExportsObjectAssignProperty.ts @@ -0,0 +1,82 @@ +// @allowJs: true +// @noEmit: true +// @strict: true +// @checkJs: true +// @filename: mod1.js +Object.defineProperty(exports, "thing", { value: 42, writable: true }); +Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); +Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); +Object.defineProperty(exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } +}); + +// @filename: mod2.js +Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); +Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); +Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); +Object.defineProperty(module.exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } +}); + +// @filename: index.js + +/** + * @type {number} + */ +const q = require("./mod1").thing; + +/** + * @type {string} + */ +const u = require("./mod2").thing; + +// @filename: validator.ts +import "./"; + +import m1 = require("./mod1"); + +m1.thing; +m1.readonlyProp; +m1.rwAccessors; +m1.readonlyAccessor; +m1.setonlyAccessor; + +// allowed assignments +m1.thing = 10; +m1.rwAccessors = 11; +m1.setonlyAccessor = "yes"; + +// disallowed assignments +m1.readonlyProp = "name"; +m1.readonlyAccessor = 12; +m1.thing = "no"; +m1.rwAccessors = "no"; +m1.setonlyAccessor = 0; + +import m2 = require("./mod2"); + +m2.thing; +m2.readonlyProp; +m2.rwAccessors; +m2.readonlyAccessor; +m2.setonlyAccessor; + +// allowed assignments +m2.thing = "ok"; +m2.rwAccessors = 11; +m2.setonlyAccessor = "yes"; + +// disallowed assignments +m2.readonlyProp = "name"; +m2.readonlyAccessor = 12; +m2.thing = 0; +m2.rwAccessors = "no"; +m2.setonlyAccessor = 0; diff --git a/tests/cases/conformance/jsdoc/checkExportsObjectAssignPrototypeProperty.ts b/tests/cases/conformance/jsdoc/checkExportsObjectAssignPrototypeProperty.ts new file mode 100644 index 00000000000..9518e052646 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkExportsObjectAssignPrototypeProperty.ts @@ -0,0 +1,52 @@ +// @allowJs: true +// @noEmit: true +// @strict: true +// @checkJs: true +// @filename: mod1.js +/** + * @constructor + * @param {string} name + */ +function Person(name) { + this.name = name; +} +Person.prototype.describe = function () { + return "Person called " + this.name; +}; +Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); +Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); +Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); +Object.defineProperty(Person.prototype, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } +}); +module.exports = Person; + +// @filename: validator.ts +import "./"; + +import Person = require("./mod1"); + +const m1 = new Person("Name") + +m1.thing; +m1.readonlyProp; +m1.rwAccessors; +m1.readonlyAccessor; +m1.setonlyAccessor; + +// allowed assignments +m1.thing = 10; +m1.rwAccessors = 11; +m1.setonlyAccessor = "yes"; + +// disallowed assignments +m1.readonlyProp = "name"; +m1.readonlyAccessor = 12; +m1.thing = "no"; +m1.rwAccessors = "no"; +m1.setonlyAccessor = 0; + diff --git a/tests/cases/conformance/jsdoc/checkObjectDefineProperty.ts b/tests/cases/conformance/jsdoc/checkObjectDefineProperty.ts new file mode 100644 index 00000000000..d0ba377b000 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkObjectDefineProperty.ts @@ -0,0 +1,68 @@ +// @allowJs: true +// @noEmit: true +// @strict: true +// @checkJs: true +// @filename: index.js +const x = {}; +Object.defineProperty(x, "name", { value: "Charles", writable: true }); +Object.defineProperty(x, "middleInit", { value: "H" }); +Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); +Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } }); +Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }); +Object.defineProperty(x, "zipStr", { + /** @param {string} str */ + set(str) { + this.zip = Number(str) + } +}); + +/** + * @param {{name: string}} named + */ +function takeName(named) { return named.name; } + +takeName(x); +/** + * @type {number} + */ +var a = x.zip; + +/** + * @type {number} + */ +var b = x.houseNumber; + +const returnExemplar = () => x; +const needsExemplar = (_ = x) => void 0; + +const expected = /** @type {{name: string, readonly middleInit: string, readonly lastName: string, zip: number, readonly houseNumber: number, zipStr: string}} */(/** @type {*} */(null)); + +/** + * + * @param {typeof returnExemplar} a + * @param {typeof needsExemplar} b + */ +function match(a, b) {} + +match(() => expected, (x = expected) => void 0); + +module.exports = x; + +// @filename: validate.ts +// Validate in TS as simple validations would usually be interpreted as more special assignments +import x = require("./"); +x.name; +x.middleInit; +x.lastName; +x.zip; +x.houseNumber; +x.zipStr; + +x.name = "Another"; +x.zip = 98123; +x.zipStr = "OK"; + +x.lastName = "should fail"; +x.houseNumber = 12; // should also fail +x.zipStr = 12; // should fail +x.middleInit = "R"; // should also fail diff --git a/tests/cases/conformance/jsdoc/checkOtherObjectAssignProperty.ts b/tests/cases/conformance/jsdoc/checkOtherObjectAssignProperty.ts new file mode 100644 index 00000000000..a7bccc65283 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkOtherObjectAssignProperty.ts @@ -0,0 +1,39 @@ +// @allowJs: true +// @noEmit: true +// @strict: true +// @checkJs: true +// @filename: mod1.js + +const obj = { value: 42, writable: true }; +Object.defineProperty(exports, "thing", obj); + +/** + * @type {string} + */ +let str = /** @type {string} */("other"); +Object.defineProperty(exports, str, { value: 42, writable: true }); + +const propName = "prop" +Object.defineProperty(exports, propName, { value: 42, writable: true }); + + +Object.defineProperty(exports, "bad1", { }); +Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }); +Object.defineProperty(exports, "bad3", { writable: true }); + +// @filename: importer.js +const mod = require("./mod1"); +mod.thing; +mod.other; +mod.prop; +mod.bad1; +mod.bad2; +mod.bad3; + + +mod.thing = 0; +mod.other = 0; +mod.prop = 0; +mod.bad1 = 0; +mod.bad2 = 0; +mod.bad3 = 0; diff --git a/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile1.ts b/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile1.ts new file mode 100644 index 00000000000..4dd0654a897 --- /dev/null +++ b/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile1.ts @@ -0,0 +1,20 @@ +/// + +// @allowJs: true +// @allowSyntheticDefaultImports: true + +// @Filename: /a.js +////exports.__esModule = true; +////exports.default = f; +/////** +//// * Run this function +//// * @param {string} t +//// */ +////function f(t) {} + +// @Filename: /b.js +////import f from "./a" +/////**/f + +verify.quickInfoAt("", `(alias) (property) f: (t: string) => void +import f`, "Run this function"); // Passes \ No newline at end of file diff --git a/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile2.ts b/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile2.ts new file mode 100644 index 00000000000..0cfb4e68454 --- /dev/null +++ b/tests/cases/fourslash/syntheticImportFromBabelGeneratedFile2.ts @@ -0,0 +1,22 @@ +/// + +// @allowJs: true +// @allowSyntheticDefaultImports: true + +// @Filename: /a.js +////Object.defineProperty(exports, "__esModule", { +//// value: true +////}); +////exports.default = f; +/////** +//// * Run this function +//// * @param {string} t +//// */ +////function f(t) {} + +// @Filename: /b.js +////import f from "./a" +/////**/f + +verify.quickInfoAt("", `(alias) (property) f: (t: string) => void +import f`, "Run this function"); // Passes \ No newline at end of file From 71d8961ba017f319e63b3e4810f4570647655e70 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 19 Oct 2018 15:59:50 -0700 Subject: [PATCH 080/262] Do not do any reduction (even if it contains any) to the union type when getting contextual type Fixes #27975 --- src/compiler/checker.ts | 66 +++++++++++-------- .../reference/unionTypeWithIndexAndTuple.js | 11 ++++ .../unionTypeWithIndexAndTuple.symbols | 18 +++++ .../unionTypeWithIndexAndTuple.types | 18 +++++ .../compiler/unionTypeWithIndexAndTuple.ts | 6 ++ 5 files changed, 90 insertions(+), 29 deletions(-) create mode 100644 tests/baselines/reference/unionTypeWithIndexAndTuple.js create mode 100644 tests/baselines/reference/unionTypeWithIndexAndTuple.symbols create mode 100644 tests/baselines/reference/unionTypeWithIndexAndTuple.types create mode 100644 tests/cases/compiler/unionTypeWithIndexAndTuple.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ea5e27c2c9e..46bd9a48b00 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8855,10 +8855,10 @@ namespace ts { return false; } - function addTypeToUnion(typeSet: Type[], includes: TypeFlags, type: Type) { + function addTypeToUnion(typeSet: Type[], includes: TypeFlags, type: Type, noReduction: boolean) { const flags = type.flags; if (flags & TypeFlags.Union) { - return addTypesToUnion(typeSet, includes, (type).types); + return addTypesToUnion(typeSet, includes, (type).types, noReduction); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn @@ -8866,28 +8866,35 @@ namespace ts { // easier to reason about their origin. if (!(flags & TypeFlags.Never || flags & TypeFlags.Intersection && isEmptyIntersectionType(type))) { includes |= flags & ~TypeFlags.ConstructionFlags; - if (flags & TypeFlags.AnyOrUnknown) { + if (noReduction) { + addTypeToTypeSet(typeSet, type); + } + else if (flags & TypeFlags.AnyOrUnknown) { if (type === wildcardType) includes |= TypeFlags.Wildcard; } else if (!strictNullChecks && flags & TypeFlags.Nullable) { if (!(flags & TypeFlags.ContainsWideningType)) includes |= TypeFlags.NonWideningType; } else { - const len = typeSet.length; - const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); - if (index < 0) { - typeSet.splice(~index, 0, type); - } + addTypeToTypeSet(typeSet, type); } } return includes; } + function addTypeToTypeSet(typeSet: Type[], type: Type) { + const len = typeSet.length; + const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray): TypeFlags { + function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray, noReduction: boolean): TypeFlags { for (const type of types) { - includes = addTypeToUnion(typeSet, includes, type); + includes = addTypeToUnion(typeSet, includes, type, noReduction); } return includes; } @@ -8964,24 +8971,26 @@ namespace ts { return types[0]; } const typeSet: Type[] = []; - const includes = addTypesToUnion(typeSet, 0, types); - if (includes & TypeFlags.AnyOrUnknown) { - return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; - } - switch (unionReduction) { - case UnionReduction.Literal: - if (includes & TypeFlags.StringOrNumberLiteralOrUnique | TypeFlags.BooleanLiteral) { - removeRedundantLiteralTypes(typeSet, includes); - } - break; - case UnionReduction.Subtype: - removeSubtypes(typeSet); - break; - } - if (typeSet.length === 0) { - return includes & TypeFlags.Null ? includes & TypeFlags.NonWideningType ? nullType : nullWideningType : - includes & TypeFlags.Undefined ? includes & TypeFlags.NonWideningType ? undefinedType : undefinedWideningType : - neverType; + const includes = addTypesToUnion(typeSet, 0, types, unionReduction === UnionReduction.None); + if (unionReduction !== UnionReduction.None) { + if (includes & TypeFlags.AnyOrUnknown) { + return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; + } + switch (unionReduction) { + case UnionReduction.Literal: + if (includes & TypeFlags.StringOrNumberLiteralOrUnique | TypeFlags.BooleanLiteral) { + removeRedundantLiteralTypes(typeSet, includes); + } + break; + case UnionReduction.Subtype: + removeSubtypes(typeSet); + break; + } + if (typeSet.length === 0) { + return includes & TypeFlags.Null ? includes & TypeFlags.NonWideningType ? nullType : nullWideningType : + includes & TypeFlags.Undefined ? includes & TypeFlags.NonWideningType ? undefinedType : undefinedWideningType : + neverType; + } } return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : TypeFlags.UnionOfPrimitiveTypes, aliasSymbol, aliasTypeArguments); } @@ -16868,7 +16877,6 @@ namespace ts { function getContextualTypeForElementExpression(arrayContextualType: Type | undefined, index: number): Type | undefined { return arrayContextualType && ( getTypeOfPropertyOfContextualType(arrayContextualType, "" + index as __String) - || getIndexTypeOfContextualType(arrayContextualType, IndexKind.Number) || getIteratedTypeOrElementType(arrayContextualType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false)); } diff --git a/tests/baselines/reference/unionTypeWithIndexAndTuple.js b/tests/baselines/reference/unionTypeWithIndexAndTuple.js new file mode 100644 index 00000000000..7fc5ba607b4 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndTuple.js @@ -0,0 +1,11 @@ +//// [unionTypeWithIndexAndTuple.ts] +interface I { + [index: number]: any; + someOtherProperty: number; +} +function f(args: ["a"] | I) { } +f(["a"]); + +//// [unionTypeWithIndexAndTuple.js] +function f(args) { } +f(["a"]); diff --git a/tests/baselines/reference/unionTypeWithIndexAndTuple.symbols b/tests/baselines/reference/unionTypeWithIndexAndTuple.symbols new file mode 100644 index 00000000000..b8978fd5b6a --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndTuple.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/unionTypeWithIndexAndTuple.ts === +interface I { +>I : Symbol(I, Decl(unionTypeWithIndexAndTuple.ts, 0, 0)) + + [index: number]: any; +>index : Symbol(index, Decl(unionTypeWithIndexAndTuple.ts, 1, 5)) + + someOtherProperty: number; +>someOtherProperty : Symbol(I.someOtherProperty, Decl(unionTypeWithIndexAndTuple.ts, 1, 25)) +} +function f(args: ["a"] | I) { } +>f : Symbol(f, Decl(unionTypeWithIndexAndTuple.ts, 3, 1)) +>args : Symbol(args, Decl(unionTypeWithIndexAndTuple.ts, 4, 11)) +>I : Symbol(I, Decl(unionTypeWithIndexAndTuple.ts, 0, 0)) + +f(["a"]); +>f : Symbol(f, Decl(unionTypeWithIndexAndTuple.ts, 3, 1)) + diff --git a/tests/baselines/reference/unionTypeWithIndexAndTuple.types b/tests/baselines/reference/unionTypeWithIndexAndTuple.types new file mode 100644 index 00000000000..6b7ec0d3659 --- /dev/null +++ b/tests/baselines/reference/unionTypeWithIndexAndTuple.types @@ -0,0 +1,18 @@ +=== tests/cases/compiler/unionTypeWithIndexAndTuple.ts === +interface I { + [index: number]: any; +>index : number + + someOtherProperty: number; +>someOtherProperty : number +} +function f(args: ["a"] | I) { } +>f : (args: I | ["a"]) => void +>args : I | ["a"] + +f(["a"]); +>f(["a"]) : void +>f : (args: I | ["a"]) => void +>["a"] : ["a"] +>"a" : "a" + diff --git a/tests/cases/compiler/unionTypeWithIndexAndTuple.ts b/tests/cases/compiler/unionTypeWithIndexAndTuple.ts new file mode 100644 index 00000000000..56fea3d7726 --- /dev/null +++ b/tests/cases/compiler/unionTypeWithIndexAndTuple.ts @@ -0,0 +1,6 @@ +interface I { + [index: number]: any; + someOtherProperty: number; +} +function f(args: ["a"] | I) { } +f(["a"]); \ No newline at end of file From bf393ae1cd25ae3921ffa41b4385fc2ec14c212f Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 19 Oct 2018 16:23:34 -0700 Subject: [PATCH 081/262] Check EOF token to get errors for JSDoc (#28000) * Check EOF token to get errors for JSDoc * outputFile instead of noEmit for test --- src/compiler/checker.ts | 1 + .../reference/checkJsdocOnEndOfFile.errors.txt | 10 ++++++++++ tests/baselines/reference/checkJsdocOnEndOfFile.js | 10 ++++++++++ .../baselines/reference/checkJsdocOnEndOfFile.symbols | 6 ++++++ tests/baselines/reference/checkJsdocOnEndOfFile.types | 6 ++++++ tests/cases/conformance/jsdoc/checkJsdocOnEndOfFile.ts | 8 ++++++++ 6 files changed, 41 insertions(+) create mode 100644 tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt create mode 100644 tests/baselines/reference/checkJsdocOnEndOfFile.js create mode 100644 tests/baselines/reference/checkJsdocOnEndOfFile.symbols create mode 100644 tests/baselines/reference/checkJsdocOnEndOfFile.types create mode 100644 tests/cases/conformance/jsdoc/checkJsdocOnEndOfFile.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ea5e27c2c9e..885396e7d73 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -27305,6 +27305,7 @@ namespace ts { clear(potentialNewTargetCollisions); forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt b/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt new file mode 100644 index 00000000000..4dc2320dcd8 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/jsdoc/eof.js(2,20): error TS2304: Cannot find name 'bad'. + + +==== tests/cases/conformance/jsdoc/eof.js (1 errors) ==== + /** + * @typedef {Array} Should have error here + ~~~ +!!! error TS2304: Cannot find name 'bad'. + */ + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.js b/tests/baselines/reference/checkJsdocOnEndOfFile.js new file mode 100644 index 00000000000..a9d07d45e54 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.js @@ -0,0 +1,10 @@ +//// [eof.js] +/** + * @typedef {Array} Should have error here + */ + + +//// [output.js] +/** + * @typedef {Array} Should have error here + */ diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.symbols b/tests/baselines/reference/checkJsdocOnEndOfFile.symbols new file mode 100644 index 00000000000..bda09fa653e --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/jsdoc/eof.js === +/** +No type information for this code. * @typedef {Array} Should have error here +No type information for this code. */ +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.types b/tests/baselines/reference/checkJsdocOnEndOfFile.types new file mode 100644 index 00000000000..bda09fa653e --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/jsdoc/eof.js === +/** +No type information for this code. * @typedef {Array} Should have error here +No type information for this code. */ +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/cases/conformance/jsdoc/checkJsdocOnEndOfFile.ts b/tests/cases/conformance/jsdoc/checkJsdocOnEndOfFile.ts new file mode 100644 index 00000000000..f9f3157084d --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkJsdocOnEndOfFile.ts @@ -0,0 +1,8 @@ +// @outFile: output.js +// @allowJs: true +// @checkJs: true +// @Filename: eof.js + +/** + * @typedef {Array} Should have error here + */ From 72244c5b03ec13a77088c4b2f016708007655ce0 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 19 Oct 2018 18:00:45 -0700 Subject: [PATCH 082/262] Support 'isSourceFileFromExternalLibrary' for source files from '/// '' (#28004) * Support 'isSourceFileFromExternalLibrary' for source files from '/// '' * Calculate `isExternalLibraryImport` at the end * Calculate isExternalLibraryImport with symlink path --- src/compiler/moduleNameResolver.ts | 27 ++++++++++--------- src/compiler/program.ts | 4 +++ src/compiler/resolutionCache.ts | 2 +- src/compiler/types.ts | 2 ++ .../unittests/programMissingFiles.ts | 23 +++++++++++----- .../reference/api/tsserverlibrary.d.ts | 2 ++ tests/baselines/reference/api/typescript.d.ts | 2 ++ tests/baselines/reference/typingsLookup4.js | 8 ------ 8 files changed, 43 insertions(+), 27 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index c09c9542055..99b65c8946e 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -298,14 +298,12 @@ namespace ts { let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; if (resolved) { - if (!options.preserveSymlinks) { - resolved = { ...resolved, fileName: realPath(resolved.fileName, host, traceEnabled) }; - } - + const { fileName, packageId } = resolved; + const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled); if (traceEnabled) { - trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved.fileName, primary); + trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary); } - resolvedTypeReferenceDirective = { primary, resolvedFileName: resolved.fileName, packageId: resolved.packageId }; + resolvedTypeReferenceDirective = { primary, resolvedFileName, packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) }; } return { resolvedTypeReferenceDirective, failedLookupLocations }; @@ -316,7 +314,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); } - return forEach(typeRoots, typeRoot => { + return firstDefined(typeRoots, typeRoot => { const candidate = combinePaths(typeRoot, typeReferenceDirectiveName); const candidateDirectory = getDirectoryPath(candidate); const directoryExists = directoryProbablyExists(candidateDirectory, host); @@ -343,15 +341,16 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - let result: SearchResult | undefined; + let result: Resolved | undefined; if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) { - result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + const searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined); + result = searchResult && searchResult.value; } else { const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)); - result = toSearchResult(nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true)); + result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true); } - const resolvedFile = resolvedTypeScriptOnly(result && result.value); + const resolvedFile = resolvedTypeScriptOnly(result); if (!resolvedFile && traceEnabled) { trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -883,7 +882,7 @@ namespace ts { const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { - return toSearchResult({ resolved, isExternalLibraryImport: stringContains(resolved.path, nodeModulesPathPart) }); + return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!isExternalModuleNameRelative(moduleName)) { @@ -960,6 +959,10 @@ namespace ts { /*@internal*/ export const nodeModulesPathPart = "/node_modules/"; + /*@internal*/ + export function pathContainsNodeModules(path: string): boolean { + return stringContains(path, nodeModulesPathPart); + } /** * This will be called on the successfully resolved path from `loadModuleFromFile`. diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 7544b081fcd..3c3c1ff5db2 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2345,6 +2345,8 @@ namespace ts { } let saveResolution = true; if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; + if (resolvedTypeReferenceDirective.primary) { // resolved from the primary path processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 @@ -2373,6 +2375,8 @@ namespace ts { processSourceFile(resolvedTypeReferenceDirective.resolvedFileName!, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); } } + + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; } else { fileProcessingDiagnostics.add(createDiagnostic(refFile!, refPos!, refEnd!, Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index b462ab96b1a..9a2e62706b3 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -432,7 +432,7 @@ namespace ts { function getDirectoryToWatchFromFailedLookupLocationDirectory(dir: string, dirPath: Path) { // If directory path contains node module, get the most parent node_modules directory for watching - while (stringContains(dirPath, nodeModulesPathPart)) { + while (pathContainsNodeModules(dirPath)) { dir = getDirectoryPath(dir); dirPath = getDirectoryPath(dirPath); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index fe31a30a30f..1c2009bc19f 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4942,6 +4942,8 @@ namespace ts { // The location of the .d.ts file we located, or undefined if resolution failed resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { diff --git a/src/testRunner/unittests/programMissingFiles.ts b/src/testRunner/unittests/programMissingFiles.ts index eb68e3bd665..55dfa7f5cc2 100644 --- a/src/testRunner/unittests/programMissingFiles.ts +++ b/src/testRunner/unittests/programMissingFiles.ts @@ -113,12 +113,23 @@ namespace ts { const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, bar, barFooPackage, barFooIndex, fooPackage, fooIndex], cwd: "/" }); const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); - - for (const file of [a, bar, barFooIndex, fooIndex]) { - const isExternalExpected = file !== a; - const isExternalActual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); - assert.equal(isExternalActual, isExternalExpected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${isExternalExpected}, got ${isExternalActual}`); - } + assertIsExternal(program, [a, bar, barFooIndex, fooIndex], f => f !== a); }); + + it('works on `/// `', () => { + const a = new documents.TextDocument("/a.ts", '/// '); + const fooIndex = new documents.TextDocument("/node_modules/foo/index.d.ts", "declare const foo: number;"); + const fs = vfs.createFromFileSystem(Harness.IO, /*ignoreCase*/ false, { documents: [a, fooIndex], cwd: "/" }); + const program = createProgram(["/a.ts"], emptyOptions, new fakes.CompilerHost(fs, { newLine: NewLineKind.LineFeed })); + assertIsExternal(program, [a, fooIndex], f => f !== a); + }); + + function assertIsExternal(program: Program, files: ReadonlyArray, isExternalExpected: (file: documents.TextDocument) => boolean): void { + for (const file of files) { + const actual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!); + const expected = isExternalExpected(file); + assert.equal(actual, expected, `Expected ${file.file} isSourceFileFromExternalLibrary to be ${expected}, got ${actual}`); + } + } }); } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index a7e8d3e5690..1680826b31f 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2670,6 +2670,8 @@ declare namespace ts { primary: boolean; resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 0c2485d1a25..a7c3f9cd902 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2670,6 +2670,8 @@ declare namespace ts { primary: boolean; resolvedFileName: string | undefined; packageId?: PackageId; + /** True if `resolvedFileName` comes from `node_modules`. */ + isExternalLibraryImport?: boolean; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; diff --git a/tests/baselines/reference/typingsLookup4.js b/tests/baselines/reference/typingsLookup4.js index d2424644d16..a464bb59faf 100644 --- a/tests/baselines/reference/typingsLookup4.js +++ b/tests/baselines/reference/typingsLookup4.js @@ -32,14 +32,6 @@ import { m } from "mquery"; j + k + l + m; -//// [lquery.js] -"use strict"; -exports.__esModule = true; -exports.l = 2; -//// [index.js] -"use strict"; -exports.__esModule = true; -exports.m = 3; //// [a.js] "use strict"; exports.__esModule = true; From 033ea4c2325400041af773ca37aa33f621a95699 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 21 Oct 2018 09:12:52 -0700 Subject: [PATCH 083/262] Simplify addTypeToUnion function --- src/compiler/checker.ts | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 327004f776d..9fab5821e4e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8855,10 +8855,10 @@ namespace ts { return false; } - function addTypeToUnion(typeSet: Type[], includes: TypeFlags, type: Type, noReduction: boolean) { + function addTypeToUnion(typeSet: Type[], includes: TypeFlags, type: Type) { const flags = type.flags; if (flags & TypeFlags.Union) { - return addTypesToUnion(typeSet, includes, (type).types, noReduction); + return addTypesToUnion(typeSet, includes, (type).types); } // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are // another form of 'never' (in that they have an empty value domain). We could in theory turn @@ -8866,35 +8866,26 @@ namespace ts { // easier to reason about their origin. if (!(flags & TypeFlags.Never || flags & TypeFlags.Intersection && isEmptyIntersectionType(type))) { includes |= flags & ~TypeFlags.ConstructionFlags; - if (noReduction) { - addTypeToTypeSet(typeSet, type); - } - else if (flags & TypeFlags.AnyOrUnknown) { - if (type === wildcardType) includes |= TypeFlags.Wildcard; - } - else if (!strictNullChecks && flags & TypeFlags.Nullable) { + if (type === wildcardType) includes |= TypeFlags.Wildcard; + if (!strictNullChecks && flags & TypeFlags.Nullable) { if (!(flags & TypeFlags.ContainsWideningType)) includes |= TypeFlags.NonWideningType; } else { - addTypeToTypeSet(typeSet, type); + const len = typeSet.length; + const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); + if (index < 0) { + typeSet.splice(~index, 0, type); + } } } return includes; } - function addTypeToTypeSet(typeSet: Type[], type: Type) { - const len = typeSet.length; - const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); - if (index < 0) { - typeSet.splice(~index, 0, type); - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray, noReduction: boolean): TypeFlags { + function addTypesToUnion(typeSet: Type[], includes: TypeFlags, types: ReadonlyArray): TypeFlags { for (const type of types) { - includes = addTypeToUnion(typeSet, includes, type, noReduction); + includes = addTypeToUnion(typeSet, includes, type); } return includes; } @@ -8971,7 +8962,7 @@ namespace ts { return types[0]; } const typeSet: Type[] = []; - const includes = addTypesToUnion(typeSet, 0, types, unionReduction === UnionReduction.None); + const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== UnionReduction.None) { if (includes & TypeFlags.AnyOrUnknown) { return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; From ea0c7eb3ce23cec6f60dcf4b4c0af208e61ba29a Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Sun, 21 Oct 2018 18:15:01 +0200 Subject: [PATCH 084/262] Fix performance regression when reusing old state Fixes: #28025 --- src/compiler/program.ts | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 3c3c1ff5db2..144ea62098d 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -594,7 +594,7 @@ namespace ts { let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: UnderscoreEscapedMap; - let modifiedFilePaths: Path[] | undefined; + let unmodifiedSourceFilesWithAmbientModules: SourceFile[] | undefined; const cachedSemanticDiagnosticsForFile: DiagnosticCache = {}; const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {}; @@ -880,21 +880,14 @@ namespace ts { return classifiableNames; } - interface OldProgramState { - program: Program | undefined; - oldSourceFile: SourceFile | undefined; - /** The collection of paths modified *since* the old program. */ - modifiedFilePaths: Path[] | undefined; - } - - function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile, oldProgramState: OldProgramState) { + function resolveModuleNamesReusingOldState(moduleNames: string[], containingFile: string, file: SourceFile) { if (structuralIsReused === StructureIsReused.Not && !file.ambientModuleNames.length) { // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, // the best we can do is fallback to the default logic. return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName)); } - const oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + const oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { // `file` was created for the new program. // @@ -958,7 +951,7 @@ namespace ts { } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { @@ -1001,12 +994,9 @@ namespace ts { // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState: OldProgramState): boolean { - if (!oldProgramState.program) { - return false; - } - const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile!, moduleName); // TODO: GH#18217 - const resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string): boolean { + const resolutionToFile = getResolvedModule(oldSourceFile!, moduleName); + const resolvedFile = resolutionToFile && oldProgram!.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -1016,8 +1006,8 @@ namespace ts { } // at least one of declarations should come from non-modified source file - const firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find( - f => !contains(oldProgramState.modifiedFilePaths, f.path) && contains(f.ambientModuleNames, moduleName) + const firstUnmodifiedFile = unmodifiedSourceFilesWithAmbientModules && unmodifiedSourceFilesWithAmbientModules.find( + f => contains(f.ambientModuleNames, moduleName) ); if (!firstUnmodifiedFile) { @@ -1213,14 +1203,14 @@ namespace ts { return oldProgram.structureIsReused; } - modifiedFilePaths = modifiedSourceFiles.map(f => f.newFile.path); + const modifiedFiles = modifiedSourceFiles.map(f => f.oldFile); + unmodifiedSourceFilesWithAmbientModules = oldSourceFiles.filter((f) => !!f.ambientModuleNames.length && !contains(modifiedFiles, f)); // try to verify results of module resolution for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); if (resolveModuleNamesWorker) { const moduleNames = getModuleNames(newSourceFile); - const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile, modifiedFilePaths }; - const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile); // ensure that module resolution results are still correct const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo); if (resolutionsChanged) { @@ -2422,8 +2412,7 @@ namespace ts { if (file.imports.length || file.moduleAugmentations.length) { // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. const moduleNames = getModuleNames(file); - const oldProgramState: OldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths }; - const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file, oldProgramState); + const resolutions = resolveModuleNamesReusingOldState(moduleNames, getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file); Debug.assert(resolutions.length === moduleNames.length); for (let i = 0; i < moduleNames.length; i++) { const resolution = resolutions[i]; From 63a8cb6933d9a78dde7f5e5df7b01417a812968c Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Sun, 21 Oct 2018 19:57:23 +0200 Subject: [PATCH 085/262] use Map instead of Array --- src/compiler/program.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 144ea62098d..896613b549c 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -594,7 +594,7 @@ namespace ts { let diagnosticsProducingTypeChecker: TypeChecker; let noDiagnosticsTypeChecker: TypeChecker; let classifiableNames: UnderscoreEscapedMap; - let unmodifiedSourceFilesWithAmbientModules: SourceFile[] | undefined; + const ambientModuleNameToUnmodifiedFileName = createMap(); const cachedSemanticDiagnosticsForFile: DiagnosticCache = {}; const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {}; @@ -1006,16 +1006,14 @@ namespace ts { } // at least one of declarations should come from non-modified source file - const firstUnmodifiedFile = unmodifiedSourceFilesWithAmbientModules && unmodifiedSourceFilesWithAmbientModules.find( - f => contains(f.ambientModuleNames, moduleName) - ); + const unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName); - if (!firstUnmodifiedFile) { + if (!unmodifiedFile) { return false; } if (isTraceEnabled(options, host)) { - trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile); } return true; } @@ -1204,7 +1202,13 @@ namespace ts { } const modifiedFiles = modifiedSourceFiles.map(f => f.oldFile); - unmodifiedSourceFilesWithAmbientModules = oldSourceFiles.filter((f) => !!f.ambientModuleNames.length && !contains(modifiedFiles, f)); + for (const oldFile of oldSourceFiles) { + if (!contains(modifiedFiles, oldFile)) { + for (const moduleName of oldFile.ambientModuleNames) { + ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName); + } + } + } // try to verify results of module resolution for (const { oldFile: oldSourceFile, newFile: newSourceFile } of modifiedSourceFiles) { const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory); From 778f438a7f5863af55e840a9e76c41d7e76ba658 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Mon, 22 Oct 2018 10:15:46 -0700 Subject: [PATCH 086/262] Update user baselines (#28047) --- tests/baselines/reference/user/async.log | 3 ++ .../user/chrome-devtools-frontend.log | 47 ++++++++++++++++--- tests/baselines/reference/user/npm.log | 14 ------ 3 files changed, 43 insertions(+), 21 deletions(-) diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 32b54ba4a0e..ceb25237c7b 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -582,9 +582,11 @@ node_modules/async/priorityQueue.js(9,14): error TS2695: Left side of comma oper node_modules/async/priorityQueue.js(18,15): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/priorityQueue.js(23,21): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/priorityQueue.js(47,10): error TS2695: Left side of comma operator is unused and has no side effects. +node_modules/async/priorityQueue.js(86,12): error TS2304: Cannot find name 'AsyncFunction'. node_modules/async/priorityQueue.js(93,20): error TS1005: '}' expected. node_modules/async/queue.js(8,18): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/queue.js(9,11): error TS2695: Left side of comma operator is unused and has no side effects. +node_modules/async/queue.js(91,12): error TS2304: Cannot find name 'AsyncFunction'. node_modules/async/queue.js(97,20): error TS1005: '}' expected. node_modules/async/race.js(63,17): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/race.js(64,11): error TS2695: Left side of comma operator is unused and has no side effects. @@ -618,6 +620,7 @@ node_modules/async/retryable.js(12,18): error TS2695: Left side of comma operato node_modules/async/retryable.js(13,13): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/retryable.js(18,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/retryable.js(18,70): error TS2695: Left side of comma operator is unused and has no side effects. +node_modules/async/retryable.js(51,12): error TS2304: Cannot find name 'AsyncFunction'. node_modules/async/select.js(44,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/selectLimit.js(36,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/selectSeries.js(34,20): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 77638fea091..597f7977219 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -2833,10 +2833,14 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,11): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,32): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60268,1): error TS2304: Cannot find name 'define'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60346,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60397,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60430,8): error TS2339: Property 'errors' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60436,1): error TS2323: Cannot redeclare exported variable 'Syntax'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60446,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60601,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60602,1): error TS2323: Cannot redeclare exported variable 'Syntax'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60688,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60728,13): error TS2339: Property 'match' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,6): error TS2339: Property 'scanner' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,25): error TS2339: Property 'startMarker' does not exist on type 'JSXParser'. @@ -2999,6 +3003,11 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61200,9): error TS2339: Property 'config' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61201,6): error TS2339: Property 'tokens' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61209,62): error TS2339: Property 'match' does not exist on type 'JSXParser'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61221,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61281,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61386,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61407,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62087,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62832,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'id' must be of type 'string', but here has type 'any'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63482,12): error TS2339: Property 'message' does not exist on type '{ simple: boolean; paramSet: {}; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63483,39): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; paramSet: {}; }'. @@ -3010,12 +3019,19 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64518,9): error TS2551: Property 'paramSet' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. Did you mean 'params'? node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64534,18): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64536,17): error TS2339: Property 'message' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65232,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65248,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65283,7): error TS2339: Property 'index' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65284,7): error TS2339: Property 'lineNumber' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65285,7): error TS2339: Property 'description' does not exist on type 'Error'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65310,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65379,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65468,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65533,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66529,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66549,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66811,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67117,1): error TS2322: Type 'string[]' is not assignable to type 'RegExpExecArray'. Property 'index' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67300,14): error TS2339: Property 'Channels' does not exist on type '{}'. @@ -6067,6 +6083,13 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(429,1 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(529,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(544,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(551,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(768,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(769,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(770,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(771,19): error TS2339: Property 'network' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(772,19): error TS2339: Property 'panels' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(773,19): error TS2339: Property 'panels' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(786,68): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(789,21): error TS2339: Property 'exposeWebInspectorNamespace' does not exist on type 'ExtensionDescriptor'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(790,12): error TS2339: Property 'webInspector' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(232,23): error TS2339: Property 'style' does not exist on type 'Element'. @@ -11596,23 +11619,30 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,482): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,502): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,564): error TS2339: Property 'code' does not exist on type 'Error'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(166,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(293,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(337,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(398,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1330,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1370,101): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1550,11): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1557,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2037,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2281,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2359,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2378,16): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2397,20): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2398,27): error TS2339: Property 'clipboardData' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2450,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2476,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2503,41): error TS2339: Property '_document' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2509,18): error TS2339: Property '_parentElement' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2524,18): error TS2339: Property 'emit' does not exist on type 'CharMeasure'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2587,35): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2589,43): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2535,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2612,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2615,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2618,52): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2619,74): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2620,37): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2651,44): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2664,50): error TS2339: Property 'maxLength' does not exist on type 'CircularList'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2674,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2690,63): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2694,68): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2697,70): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. @@ -11620,6 +11650,9 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2704,51): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2713,22): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2714,22): error TS2339: Property '_objectCount' does not exist on type 'typeof DomElementObjectPool'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2721,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2732,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2766,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2925,9): error TS2322: Type 'number' is not assignable to type 'number[]'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3087,14): error TS2339: Property 'browser' does not exist on type 'Terminal'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3151,54): error TS2339: Property 'theme' does not exist on type 'Terminal'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 435d962fa95..37c97f611a0 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -120,13 +120,11 @@ node_modules/npm/lib/config/bin-links.js(30,16): error TS2339: Property 'config' node_modules/npm/lib/config/core.js(17,1): error TS2323: Cannot redeclare exported variable 'loaded'. node_modules/npm/lib/config/core.js(18,1): error TS2323: Cannot redeclare exported variable 'rootConf'. node_modules/npm/lib/config/core.js(19,1): error TS2323: Cannot redeclare exported variable 'usingBuiltin'. -node_modules/npm/lib/config/core.js(23,21): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/lib/config/core.js(77,7): error TS2323: Cannot redeclare exported variable 'loaded'. node_modules/npm/lib/config/core.js(87,3): error TS2323: Cannot redeclare exported variable 'usingBuiltin'. node_modules/npm/lib/config/core.js(88,12): error TS2323: Cannot redeclare exported variable 'rootConf'. node_modules/npm/lib/config/core.js(95,6): error TS2339: Property 'on' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(98,6): error TS2339: Property 'on' does not exist on type 'Conf'. -node_modules/npm/lib/config/core.js(102,29): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/lib/config/core.js(105,8): error TS2339: Property 'usingBuiltin' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(128,41): error TS2551: Property 'localPrefix' does not exist on type 'Conf'. Did you mean 'loadPrefix'? node_modules/npm/lib/config/core.js(130,35): error TS2339: Property 'get' does not exist on type 'Conf'. @@ -142,7 +140,6 @@ node_modules/npm/lib/config/core.js(165,10): error TS2339: Property 'once' does node_modules/npm/lib/config/core.js(176,23): error TS2339: Property 'get' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(190,5): error TS2323: Cannot redeclare exported variable 'loaded'. node_modules/npm/lib/config/core.js(208,24): error TS2339: Property 'list' does not exist on type 'Conf'. -node_modules/npm/lib/config/core.js(213,28): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/lib/config/core.js(237,21): error TS2339: Property 'sources' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(245,17): error TS2339: Property 'emit' does not exist on type 'Conf'. node_modules/npm/lib/config/core.js(279,8): error TS2339: Property '_saving' does not exist on type 'Conf'. @@ -220,8 +217,6 @@ node_modules/npm/lib/config.js(84,19): error TS2339: Property 'config' does not node_modules/npm/lib/config.js(85,15): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(87,7): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(93,25): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. -node_modules/npm/lib/config.js(105,37): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/core")'. -node_modules/npm/lib/config.js(107,28): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/core")'. node_modules/npm/lib/config.js(135,19): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(136,7): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(137,7): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -241,7 +236,6 @@ node_modules/npm/lib/config.js(245,75): error TS2339: Property 'config' does not node_modules/npm/lib/config.js(248,47): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(248,79): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config.js(251,21): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. -node_modules/npm/lib/config.js(267,26): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/core")'. node_modules/npm/lib/config.js(273,29): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/dedupe.js(35,32): error TS2339: Property 'dir' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/dedupe.js(37,11): error TS2339: Property 'command' does not exist on type 'typeof EventEmitter'. @@ -283,7 +277,6 @@ node_modules/npm/lib/docs.js(40,38): error TS2339: Property 'config' does not ex node_modules/npm/lib/doctor/check-files-permission.js(11,14): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/doctor/check-files-permission.js(11,38): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/doctor/verify-cached-files.js(10,90): error TS2345: Argument of type '2' is not assignable to parameter of type '(string | number)[] | null | undefined'. -node_modules/npm/lib/doctor.js(6,54): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/lib/doctor.js(23,41): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/doctor.js(24,40): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/doctor.js(42,32): error TS2339: Property 'cache' does not exist on type 'typeof EventEmitter'. @@ -1140,14 +1133,10 @@ node_modules/npm/test/tap/config-basic.js(1,20): error TS2307: Cannot find modul node_modules/npm/test/tap/config-basic.js(81,12): error TS2531: Object is possibly 'null'. node_modules/npm/test/tap/config-basic.js(81,29): error TS2339: Property 'list' does not exist on type 'Conf'. node_modules/npm/test/tap/config-basic.js(82,24): error TS2531: Object is possibly 'null'. -node_modules/npm/test/tap/config-basic.js(82,60): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. -node_modules/npm/test/tap/config-basic.js(83,48): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/test/tap/config-builtin.js(1,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-builtin.js(60,12): error TS2531: Object is possibly 'null'. node_modules/npm/test/tap/config-builtin.js(60,29): error TS2339: Property 'list' does not exist on type 'Conf'. node_modules/npm/test/tap/config-builtin.js(61,13): error TS2531: Object is possibly 'null'. -node_modules/npm/test/tap/config-builtin.js(61,49): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. -node_modules/npm/test/tap/config-builtin.js(62,37): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/test/tap/config-certfile.js(5,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-credentials.js(1,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-edit.js(6,20): error TS2307: Cannot find module 'tap'. @@ -1157,15 +1146,12 @@ node_modules/npm/test/tap/config-malformed.js(1,20): error TS2307: Cannot find m node_modules/npm/test/tap/config-meta.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-meta.js(63,9): error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/npm/test/tap/config-meta.js(101,35): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/test/tap/config-new-cafile.js(5,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-private.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-project.js(1,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/config-project.js(59,12): error TS2531: Object is possibly 'null'. node_modules/npm/test/tap/config-project.js(59,29): error TS2339: Property 'list' does not exist on type 'Conf'. node_modules/npm/test/tap/config-project.js(60,13): error TS2531: Object is possibly 'null'. -node_modules/npm/test/tap/config-project.js(60,49): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. -node_modules/npm/test/tap/config-project.js(61,37): error TS2339: Property 'defaults' does not exist on type 'typeof import("/npm/node_modules/npm/lib/config/defaults")'. node_modules/npm/test/tap/config-save.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/correct-mkdir.js(1,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/correct-mkdir.js(4,29): error TS2307: Cannot find module 'require-inject'. From 8e0142d709b2d324caaebd12908295448cff4d2c Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 11:16:39 -0700 Subject: [PATCH 087/262] Support import completions for a re-export with a different name from the original (#28055) --- src/services/completions.ts | 2 +- .../completionsImport_reExport_wrongName.ts | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index e2c7be0298a..c5ef84836e4 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1410,7 +1410,7 @@ namespace ts.Completions { // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). if (typeChecker.getMergedSymbol(symbol.parent!) !== resolvedModuleSymbol - || some(symbol.declarations, d => isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier)) { + || some(symbol.declarations, d => isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier)) { continue; } diff --git a/tests/cases/fourslash/completionsImport_reExport_wrongName.ts b/tests/cases/fourslash/completionsImport_reExport_wrongName.ts index 1fe168b58a0..912f133e72a 100644 --- a/tests/cases/fourslash/completionsImport_reExport_wrongName.ts +++ b/tests/cases/fourslash/completionsImport_reExport_wrongName.ts @@ -12,9 +12,13 @@ /////**/ goTo.marker(""); -verify.completionListContains({ name: "x", source: "/a" }, "const x: 0", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: [ + { name: "x", source: "/a", sourceDisplay: "./a", text: "const x: 0", hasAction: true }, + { name: "y", source: "/index", sourceDisplay: ".", text: "(alias) const y: 0\nexport y", hasAction: true }, + ], + preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { @@ -25,3 +29,12 @@ verify.applyCodeActionFromCompletion("", { `, }); +verify.applyCodeActionFromCompletion("", { + name: "y", + source: "/index", + description: `Import 'y' from module "."`, + newFileContent: `import { x } from "./a"; +import { y } from "."; + +`, +}); From afa94c527cd407fb0eed815d070f66406485a03d Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 11:18:56 -0700 Subject: [PATCH 088/262] Un-consolidate overloads for Map and WeakMap (#28052) --- src/lib/es2015.collection.d.ts | 3 ++- src/lib/es2015.iterable.d.ts | 2 +- tests/baselines/reference/newMap.errors.txt | 8 ++++++++ tests/baselines/reference/newMap.js | 6 ++++++ tests/baselines/reference/newMap.symbols | 4 ++++ tests/baselines/reference/newMap.types | 5 +++++ tests/cases/compiler/newMap.ts | 2 ++ 7 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/newMap.errors.txt create mode 100644 tests/baselines/reference/newMap.js create mode 100644 tests/baselines/reference/newMap.symbols create mode 100644 tests/baselines/reference/newMap.types create mode 100644 tests/cases/compiler/newMap.ts diff --git a/src/lib/es2015.collection.d.ts b/src/lib/es2015.collection.d.ts index 46bb7af0c8f..34afa3d1b2b 100644 --- a/src/lib/es2015.collection.d.ts +++ b/src/lib/es2015.collection.d.ts @@ -9,7 +9,8 @@ interface Map { } interface MapConstructor { - new (entries?: ReadonlyArray<[K, V]> | null): Map; + new(): Map; + new(entries?: ReadonlyArray<[K, V]> | null): Map; readonly prototype: Map; } declare var Map: MapConstructor; diff --git a/src/lib/es2015.iterable.d.ts b/src/lib/es2015.iterable.d.ts index 568d3596dda..f0a38dff3fe 100644 --- a/src/lib/es2015.iterable.d.ts +++ b/src/lib/es2015.iterable.d.ts @@ -135,7 +135,7 @@ interface MapConstructor { interface WeakMap { } interface WeakMapConstructor { - new (iterable: Iterable<[K, V]>): WeakMap; + new (iterable: Iterable<[K, V]>): WeakMap; } interface Set { diff --git a/tests/baselines/reference/newMap.errors.txt b/tests/baselines/reference/newMap.errors.txt new file mode 100644 index 00000000000..46668890b07 --- /dev/null +++ b/tests/baselines/reference/newMap.errors.txt @@ -0,0 +1,8 @@ +tests/cases/compiler/newMap.ts(1,9): error TS2558: Expected 0-2 type arguments, but got 1. + + +==== tests/cases/compiler/newMap.ts (1 errors) ==== + new Map(); + ~~~~~~ +!!! error TS2558: Expected 0-2 type arguments, but got 1. + \ No newline at end of file diff --git a/tests/baselines/reference/newMap.js b/tests/baselines/reference/newMap.js new file mode 100644 index 00000000000..9ab99fc7242 --- /dev/null +++ b/tests/baselines/reference/newMap.js @@ -0,0 +1,6 @@ +//// [newMap.ts] +new Map(); + + +//// [newMap.js] +new Map(); diff --git a/tests/baselines/reference/newMap.symbols b/tests/baselines/reference/newMap.symbols new file mode 100644 index 00000000000..1ce51df4969 --- /dev/null +++ b/tests/baselines/reference/newMap.symbols @@ -0,0 +1,4 @@ +=== tests/cases/compiler/newMap.ts === +new Map(); +>Map : Symbol(Map, Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + diff --git a/tests/baselines/reference/newMap.types b/tests/baselines/reference/newMap.types new file mode 100644 index 00000000000..d3fab45ccc0 --- /dev/null +++ b/tests/baselines/reference/newMap.types @@ -0,0 +1,5 @@ +=== tests/cases/compiler/newMap.ts === +new Map(); +>new Map() : any +>Map : MapConstructor + diff --git a/tests/cases/compiler/newMap.ts b/tests/cases/compiler/newMap.ts new file mode 100644 index 00000000000..ab7040e11d9 --- /dev/null +++ b/tests/cases/compiler/newMap.ts @@ -0,0 +1,2 @@ +// @lib: es6 +new Map(); From 02c74987b70a70bf2d135735dcb6c1a4e4de3e53 Mon Sep 17 00:00:00 2001 From: Sam Drugan Date: Mon, 22 Oct 2018 19:32:49 +0100 Subject: [PATCH 089/262] added await keyword to completions and added test (#27912) --- src/services/completions.ts | 2 +- tests/cases/fourslash/completionAwaitKeyword.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/completionAwaitKeyword.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index c5ef84836e4..0e0bf50cf83 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -2150,7 +2150,7 @@ namespace ts.Completions { case KeywordCompletionFilters.None: return false; case KeywordCompletionFilters.All: - return kind === SyntaxKind.AsyncKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword + return kind === SyntaxKind.AsyncKeyword || SyntaxKind.AwaitKeyword || !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword || isTypeKeyword(kind) && kind !== SyntaxKind.UndefinedKeyword; case KeywordCompletionFilters.ClassElementKeywords: return isClassMemberCompletionKeyword(kind); diff --git a/tests/cases/fourslash/completionAwaitKeyword.ts b/tests/cases/fourslash/completionAwaitKeyword.ts new file mode 100644 index 00000000000..3cb565cf88b --- /dev/null +++ b/tests/cases/fourslash/completionAwaitKeyword.ts @@ -0,0 +1,4 @@ +//// /**/ + +goTo.marker("") +verify.completionListContains("await"); \ No newline at end of file From d3d4f83f89d6d407f4a5f061964b70be3dc8eeed Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 11:44:06 -0700 Subject: [PATCH 090/262] Remove hack to get target of GetAccessor symbol (#27868) * Remove hack to get target of GetAccessor symbol * Add tests and get moveToNewFile to work with binding patterns --- src/harness/fourslash.ts | 8 +++-- src/services/refactors/moveToNewFile.ts | 27 ++++++++++++--- src/services/utilities.ts | 10 ++---- .../findAllRefsDestructureGetter2.ts | 26 +++++++++++++++ tests/cases/fourslash/fourslash.ts | 2 +- .../moveToNewFile_bindingPatterns.ts | 23 +++++++++++++ tests/cases/fourslash/moveToNewFile_getter.ts | 33 +++++++++++++++++++ 7 files changed, 113 insertions(+), 16 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsDestructureGetter2.ts create mode 100644 tests/cases/fourslash/moveToNewFile_bindingPatterns.ts create mode 100644 tests/cases/fourslash/moveToNewFile_getter.ts diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index dc28871d1c0..a75a78e2a63 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1328,8 +1328,10 @@ Actual: ${stringify(fullActual)}`); }))); } - public verifyQuickInfoAt(markerName: string, expectedText: string, expectedDocumentation?: string) { - this.goToMarker(markerName); + public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string) { + if (typeof markerName === "string") this.goToMarker(markerName); + else this.goToRangeStart(markerName); + this.verifyQuickInfoString(expectedText, expectedDocumentation); } @@ -4221,7 +4223,7 @@ namespace FourSlashInterface { this.state.verifyQuickInfoString(expectedText, expectedDocumentation); } - public quickInfoAt(markerName: string, expectedText: string, expectedDocumentation?: string) { + public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string) { this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation); } diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 693cdd9c6cb..757b1ab71cf 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -612,7 +612,7 @@ namespace ts.refactor { | ImportEqualsDeclaration; type TopLevelDeclarationStatement = NonVariableTopLevelDeclaration | VariableStatement; interface TopLevelVariableDeclaration extends VariableDeclaration { parent: VariableDeclarationList & { parent: VariableStatement; }; } - type TopLevelDeclaration = NonVariableTopLevelDeclaration | TopLevelVariableDeclaration; + type TopLevelDeclaration = NonVariableTopLevelDeclaration | TopLevelVariableDeclaration | BindingElement; function isTopLevelDeclaration(node: Node): node is TopLevelDeclaration { return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); } @@ -653,7 +653,7 @@ namespace ts.refactor { return cb(statement as FunctionDeclaration | ClassDeclaration | EnumDeclaration | ModuleDeclaration | TypeAliasDeclaration | InterfaceDeclaration | ImportEqualsDeclaration); case SyntaxKind.VariableStatement: - return forEach((statement as VariableStatement).declarationList.declarations as ReadonlyArray, cb); + return firstDefined((statement as VariableStatement).declarationList.declarations, decl => forEachTopLevelDeclarationInBindingName(decl.name, cb)); case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; @@ -663,13 +663,32 @@ namespace ts.refactor { } } } + function forEachTopLevelDeclarationInBindingName(name: BindingName, cb: (node: TopLevelDeclaration) => T): T | undefined { + switch (name.kind) { + case SyntaxKind.Identifier: + return cb(cast(name.parent, (x): x is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(x) || isBindingElement(x))); + case SyntaxKind.ArrayBindingPattern: + case SyntaxKind.ObjectBindingPattern: + return firstDefined(name.elements, em => isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name); + } + } function nameOfTopLevelDeclaration(d: TopLevelDeclaration): Identifier | undefined { - return d.kind === SyntaxKind.ExpressionStatement ? d.expression.left.name : tryCast(d.name, isIdentifier); + return isExpressionStatement(d) ? d.expression.left.name : tryCast(d.name, isIdentifier); } function getTopLevelDeclarationStatement(d: TopLevelDeclaration): TopLevelDeclarationStatement { - return isVariableDeclaration(d) ? d.parent.parent : d; + switch (d.kind) { + case SyntaxKind.VariableDeclaration: + return d.parent.parent; + case SyntaxKind.BindingElement: + return getTopLevelDeclarationStatement( + cast(d.parent.parent, (p): p is TopLevelVariableDeclaration | BindingElement => isVariableDeclaration(p) || isBindingElement(p))); + default: + return d; + } } function addExportToChanges(sourceFile: SourceFile, decl: TopLevelDeclarationStatement, changes: textChanges.ChangeTracker, useEs6Exports: boolean): void { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index e53f568c0f4..f0326599ad0 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1337,15 +1337,9 @@ namespace ts { !bindingElement.propertyName; } - export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: ObjectBindingElementWithoutPropertyName) { + export function getPropertySymbolFromBindingElement(checker: TypeChecker, bindingElement: ObjectBindingElementWithoutPropertyName): Symbol | undefined { const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - const propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & SymbolFlags.Accessor) { - // See GH#16922 - Debug.assert(!!(propSymbol.flags & SymbolFlags.Transient)); - return (propSymbol as TransientSymbol).target; - } - return propSymbol; + return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } /** diff --git a/tests/cases/fourslash/findAllRefsDestructureGetter2.ts b/tests/cases/fourslash/findAllRefsDestructureGetter2.ts new file mode 100644 index 00000000000..d26983a1091 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsDestructureGetter2.ts @@ -0,0 +1,26 @@ +/// + +// @noLib: true + +// @Filename: /a.ts +////class C { +//// get [|{| "isWriteAccess": true, "isDefinition": true |}g|](): number { return 0; } +//// +//// set [|{| "isWriteAccess": true, "isDefinition": true |}s|](value: number) {} +////} +////const { [|{| "isWriteAccess": true, "isDefinition": true |}g|], [|{| "isWriteAccess": true, "isDefinition": true |}s|] } = new C(); + +const [g0, s0, g1, s1] = test.ranges(); +verify.quickInfoAt(g0, "(property) C.g: number"); +verify.referenceGroups(g0, [{ definition: "(property) C.g: number", ranges: [g0, g1] }]); +verify.referenceGroups(g1, [ + { definition: "(property) C.g: number", ranges: [g0] }, + { definition: "const g: number", ranges: [g1] }, +]); + +verify.quickInfoAt(s0, "(property) C.s: number"); +verify.referenceGroups(s0, [{ definition: "(property) C.s: number", ranges: [s0, s1] }]); +verify.referenceGroups(s1, [ + { definition: "(property) C.s: number", ranges: [s0] }, + { definition: "const s: number", ranges: [s1] } +]); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 4603d61a286..e58e12a9ecf 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -322,7 +322,7 @@ declare namespace FourSlashInterface { /** Verify the quick info available at the current marker. */ quickInfoIs(expectedText: string, expectedDocumentation?: string): void; /** Goto a marker and call `quickInfoIs`. */ - quickInfoAt(markerName: string, expectedText?: string, expectedDocumentation?: string): void; + quickInfoAt(markerName: string | Range, expectedText?: string, expectedDocumentation?: string): void; /** * Call `quickInfoAt` for each pair in the object. * (If the value is an array, it is [expectedText, expectedDocumentation].) diff --git a/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts b/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts new file mode 100644 index 00000000000..f004fdbdde9 --- /dev/null +++ b/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts @@ -0,0 +1,23 @@ +/// + +// @Filename: /a.ts +////[|export const [x, { p: y }] = [0, { p: 1 }];|] + +// @Filename: /b.ts +////import { x, y } from "./a"; + +verify.noErrors(); + +verify.moveToNewFile({ + newFileContents: { + "/a.ts": "", + + "/x.ts": +`export const [x, { p: y }] = [0, { p: 1 }];`, + + "/b.ts": +` +import { x, y } from "./x"; +`, + }, +}); diff --git a/tests/cases/fourslash/moveToNewFile_getter.ts b/tests/cases/fourslash/moveToNewFile_getter.ts new file mode 100644 index 00000000000..d595d92cf07 --- /dev/null +++ b/tests/cases/fourslash/moveToNewFile_getter.ts @@ -0,0 +1,33 @@ +/// + +// @Filename: /a.ts +////class C { +//// get g() { return 0; } +//// get h() { return 1; } +////} +////[|export const { g, h: i } = new C();|] + +// @Filename: /b.ts +////import { g, i } from "./a"; + +verify.noErrors(); + +verify.moveToNewFile({ + newFileContents: { + "/a.ts": +`export class C { + get g() { return 0; } + get h() { return 1; } +} +`, + + "/g.ts": +`import { C } from "./a"; +export const { g, h: i } = new C();`, + + "/b.ts": +` +import { g, i } from "./g"; +`, + }, +}); From 1930f8a790aa2afeb49ee6287edfed5b381c26eb Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 11:44:39 -0700 Subject: [PATCH 091/262] fourslash: Add 'goToMarkerOrRange' helper (#28057) --- src/harness/fourslash.ts | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a75a78e2a63..a9d2bc8a006 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1181,12 +1181,7 @@ namespace FourSlash { })); for (const start of toArray(starts)) { - if (typeof start === "string") { - this.goToMarker(start); - } - else { - this.goToRangeStart(start); - } + this.goToMarkerOrRange(start); const fullActual = ts.map(this.findReferencesAtCaret(), ({ definition, references }, i) => { const text = definition.displayParts.map(d => d.text).join(""); return { @@ -1203,15 +1198,7 @@ namespace FourSlash { } public verifyNoReferences(markerNameOrRange?: string | Range) { - if (markerNameOrRange) { - if (ts.isString(markerNameOrRange)) { - this.goToMarker(markerNameOrRange); - } - else { - this.goToRangeStart(markerNameOrRange); - } - } - + if (markerNameOrRange) this.goToMarkerOrRange(markerNameOrRange); const refs = this.getReferencesAtCaret(); if (refs && refs.length) { this.raiseError(`Expected getReferences to fail, but saw references: ${stringify(refs)}`); @@ -2053,6 +2040,14 @@ Actual: ${stringify(fullActual)}`); this.goToPosition(len); } + private goToMarkerOrRange(markerOrRange: string | Range) { + if (typeof markerOrRange === "string") { + this.goToMarker(markerOrRange); + } else { + this.goToRangeStart(markerOrRange); + } + } + public goToRangeStart({ fileName, pos }: Range) { this.openFile(fileName); this.goToPosition(pos); From 96480b5ba9bb56d8412021176e439b9b02c9d2c7 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Mon, 22 Oct 2018 20:59:42 +0200 Subject: [PATCH 092/262] fix return type of LangageServiceHost.resolve* Fixes: #28058 --- src/services/types.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/services/types.ts b/src/services/types.ts index 80dac58095c..72ded445dba 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -212,9 +212,9 @@ namespace ts { * * If this is implemented, `getResolvedModuleWithFailedLookupLocationsFromCache` should be too. */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; From 3b058a4de4e1da12532ee9c589f04623309f8597 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Mon, 22 Oct 2018 21:12:12 +0200 Subject: [PATCH 093/262] fix compile errors, accept baselines --- src/compiler/program.ts | 6 +++--- src/compiler/types.ts | 8 ++++---- src/compiler/utilities.ts | 4 ++-- tests/baselines/reference/api/tsserverlibrary.d.ts | 6 +++--- tests/baselines/reference/api/typescript.d.ts | 6 +++--- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 3c3c1ff5db2..fa86ef147cb 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -599,7 +599,7 @@ namespace ts { const cachedSemanticDiagnosticsForFile: DiagnosticCache = {}; const cachedDeclarationDiagnosticsForFile: DiagnosticCache = {}; - let resolvedTypeReferenceDirectives = createMap(); + let resolvedTypeReferenceDirectives = createMap(); let fileProcessingDiagnostics = createDiagnosticCollection(); // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. @@ -656,7 +656,7 @@ namespace ts { resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader); } - let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => ResolvedTypeReferenceDirective[]; + let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => (ResolvedTypeReferenceDirective | undefined)[]; if (host.resolveTypeReferenceDirectives) { resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference); } @@ -2335,7 +2335,7 @@ namespace ts { } } - function processTypeReferenceDirective(typeReferenceDirective: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective, + function processTypeReferenceDirective(typeReferenceDirective: string, resolvedTypeReferenceDirective?: ResolvedTypeReferenceDirective, refFile?: SourceFile, refPos?: number, refEnd?: number): void { // If we already found this library as a primary reference - nothing to do diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 1c2009bc19f..e025ba8a4ca 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2714,7 +2714,7 @@ namespace ts { // It is used to resolve module names in the checker. // Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead /* @internal */ resolvedModules?: Map; - /* @internal */ resolvedTypeReferenceDirectiveNames: Map; + /* @internal */ resolvedTypeReferenceDirectiveNames: Map; /* @internal */ imports: ReadonlyArray; /** * When a file's references are redirected due to project reference directives, @@ -2889,7 +2889,7 @@ namespace ts { /* @internal */ getTypeCount(): number; /* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection; - /* @internal */ getResolvedTypeReferenceDirectives(): Map; + /* @internal */ getResolvedTypeReferenceDirectives(): Map; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; @@ -2997,7 +2997,7 @@ namespace ts { getSourceFiles(): ReadonlyArray; getSourceFile(fileName: string): SourceFile | undefined; - getResolvedTypeReferenceDirectives(): ReadonlyMap; + getResolvedTypeReferenceDirectives(): ReadonlyMap; readonly redirectTargetsMap: RedirectTargetsMap; } @@ -4979,7 +4979,7 @@ namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; /* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 6310d299b42..bd1d874e9dc 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -227,9 +227,9 @@ namespace ts { sourceFile.resolvedModules.set(moduleNameText, resolvedModule); } - export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void { + export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective?: ResolvedTypeReferenceDirective): void { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = createMap(); + sourceFile.resolvedTypeReferenceDirectiveNames = createMap(); } sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 1680826b31f..bd9067a20c2 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2694,7 +2694,7 @@ declare namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } @@ -4656,9 +4656,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index a7c3f9cd902..0d24af21eeb 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2694,7 +2694,7 @@ declare namespace ts { /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; } @@ -4656,9 +4656,9 @@ declare namespace ts { realpath?(path: string): string; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; getDirectories?(directoryName: string): string[]; /** * Gets a set of custom transformers to use during emit. From 5b3fe6e68b94c4fdb3201e131d0d8da6cb4d87cd Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Mon, 22 Oct 2018 21:23:04 +0200 Subject: [PATCH 094/262] update other interfaces and implementations and accept baseline --- src/compiler/resolutionCache.ts | 10 +++++----- src/compiler/watch.ts | 4 ++-- src/server/project.ts | 4 ++-- src/services/shims.ts | 12 ++++++------ tests/baselines/reference/api/tsserverlibrary.d.ts | 8 ++++---- tests/baselines/reference/api/typescript.d.ts | 4 ++-- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 9a2e62706b3..b11de69b0e2 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -5,9 +5,9 @@ namespace ts { startRecordingFilesWithChangedResolutions(): void; finishRecordingFilesWithChangedResolutions(): Path[] | undefined; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; invalidateResolutionOfFile(filePath: Path): void; removeResolutionsOfFile(filePath: Path): void; @@ -250,7 +250,7 @@ namespace ts { loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, reusedNames: string[] | undefined, - logChanges: boolean): R[] { + logChanges: boolean): (R | undefined)[] { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = cache.get(path) || cache.set(path, createMap()).get(path)!; @@ -335,7 +335,7 @@ namespace ts { } } - function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[] { + function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[] { return resolveNamesWithLocalCache( typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, @@ -344,7 +344,7 @@ namespace ts { ); } - function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[] { + function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[] { return resolveNamesWithLocalCache( moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 261013e29b3..7c9c0a28a34 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -338,9 +338,9 @@ namespace ts { getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** Internal interface used to wire emit through same host */ diff --git a/src/server/project.ts b/src/server/project.ts index fe977124e9b..b87ddc9fb7f 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -368,7 +368,7 @@ namespace ts.server { return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); } - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[] { + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[] { return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); } @@ -376,7 +376,7 @@ namespace ts.server { return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile); } - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[] { + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[] { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); } diff --git a/src/services/shims.ts b/src/services/shims.ts index 8bff0db731f..3ee11817c49 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -331,19 +331,19 @@ namespace ts { private loggingEnabled = false; private tracingEnabled = false; - public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[]; - public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; + public resolveModuleNames: (moduleName: string[], containingFile: string) => (ResolvedModuleFull | undefined)[]; + public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => (ResolvedTypeReferenceDirective | undefined)[]; public directoryExists: (directoryName: string) => boolean; constructor(private shimHost: LanguageServiceShimHost) { // if shimHost is a COM object then property check will become method call with no arguments. // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { - this.resolveModuleNames = (moduleNames: string[], containingFile: string): ResolvedModuleFull[] => { + this.resolveModuleNames = (moduleNames, containingFile) => { const resolutionsInFile = >JSON.parse(this.shimHost.getModuleResolutionsForFile!(containingFile)); // TODO: GH#18217 return map(moduleNames, name => { const result = getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined!; // TODO: GH#18217 + return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } @@ -351,9 +351,9 @@ namespace ts { this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName); } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { - this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => { + this.resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile) => { const typeDirectivesForFile = >JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile!(containingFile)); // TODO: GH#18217 - return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name)!); // TODO: GH#18217 + return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name)); }; } } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index bd9067a20c2..5921a644444 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4386,9 +4386,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -8151,9 +8151,9 @@ declare namespace ts.server { readFile(fileName: string): string | undefined; writeFile(fileName: string, content: string): void; fileExists(file: string): boolean; - resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModuleFull[]; + resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[]; getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; directoryExists(path: string): boolean; getDirectories(path: string): string[]; log(s: string): void; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 0d24af21eeb..573d470fde5 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4386,9 +4386,9 @@ declare namespace ts { /** If provided is used to get the environment variable */ getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): ResolvedModule[]; + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference): (ResolvedModule | undefined)[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirective[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options From 34256145b8d287be92ea5757c72173dc2e7e8219 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 14:37:27 -0700 Subject: [PATCH 095/262] Fix lint --- src/harness/fourslash.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a9d2bc8a006..844f7b26598 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2043,7 +2043,8 @@ Actual: ${stringify(fullActual)}`); private goToMarkerOrRange(markerOrRange: string | Range) { if (typeof markerOrRange === "string") { this.goToMarker(markerOrRange); - } else { + } + else { this.goToRangeStart(markerOrRange); } } From f701daf4e01468f990081ad6dea0649ccf161c09 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 16:33:43 -0700 Subject: [PATCH 096/262] Infer over each mapped type constraint member if it is a union (#28006) --- src/compiler/checker.ts | 88 +++++++++++-------- src/compiler/types.ts | 2 + .../checkJsxIntersectionElementPropsType.js | 38 ++++++++ ...eckJsxIntersectionElementPropsType.symbols | 41 +++++++++ ...checkJsxIntersectionElementPropsType.types | 35 ++++++++ .../checkJsxIntersectionElementPropsType.tsx | 14 +++ 6 files changed, 182 insertions(+), 36 deletions(-) create mode 100644 tests/baselines/reference/checkJsxIntersectionElementPropsType.js create mode 100644 tests/baselines/reference/checkJsxIntersectionElementPropsType.symbols create mode 100644 tests/baselines/reference/checkJsxIntersectionElementPropsType.types create mode 100644 tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9fab5821e4e..3ad881b9aff 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6786,7 +6786,7 @@ namespace ts { const modifiers = getMappedTypeModifiers(type.mappedType); const readonlyMask = modifiers & MappedTypeModifiers.IncludeReadonly ? false : true; const optionalMask = modifiers & MappedTypeModifiers.IncludeOptional ? 0 : SymbolFlags.Optional; - const stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType), readonlyMask && indexInfo.isReadonly); + const stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly); const members = createSymbolTable(); for (const prop of getPropertiesOfType(type.source)) { const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0); @@ -6795,6 +6795,7 @@ namespace ts { inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; + inferredProp.constraintType = type.constraintType; members.set(prop.escapedName, inferredProp); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); @@ -13493,18 +13494,18 @@ namespace ts { * property is computed by inferring from the source property type to X for the type * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ - function inferTypeForHomomorphicMappedType(source: Type, target: MappedType): Type | undefined { - const key = source.id + "," + target.id; + function inferTypeForHomomorphicMappedType(source: Type, target: MappedType, constraint: IndexType): Type | undefined { + const key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } reverseMappedCache.set(key, undefined); - const type = createReverseMappedType(source, target); + const type = createReverseMappedType(source, target, constraint); reverseMappedCache.set(key, type); return type; } - function createReverseMappedType(source: Type, target: MappedType) { + function createReverseMappedType(source: Type, target: MappedType, constraint: IndexType) { const properties = getPropertiesOfType(source); if (properties.length === 0 && !getIndexInfoOfType(source, IndexKind.String)) { return undefined; @@ -13519,13 +13520,13 @@ namespace ts { // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType((source).typeArguments![0], target)); + return createArrayType(inferReverseMappedType((source).typeArguments![0], target, constraint)); } if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType((source).typeArguments![0], target)); + return createReadonlyArrayType(inferReverseMappedType((source).typeArguments![0], target, constraint)); } if (isTupleType(source)) { - const elementTypes = map(source.typeArguments || emptyArray, t => inferReverseMappedType(t, target)); + const elementTypes = map(source.typeArguments || emptyArray, t => inferReverseMappedType(t, target, constraint)); const minLength = getMappedTypeModifiers(target) & MappedTypeModifiers.IncludeOptional ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); @@ -13535,15 +13536,16 @@ namespace ts { const reversed = createObjectType(ObjectFlags.ReverseMapped | ObjectFlags.Anonymous, /*symbol*/ undefined) as ReverseMappedType; reversed.source = source; reversed.mappedType = target; + reversed.constraintType = constraint; return reversed; } function getTypeOfReverseMappedSymbol(symbol: ReverseMappedSymbol) { - return inferReverseMappedType(symbol.propertyType, symbol.mappedType); + return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType); } - function inferReverseMappedType(sourceType: Type, target: MappedType): Type { - const typeParameter = getIndexedAccessType((getConstraintTypeFromMappedType(target)).type, getTypeParameterFromMappedType(target)); + function inferReverseMappedType(sourceType: Type, target: MappedType, constraint: IndexType): Type { + const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target)); const templateType = getTemplateTypeFromMappedType(target); const inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); @@ -13841,6 +13843,44 @@ namespace ts { return undefined; } + function inferFromMappedTypeConstraint(source: Type, target: Type, constraintType: Type): boolean { + if (constraintType.flags & TypeFlags.Union) { + let result = false; + for (const type of (constraintType as UnionType).types) { + result = inferFromMappedTypeConstraint(source, target, type) || result; + } + return result; + } + if (constraintType.flags & TypeFlags.Index) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + const inference = getInferenceInfoForType((constraintType).type); + if (inference && !inference.isFixed) { + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType as IndexType); + if (inferredType) { + const savePriority = priority; + priority |= InferencePriority.HomomorphicMappedType; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return true; + } + if (constraintType.flags & TypeFlags.TypeParameter) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + const savePriority = priority; + priority |= InferencePriority.MappedTypeConstraint; + inferFromTypes(getIndexType(source), constraintType); + priority = savePriority; + inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return true; + } + return false; + } + function inferFromObjectTypes(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 @@ -13850,31 +13890,7 @@ namespace ts { } if (getObjectFlags(target) & ObjectFlags.Mapped) { const constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & TypeFlags.Index) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - const inference = getInferenceInfoForType((constraintType).type); - if (inference && !inference.isFixed) { - const inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - const savePriority = priority; - priority |= InferencePriority.HomomorphicMappedType; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - return; - } - if (constraintType.flags & TypeFlags.TypeParameter) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - const savePriority = priority; - priority |= InferencePriority.MappedTypeConstraint; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; - inferFromTypes(getUnionType(map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + if (inferFromMappedTypeConstraint(source, target, constraintType)) { return; } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 1c2009bc19f..21e09d799e9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3682,6 +3682,7 @@ namespace ts { export interface ReverseMappedSymbol extends TransientSymbol { propertyType: Type; mappedType: MappedType; + constraintType: IndexType; } export const enum InternalSymbolName { @@ -4090,6 +4091,7 @@ namespace ts { export interface ReverseMappedType extends ObjectType { source: Type; mappedType: MappedType; + constraintType: IndexType; } /* @internal */ diff --git a/tests/baselines/reference/checkJsxIntersectionElementPropsType.js b/tests/baselines/reference/checkJsxIntersectionElementPropsType.js new file mode 100644 index 00000000000..cbdf2835c0b --- /dev/null +++ b/tests/baselines/reference/checkJsxIntersectionElementPropsType.js @@ -0,0 +1,38 @@ +//// [checkJsxIntersectionElementPropsType.tsx] +declare namespace JSX { + interface ElementAttributesProperty { props: {}; } +} + +declare class Component

{ + constructor(props: Readonly

); + readonly props: Readonly

; +} + +class C extends Component<{ x?: boolean; } & T> {} +const y = new C({foobar: "example"}); +const x = + +//// [checkJsxIntersectionElementPropsType.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var C = /** @class */ (function (_super) { + __extends(C, _super); + function C() { + return _super !== null && _super.apply(this, arguments) || this; + } + return C; +}(Component)); +var y = new C({ foobar: "example" }); +var x = ; diff --git a/tests/baselines/reference/checkJsxIntersectionElementPropsType.symbols b/tests/baselines/reference/checkJsxIntersectionElementPropsType.symbols new file mode 100644 index 00000000000..aa0cf85044e --- /dev/null +++ b/tests/baselines/reference/checkJsxIntersectionElementPropsType.symbols @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx === +declare namespace JSX { +>JSX : Symbol(JSX, Decl(checkJsxIntersectionElementPropsType.tsx, 0, 0)) + + interface ElementAttributesProperty { props: {}; } +>ElementAttributesProperty : Symbol(ElementAttributesProperty, Decl(checkJsxIntersectionElementPropsType.tsx, 0, 23)) +>props : Symbol(ElementAttributesProperty.props, Decl(checkJsxIntersectionElementPropsType.tsx, 1, 41)) +} + +declare class Component

{ +>Component : Symbol(Component, Decl(checkJsxIntersectionElementPropsType.tsx, 2, 1)) +>P : Symbol(P, Decl(checkJsxIntersectionElementPropsType.tsx, 4, 24)) + + constructor(props: Readonly

); +>props : Symbol(props, Decl(checkJsxIntersectionElementPropsType.tsx, 5, 14)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(checkJsxIntersectionElementPropsType.tsx, 4, 24)) + + readonly props: Readonly

; +>props : Symbol(Component.props, Decl(checkJsxIntersectionElementPropsType.tsx, 5, 34)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(checkJsxIntersectionElementPropsType.tsx, 4, 24)) +} + +class C extends Component<{ x?: boolean; } & T> {} +>C : Symbol(C, Decl(checkJsxIntersectionElementPropsType.tsx, 7, 1)) +>T : Symbol(T, Decl(checkJsxIntersectionElementPropsType.tsx, 9, 8)) +>Component : Symbol(Component, Decl(checkJsxIntersectionElementPropsType.tsx, 2, 1)) +>x : Symbol(x, Decl(checkJsxIntersectionElementPropsType.tsx, 9, 30)) +>T : Symbol(T, Decl(checkJsxIntersectionElementPropsType.tsx, 9, 8)) + +const y = new C({foobar: "example"}); +>y : Symbol(y, Decl(checkJsxIntersectionElementPropsType.tsx, 10, 5)) +>C : Symbol(C, Decl(checkJsxIntersectionElementPropsType.tsx, 7, 1)) +>foobar : Symbol(foobar, Decl(checkJsxIntersectionElementPropsType.tsx, 10, 17)) + +const x = +>x : Symbol(x, Decl(checkJsxIntersectionElementPropsType.tsx, 11, 5)) +>C : Symbol(C, Decl(checkJsxIntersectionElementPropsType.tsx, 7, 1)) +>foobar : Symbol(foobar, Decl(checkJsxIntersectionElementPropsType.tsx, 11, 12)) + diff --git a/tests/baselines/reference/checkJsxIntersectionElementPropsType.types b/tests/baselines/reference/checkJsxIntersectionElementPropsType.types new file mode 100644 index 00000000000..0e95dbed361 --- /dev/null +++ b/tests/baselines/reference/checkJsxIntersectionElementPropsType.types @@ -0,0 +1,35 @@ +=== tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx === +declare namespace JSX { + interface ElementAttributesProperty { props: {}; } +>props : {} +} + +declare class Component

{ +>Component : Component

+ + constructor(props: Readonly

); +>props : Readonly

+ + readonly props: Readonly

; +>props : Readonly

+} + +class C extends Component<{ x?: boolean; } & T> {} +>C : C +>Component : Component<{ x?: boolean | undefined; } & T> +>x : boolean | undefined + +const y = new C({foobar: "example"}); +>y : C<{ foobar: {}; }> +>new C({foobar: "example"}) : C<{ foobar: {}; }> +>C : typeof C +>{foobar: "example"} : { foobar: string; } +>foobar : string +>"example" : "example" + +const x = +>x : error +> : error +>C : typeof C +>foobar : string + diff --git a/tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx b/tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx new file mode 100644 index 00000000000..3a7260a97c8 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxIntersectionElementPropsType.tsx @@ -0,0 +1,14 @@ +// @jsx: preserve +// @strict: true +declare namespace JSX { + interface ElementAttributesProperty { props: {}; } +} + +declare class Component

{ + constructor(props: Readonly

); + readonly props: Readonly

; +} + +class C extends Component<{ x?: boolean; } & T> {} +const y = new C({foobar: "example"}); +const x = \ No newline at end of file From 0c36266706596873111fe480ca5f3bf50b96ebe1 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 16:36:11 -0700 Subject: [PATCH 097/262] Obey the excludeArgument parameter when checking JSX signature validity (#28002) * Obey the excludeArgument parameter when checking JSX signature validity * Fix conditional type extending any contextual types and accept baselines * use flag check to also drop unknown from comparison for the same reason * Slight refinement - make an intersection to ensure parameter constraints flow through contextual types when instantiated * Format ternary more nicely --- src/compiler/checker.ts | 12 ++- ...xGenericTagHasCorrectInferences.errors.txt | 12 ++- .../checkJsxSubtleSkipContextSensitiveBug.js | 95 +++++++++++++++++++ ...ckJsxSubtleSkipContextSensitiveBug.symbols | 64 +++++++++++++ ...heckJsxSubtleSkipContextSensitiveBug.types | 57 +++++++++++ ...StringLiteralsInJsxAttributes02.errors.txt | 4 +- ...TypedStringLiteralsInJsxAttributes02.types | 8 +- ...actDefaultPropsInferenceSuccess.errors.txt | 4 +- ...elessFunctionComponentOverload5.errors.txt | 4 +- ...xStatelessFunctionComponentOverload5.types | 6 +- .../checkJsxSubtleSkipContextSensitiveBug.tsx | 27 ++++++ 11 files changed, 272 insertions(+), 21 deletions(-) create mode 100644 tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js create mode 100644 tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.symbols create mode 100644 tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.types create mode 100644 tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3ad881b9aff..082c31416a2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7083,7 +7083,11 @@ namespace ts { function getDefaultConstraintOfConditionalType(type: ConditionalType) { if (!type.resolvedDefaultConstraint) { const rootTrueType = type.root.trueType; - const rootTrueConstraint = rootTrueType.flags & TypeFlags.Substitution ? (rootTrueType).substitute : rootTrueType; + const rootTrueConstraint = !(rootTrueType.flags & TypeFlags.Substitution) + ? rootTrueType + : ((rootTrueType).substitute).flags & TypeFlags.AnyOrUnknown + ? (rootTrueType).typeVariable + : getIntersectionType([(rootTrueType).substitute, (rootTrueType).typeVariable]); type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); } return type.resolvedDefaultConstraint; @@ -19163,12 +19167,12 @@ namespace ts { * @param relation a relationship to check parameter and argument type * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map, reportErrors: boolean) { + function checkApplicableSignatureForJsxOpeningLikeElement(node: JsxOpeningLikeElement, signature: Signature, relation: Map, excludeArgument: boolean[] | undefined, reportErrors: boolean) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); + const attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } @@ -19180,7 +19184,7 @@ namespace ts { excludeArgument: boolean[] | undefined, reportErrors: boolean) { if (isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, reportErrors); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); } const thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { diff --git a/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt b/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt index 10a8c641cd8..36ebc70b76c 100644 --- a/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt +++ b/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt @@ -1,4 +1,6 @@ -tests/cases/conformance/jsx/file.tsx(13,71): error TS2322: Type 'string' is not assignable to type '{ x: string; }'. +tests/cases/conformance/jsx/file.tsx(13,54): error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '((a: { x: string; }) => string) & ((cur: { x: string; }) => { x: string; })'. + Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. + Type 'string' is not assignable to type '{ x: string; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -15,6 +17,8 @@ tests/cases/conformance/jsx/file.tsx(13,71): error TS2322: Type 'string' is not let b = a} />; // No error - Values should be reinstantiated with `number` (since `object` is a default, not a constraint) let c = ({ x: a.x })} />; // No Error let d = a.x} />; // Error - `string` is not assignable to `{x: string}` - ~~~ -!!! error TS2322: Type 'string' is not assignable to type '{ x: string; }'. -!!! related TS6502 tests/cases/conformance/jsx/file.tsx:4:15: The expected type comes from the return type of this signature. \ No newline at end of file + ~~~~~~~~~~ +!!! error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '((a: { x: string; }) => string) & ((cur: { x: string; }) => { x: string; })'. +!!! error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. +!!! error TS2322: Type 'string' is not assignable to type '{ x: string; }'. +!!! related TS6500 tests/cases/conformance/jsx/file.tsx:13:54: The expected type comes from property 'nextValues' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes string; }, { x: string; }>> & { initialValues: { x: string; }; nextValues: (a: { x: string; }) => string; } & BaseProps<{ x: string; }> & { children?: ReactNode; }' \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js new file mode 100644 index 00000000000..704781dbe58 --- /dev/null +++ b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.js @@ -0,0 +1,95 @@ +//// [checkJsxSubtleSkipContextSensitiveBug.tsx] +/// +import * as React from "react"; + +interface ErrorResult { error: true } + +interface AsyncLoaderProps { + readonly prop1: () => Promise; + + readonly prop2: (result: Exclude) => any; +} + +class AsyncLoader extends React.Component> { + render() { return null; } +} + +async function load(): Promise<{ success: true } | ErrorResult> { + return { success: true }; +} + +const loader = result} +/>; + + +//// [checkJsxSubtleSkipContextSensitiveBug.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + 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); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +exports.__esModule = true; +/// +var React = require("react"); +var AsyncLoader = /** @class */ (function (_super) { + __extends(AsyncLoader, _super); + function AsyncLoader() { + return _super !== null && _super.apply(this, arguments) || this; + } + AsyncLoader.prototype.render = function () { return null; }; + return AsyncLoader; +}(React.Component)); +function load() { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, { success: true }]; + }); + }); +} +var loader = React.createElement(AsyncLoader, { prop1: load, prop2: function (result) { return result; } }); diff --git a/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.symbols b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.symbols new file mode 100644 index 00000000000..4a42e972f49 --- /dev/null +++ b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.symbols @@ -0,0 +1,64 @@ +=== tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx === +/// +import * as React from "react"; +>React : Symbol(React, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 1, 6)) + +interface ErrorResult { error: true } +>ErrorResult : Symbol(ErrorResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 1, 31)) +>error : Symbol(ErrorResult.error, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 3, 23)) + +interface AsyncLoaderProps { +>AsyncLoaderProps : Symbol(AsyncLoaderProps, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 3, 37)) +>TResult : Symbol(TResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 5, 27)) + + readonly prop1: () => Promise; +>prop1 : Symbol(AsyncLoaderProps.prop1, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 5, 37)) +>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, --, --)) +>TResult : Symbol(TResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 5, 27)) + + readonly prop2: (result: Exclude) => any; +>prop2 : Symbol(AsyncLoaderProps.prop2, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 6, 43)) +>result : Symbol(result, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 8, 21)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>TResult : Symbol(TResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 5, 27)) +>ErrorResult : Symbol(ErrorResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 1, 31)) +} + +class AsyncLoader extends React.Component> { +>AsyncLoader : Symbol(AsyncLoader, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 9, 1)) +>TResult : Symbol(TResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 11, 18)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 1, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>AsyncLoaderProps : Symbol(AsyncLoaderProps, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 3, 37)) +>TResult : Symbol(TResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 11, 18)) + + render() { return null; } +>render : Symbol(AsyncLoader.render, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 11, 79)) +} + +async function load(): Promise<{ success: true } | ErrorResult> { +>load : Symbol(load, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 13, 1)) +>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, --, --)) +>success : Symbol(success, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 15, 32)) +>ErrorResult : Symbol(ErrorResult, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 1, 31)) + + return { success: true }; +>success : Symbol(success, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 16, 12)) +} + +const loader = loader : Symbol(loader, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 19, 5)) +>AsyncLoader : Symbol(AsyncLoader, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 9, 1)) + + prop1={load} +>prop1 : Symbol(prop1, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 19, 27)) +>load : Symbol(load, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 13, 1)) + + prop2={result => result} +>prop2 : Symbol(prop2, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 20, 16)) +>result : Symbol(result, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 21, 11)) +>result : Symbol(result, Decl(checkJsxSubtleSkipContextSensitiveBug.tsx, 21, 11)) + +/>; + diff --git a/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.types b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.types new file mode 100644 index 00000000000..da2947255e6 --- /dev/null +++ b/tests/baselines/reference/checkJsxSubtleSkipContextSensitiveBug.types @@ -0,0 +1,57 @@ +=== tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx === +/// +import * as React from "react"; +>React : typeof React + +interface ErrorResult { error: true } +>error : true +>true : true + +interface AsyncLoaderProps { + readonly prop1: () => Promise; +>prop1 : () => Promise + + readonly prop2: (result: Exclude) => any; +>prop2 : (result: Exclude) => any +>result : Exclude +} + +class AsyncLoader extends React.Component> { +>AsyncLoader : AsyncLoader +>React.Component : React.Component, {}, any> +>React : typeof React +>Component : typeof React.Component + + render() { return null; } +>render : () => null +>null : null +} + +async function load(): Promise<{ success: true } | ErrorResult> { +>load : () => Promise +>success : true +>true : true + + return { success: true }; +>{ success: true } : { success: true; } +>success : true +>true : true +} + +const loader = loader : JSX.Element +> result}/> : JSX.Element +>AsyncLoader : typeof AsyncLoader + + prop1={load} +>prop1 : () => Promise +>load : () => Promise + + prop2={result => result} +>prop2 : (result: { success: true; }) => { success: true; } +>result => result : (result: { success: true; }) => { success: true; } +>result : { success: true; } +>result : { success: true; } + +/>; + diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index dbd66a298e6..747bbb9db8e 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,13): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,13): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,13): error TS2322: Type '{ onClick: (k: any) => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,13): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. @@ -45,7 +45,7 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,13): err !!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~ -!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ onClick: (k: any) => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. !!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. const b3 = ; // goTo has type"home" | "contact" ~~~~~~~~~~ diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.types b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.types index badb7b0d4e9..1d3508ff5c7 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.types +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.types @@ -81,14 +81,14 @@ const b2 = {console.log(k)}} extra />; // k has type >b2 : JSX.Element >{console.log(k)}} extra /> : JSX.Element >MainButton : { (buttonProps: ButtonProps): JSX.Element; (linkProps: LinkProps): JSX.Element; } ->onClick : (k: "left" | "right") => void ->(k)=>{console.log(k)} : (k: "left" | "right") => void ->k : "left" | "right" +>onClick : (k: any) => void +>(k)=>{console.log(k)} : (k: any) => void +>k : any >console.log(k) : void >console.log : (message?: any, ...optionalParams: any[]) => void >console : Console >log : (message?: any, ...optionalParams: any[]) => void ->k : "left" | "right" +>k : any >extra : true const b3 = ; // goTo has type"home" | "contact" diff --git a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt index 3becdf989bf..dbc1e42c572 100644 --- a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt +++ b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt @@ -40,7 +40,7 @@ tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx(64,37): error TS2322: !!! error TS2322: Type '(value: string) => void' is not assignable to type '"a" | "b" | ((value: string) => boolean) | undefined'. !!! error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. !!! error TS2322: Type 'void' is not assignable to type 'boolean'. -!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:6:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children" | "error"> & Partial & Readonly, "when">> & Partial boolean; }, never>>' +!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:6:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children" | "error"> & Partial & Readonly, "when">> & Partial boolean; }, never>>' class FieldFeedbackBeta

extends React.Component

{ static defaultProps: BaseProps = { @@ -61,7 +61,7 @@ tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx(64,37): error TS2322: !!! error TS2322: Type '(value: string) => void' is not assignable to type '"a" | "b" | ((value: string) => boolean) | undefined'. !!! error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. !!! error TS2322: Type 'void' is not assignable to type 'boolean'. -!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:6:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children"> & Partial & Readonly, "when" | "error">> & Partial>' +!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:6:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children"> & Partial & Readonly, "when" | "error">> & Partial>' interface MyPropsProps extends Props { when: (value: string) => boolean; diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt index 170591a8868..9101537a6e9 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/jsx/file.tsx(48,13): error TS2322: Type '{ children: string; to: string; onClick: (e: MouseEvent) => void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. +tests/cases/conformance/jsx/file.tsx(48,13): error TS2322: Type '{ children: string; to: string; onClick: (e: any) => void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. tests/cases/conformance/jsx/file.tsx(54,51): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/jsx/file.tsx(55,68): error TS2322: Type 'true' is not assignable to type 'string'. @@ -55,7 +55,7 @@ tests/cases/conformance/jsx/file.tsx(56,24): error TS2322: Type 'true' is not as // Error const b0 = {}}>GO; // extra property; ~~~~~~~~~~ -!!! error TS2322: Type '{ children: string; to: string; onClick: (e: MouseEvent) => void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. +!!! error TS2322: Type '{ children: string; to: string; onClick: (e: any) => void; }' is not assignable to type 'IntrinsicAttributes & HyphenProps'. !!! error TS2322: Property 'to' does not exist on type 'IntrinsicAttributes & HyphenProps'. const b1 = {}} {...obj0}>Hello world; // extra property; const b2 = ; // extra property diff --git a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.types b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.types index 6a9b770ef48..d9b40dad94f 100644 --- a/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.types +++ b/tests/baselines/reference/tsxStatelessFunctionComponentOverload5.types @@ -113,9 +113,9 @@ const b0 = {}}>GO; // ex >{}}>GO : JSX.Element >MainButton : { (buttonProps: ButtonProps): JSX.Element; (linkProps: LinkProps): JSX.Element; (hyphenProps: HyphenProps): JSX.Element; } >to : string ->onClick : (e: React.MouseEvent) => void ->(e)=>{} : (e: React.MouseEvent) => void ->e : React.MouseEvent +>onClick : (e: any) => void +>(e)=>{} : (e: any) => void +>e : any >MainButton : { (buttonProps: ButtonProps): JSX.Element; (linkProps: LinkProps): JSX.Element; (hyphenProps: HyphenProps): JSX.Element; } const b1 = {}} {...obj0}>Hello world; // extra property; diff --git a/tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx b/tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx new file mode 100644 index 00000000000..bd08657e93f --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxSubtleSkipContextSensitiveBug.tsx @@ -0,0 +1,27 @@ +// @strict: true +// @jsx: react +// @lib: es6 +// @skipLibCheck: true +/// +import * as React from "react"; + +interface ErrorResult { error: true } + +interface AsyncLoaderProps { + readonly prop1: () => Promise; + + readonly prop2: (result: Exclude) => any; +} + +class AsyncLoader extends React.Component> { + render() { return null; } +} + +async function load(): Promise<{ success: true } | ErrorResult> { + return { success: true }; +} + +const loader = result} +/>; From 6e5e09cef8d96b14f1c7112d3ef7189fb1714465 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 16:44:32 -0700 Subject: [PATCH 098/262] Reject return type inferences to the autoType or autoArrayType (#27169) * Reject return type inferences to the autoType or autoArrayType * Accept new error positions --- src/compiler/checker.ts | 6 +- ...renceShouldFailOnEvolvingArrays.errors.txt | 36 +++++++++ .../inferenceShouldFailOnEvolvingArrays.js | 39 +++++++++ ...nferenceShouldFailOnEvolvingArrays.symbols | 73 +++++++++++++++++ .../inferenceShouldFailOnEvolvingArrays.types | 79 +++++++++++++++++++ .../inferenceShouldFailOnEvolvingArrays.ts | 19 +++++ 6 files changed, 249 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.errors.txt create mode 100644 tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.js create mode 100644 tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.symbols create mode 100644 tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.types create mode 100644 tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 082c31416a2..acfcc313490 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13665,7 +13665,7 @@ namespace ts { // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType) { + if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType || (priority & InferencePriority.ReturnType && (source === autoType || source === autoArrayType))) { return; } const inference = getInferenceInfoForType(target); @@ -14904,7 +14904,7 @@ namespace ts { // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. - const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + const resultType = getObjectFlags(evolvedType) & ObjectFlags.EvolvingArray && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent && reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } @@ -15895,7 +15895,7 @@ namespace ts { // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { + if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); diff --git a/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.errors.txt b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.errors.txt new file mode 100644 index 00000000000..e8081e02cbd --- /dev/null +++ b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.errors.txt @@ -0,0 +1,36 @@ +tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts(7,11): error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. +tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts(9,15): error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. +tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts(15,17): error TS2322: Type 'number' is not assignable to type 'string'. +tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts(17,19): error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. +tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts(18,22): error TS2322: Type 'number' is not assignable to type 'string'. + + +==== tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts (5 errors) ==== + // repro from https://github.com/Microsoft/TypeScript/issues/25675 + // The type of `arg` blocks inference but simplifies to T. + function logLength(arg: { [K in U]: T }[U]): T { + console.log(arg.length); + return arg; + } + logLength(42); // error + ~~ +!!! error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. + let z; + z = logLength(42); // no error; T is inferred as `any` + ~~ +!!! error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. + + function logFirstLength(arg: { [K in U]: T }[U]): T { + console.log(arg[0].length); + return arg; + } + logFirstLength([42]); // error + ~~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. + let zz = []; + zz.push(logLength(42)); // no error; T is inferred as `any` + ~~ +!!! error TS2345: Argument of type '42' is not assignable to parameter of type 'string'. + zz = logFirstLength([42]); // no error; T is inferred as `any[]` + ~~ +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.js b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.js new file mode 100644 index 00000000000..805634b17e1 --- /dev/null +++ b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.js @@ -0,0 +1,39 @@ +//// [inferenceShouldFailOnEvolvingArrays.ts] +// repro from https://github.com/Microsoft/TypeScript/issues/25675 +// The type of `arg` blocks inference but simplifies to T. +function logLength(arg: { [K in U]: T }[U]): T { + console.log(arg.length); + return arg; +} +logLength(42); // error +let z; +z = logLength(42); // no error; T is inferred as `any` + +function logFirstLength(arg: { [K in U]: T }[U]): T { + console.log(arg[0].length); + return arg; +} +logFirstLength([42]); // error +let zz = []; +zz.push(logLength(42)); // no error; T is inferred as `any` +zz = logFirstLength([42]); // no error; T is inferred as `any[]` + +//// [inferenceShouldFailOnEvolvingArrays.js] +"use strict"; +// repro from https://github.com/Microsoft/TypeScript/issues/25675 +// The type of `arg` blocks inference but simplifies to T. +function logLength(arg) { + console.log(arg.length); + return arg; +} +logLength(42); // error +var z; +z = logLength(42); // no error; T is inferred as `any` +function logFirstLength(arg) { + console.log(arg[0].length); + return arg; +} +logFirstLength([42]); // error +var zz = []; +zz.push(logLength(42)); // no error; T is inferred as `any` +zz = logFirstLength([42]); // no error; T is inferred as `any[]` diff --git a/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.symbols b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.symbols new file mode 100644 index 00000000000..287e7f81c86 --- /dev/null +++ b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.symbols @@ -0,0 +1,73 @@ +=== tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/25675 +// The type of `arg` blocks inference but simplifies to T. +function logLength(arg: { [K in U]: T }[U]): T { +>logLength : Symbol(logLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 0, 0)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 19)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 36)) +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 55)) +>K : Symbol(K, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 63)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 36)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 19)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 36)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 19)) + + console.log(arg.length); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>arg.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 55)) +>length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) + + return arg; +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 2, 55)) +} +logLength(42); // error +>logLength : Symbol(logLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 0, 0)) + +let z; +>z : Symbol(z, Decl(inferenceShouldFailOnEvolvingArrays.ts, 7, 3)) + +z = logLength(42); // no error; T is inferred as `any` +>z : Symbol(z, Decl(inferenceShouldFailOnEvolvingArrays.ts, 7, 3)) +>logLength : Symbol(logLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 0, 0)) + +function logFirstLength(arg: { [K in U]: T }[U]): T { +>logFirstLength : Symbol(logFirstLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 8, 18)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 24)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 43)) +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 62)) +>K : Symbol(K, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 70)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 43)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 24)) +>U : Symbol(U, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 43)) +>T : Symbol(T, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 24)) + + console.log(arg[0].length); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>arg[0].length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 62)) +>length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) + + return arg; +>arg : Symbol(arg, Decl(inferenceShouldFailOnEvolvingArrays.ts, 10, 62)) +} +logFirstLength([42]); // error +>logFirstLength : Symbol(logFirstLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 8, 18)) + +let zz = []; +>zz : Symbol(zz, Decl(inferenceShouldFailOnEvolvingArrays.ts, 15, 3)) + +zz.push(logLength(42)); // no error; T is inferred as `any` +>zz.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) +>zz : Symbol(zz, Decl(inferenceShouldFailOnEvolvingArrays.ts, 15, 3)) +>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) +>logLength : Symbol(logLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 0, 0)) + +zz = logFirstLength([42]); // no error; T is inferred as `any[]` +>zz : Symbol(zz, Decl(inferenceShouldFailOnEvolvingArrays.ts, 15, 3)) +>logFirstLength : Symbol(logFirstLength, Decl(inferenceShouldFailOnEvolvingArrays.ts, 8, 18)) + diff --git a/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.types b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.types new file mode 100644 index 00000000000..2d7876aefe9 --- /dev/null +++ b/tests/baselines/reference/inferenceShouldFailOnEvolvingArrays.types @@ -0,0 +1,79 @@ +=== tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/25675 +// The type of `arg` blocks inference but simplifies to T. +function logLength(arg: { [K in U]: T }[U]): T { +>logLength : (arg: { [K in U]: T; }[U]) => T +>arg : { [K in U]: T; }[U] + + console.log(arg.length); +>console.log(arg.length) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>arg.length : number +>arg : { [K in U]: T; }[U] +>length : number + + return arg; +>arg : { [K in U]: T; }[U] +} +logLength(42); // error +>logLength(42) : any +>logLength : (arg: { [K in U]: T; }[U]) => T +>42 : 42 + +let z; +>z : any + +z = logLength(42); // no error; T is inferred as `any` +>z = logLength(42) : any +>z : any +>logLength(42) : any +>logLength : (arg: { [K in U]: T; }[U]) => T +>42 : 42 + +function logFirstLength(arg: { [K in U]: T }[U]): T { +>logFirstLength : (arg: { [K in U]: T; }[U]) => T +>arg : { [K in U]: T; }[U] + + console.log(arg[0].length); +>console.log(arg[0].length) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>arg[0].length : number +>arg[0] : string +>arg : { [K in U]: T; }[U] +>0 : 0 +>length : number + + return arg; +>arg : { [K in U]: T; }[U] +} +logFirstLength([42]); // error +>logFirstLength([42]) : any +>logFirstLength : (arg: { [K in U]: T; }[U]) => T +>[42] : number[] +>42 : 42 + +let zz = []; +>zz : any[] +>[] : never[] + +zz.push(logLength(42)); // no error; T is inferred as `any` +>zz.push(logLength(42)) : number +>zz.push : (...items: any[]) => number +>zz : any[] +>push : (...items: any[]) => number +>logLength(42) : any +>logLength : (arg: { [K in U]: T; }[U]) => T +>42 : 42 + +zz = logFirstLength([42]); // no error; T is inferred as `any[]` +>zz = logFirstLength([42]) : any +>zz : any[] +>logFirstLength([42]) : any +>logFirstLength : (arg: { [K in U]: T; }[U]) => T +>[42] : number[] +>42 : 42 + diff --git a/tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts b/tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts new file mode 100644 index 00000000000..13a24ce66f9 --- /dev/null +++ b/tests/cases/compiler/inferenceShouldFailOnEvolvingArrays.ts @@ -0,0 +1,19 @@ +// @strict: true +// repro from https://github.com/Microsoft/TypeScript/issues/25675 +// The type of `arg` blocks inference but simplifies to T. +function logLength(arg: { [K in U]: T }[U]): T { + console.log(arg.length); + return arg; +} +logLength(42); // error +let z; +z = logLength(42); // no error; T is inferred as `any` + +function logFirstLength(arg: { [K in U]: T }[U]): T { + console.log(arg[0].length); + return arg; +} +logFirstLength([42]); // error +let zz = []; +zz.push(logLength(42)); // no error; T is inferred as `any` +zz = logFirstLength([42]); // no error; T is inferred as `any[]` \ No newline at end of file From 76addd75d147b6cdd319fc54ceffe2c76086c61b Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 16:45:39 -0700 Subject: [PATCH 099/262] Add JSXText check into isValidLocationToAddComment (#27653) * Add JSXText check into isValidLocationToAddComment * Small simplification --- src/services/textChanges.ts | 2 +- src/services/utilities.ts | 14 +++ .../jsxTsIgnoreOnJSXExpressionsAndChildren.ts | 95 +++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/jsxTsIgnoreOnJSXExpressionsAndChildren.ts diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 0d45039f5b1..b9a13fc5420 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -1075,7 +1075,7 @@ namespace ts.textChanges { } export function isValidLocationToAddComment(sourceFile: SourceFile, position: number) { - return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position); + return !isInComment(sourceFile, position) && !isInString(sourceFile, position) && !isInTemplateString(sourceFile, position) && !isInJSXText(sourceFile, position); } function needSemicolonBetween(a: Node, b: Node): boolean { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index f0326599ad0..7a713fed749 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -909,6 +909,20 @@ namespace ts { return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } + export function isInJSXText(sourceFile: SourceFile, position: number) { + const token = getTokenAtPosition(sourceFile, position); + if (isJsxText(token)) { + return true; + } + if (token.kind === SyntaxKind.OpenBraceToken && isJsxExpression(token.parent) && isJsxElement(token.parent.parent)) { + return true; + } + if (token.kind === SyntaxKind.LessThanToken && isJsxOpeningLikeElement(token.parent) && isJsxElement(token.parent.parent)) { + return true; + } + return false; + } + export function findPrecedingMatchingToken(token: Node, matchingTokenKind: SyntaxKind, sourceFile: SourceFile) { const tokenKind = token.kind; let remainingMatchingTokens = 0; diff --git a/tests/cases/fourslash/jsxTsIgnoreOnJSXExpressionsAndChildren.ts b/tests/cases/fourslash/jsxTsIgnoreOnJSXExpressionsAndChildren.ts new file mode 100644 index 00000000000..9670a88cc3d --- /dev/null +++ b/tests/cases/fourslash/jsxTsIgnoreOnJSXExpressionsAndChildren.ts @@ -0,0 +1,95 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @jsx: react +// @esModuleInterop: true +// @skipLibCheck: true +// @Filename: declarations.d.ts +////declare namespace JSX { +//// interface Element {} +//// interface IntrinsicElements { [index: string]: {} } +////} +////declare var React: any; +// @Filename: MyComponent.jsx +////class MyComponent extends React.Component { +//// render() { +//// return ( +////

+//// {[|/*1*/doesNotExist|]} +////
+//// ); +//// } +////} +// @Filename: MyComponent2.jsx +////class MyComponent2 extends React.Component { +//// render() { +//// return ( +////
+//// Aleph{[|/*2*/doesNotExist|]}Bet +////
+//// ); +//// } +////} +// @Filename: MyComponent3.jsx +////class MyComponent3 extends React.Component { +//// render() { +//// return ( +////
+//// <[|/*3*/DoesNotExist|] /> +////
+//// ); +//// } +////} + +goTo.file(1); +verify.getSyntacticDiagnostics([]); +verify.getSemanticDiagnostics([{ code: 2304, message: "Cannot find name 'doesNotExist'." }]); +verify.codeFix({ + index: 0, + description: "Ignore this error message", + newFileContent: `class MyComponent extends React.Component { + render() { + return ( +
+ { +// @ts-ignore + doesNotExist} +
+ ); + } +}` +}); +goTo.file(2); +verify.codeFix({ + index: 0, + description: "Ignore this error message", + newFileContent: `class MyComponent2 extends React.Component { + render() { + return ( +
+ Aleph{ +// @ts-ignore + doesNotExist}Bet +
+ ); + } +}` +}); +goTo.file(3); +verify.codeFix({ + index: 0, + description: "Ignore this error message", + newFileContent: `class MyComponent3 extends React.Component { + render() { + return ( +
+ < +// @ts-ignore + DoesNotExist /> +
+ ); + } +}` +}); From 82773b855003666a7d4b2384307b258223858911 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 18:17:09 -0700 Subject: [PATCH 100/262] Fix bug: only getCompletionEntriesFromTypings if completions are for top-level directory (#27226) * Fix bug: only getCompletionEntriesFromTypings if completions are for top-level directory * Support subdirectories of a nonrelative import --- src/compiler/utilities.ts | 2 + src/services/pathCompletions.ts | 216 +++++++++--------- .../fourslash/completionsPaths_fromTypings.ts | 18 ++ 3 files changed, 128 insertions(+), 108 deletions(-) create mode 100644 tests/cases/fourslash/completionsPaths_fromTypings.ts diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index bd1d874e9dc..8cf7db15714 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -8040,6 +8040,8 @@ namespace ts { const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; const allSupportedExtensionsWithJson: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json]; + export function getSupportedExtensions(options?: CompilerOptions): ReadonlyArray; + export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 22cc56903c0..d1c365c7117 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -26,14 +26,14 @@ namespace ts.Completions.PathCompletions { const scriptPath = sourceFile.path; const scriptDirectory = getDirectoryPath(scriptPath); + const extensionOptions = getExtensionOptions(compilerOptions); if (isPathRelativeToScript(literalValue) || isRootedDiskPath(literalValue)) { - const extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); + compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); } } else { @@ -41,7 +41,14 @@ namespace ts.Completions.PathCompletions { } } - function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions) { + interface ExtensionOptions { + readonly extensions: ReadonlyArray; + readonly includeExtensions: boolean; + } + function getExtensionOptions(compilerOptions: CompilerOptions, includeExtensions = false): ExtensionOptions { + return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions }; + } + function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): ReadonlyArray { const extensions = getSupportedExtensions(compilerOptions); return compilerOptions.resolveJsonModule && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs ? extensions.concat(Extension.Json) : @@ -67,7 +74,7 @@ namespace ts.Completions.PathCompletions { compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude?: string): NameAndKind[] { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs: string[], fragment: string, scriptPath: string, extensionOptions: ExtensionOptions, compilerOptions: CompilerOptions, host: LanguageServiceHost, exclude?: string): NameAndKind[] { const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); @@ -75,7 +82,7 @@ namespace ts.Completions.PathCompletions { const result: NameAndKind[] = []; for (const baseDirectory of baseDirectories) { - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude, result); } return result; @@ -84,7 +91,7 @@ namespace ts.Completions.PathCompletions { /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, extensions: ReadonlyArray, includeExtensions: boolean, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] { + function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, { extensions, includeExtensions }: ExtensionOptions, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] { if (fragment === undefined) { fragment = ""; } @@ -108,62 +115,62 @@ namespace ts.Completions.PathCompletions { // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths const absolutePath = resolvePath(scriptPath, fragment); const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); + const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); + if (!tryDirectoryExists(host, baseDirectory)) return result; - if (tryDirectoryExists(host, baseDirectory)) { - // Enumerate the available files if possible - const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); + // Enumerate the available files if possible + const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (files) { - /** - * Multiple file entries might map to the same truncated name once we remove extensions - * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: - * - * both foo.ts and foo.tsx become foo - */ - const foundFiles = createMap(); - for (let filePath of files) { - filePath = normalizePath(filePath); - if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) { - continue; - } - - const foundFileName = includeExtensions || fileExtensionIs(filePath, Extension.Json) ? getBaseFileName(filePath) : removeFileExtension(getBaseFileName(filePath)); - - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ + const foundFiles = createMap(); + for (let filePath of files) { + filePath = normalizePath(filePath); + if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) { + continue; } - forEachKey(foundFiles, foundFile => { - result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement)); - }); - } + const foundFileName = includeExtensions || fileExtensionIs(filePath, Extension.Json) ? getBaseFileName(filePath) : removeFileExtension(getBaseFileName(filePath)); - // If possible, get folder completion as well - const directories = tryGetDirectories(host, baseDirectory); - - if (directories) { - for (const directory of directories) { - const directoryName = getBaseFileName(normalizePath(directory)); - if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, ScriptElementKind.directory)); - } + if (!foundFiles.has(foundFileName)) { + foundFiles.set(foundFileName, true); } } - // check for a version redirect - const packageJsonPath = findPackageJson(baseDirectory, host); - if (packageJsonPath) { - const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); - const typesVersions = (packageJson as any).typesVersions; - if (typeof typesVersions === "object") { - const versionResult = getPackageJsonTypesVersionsPaths(typesVersions); - const versionPaths = versionResult && versionResult.paths; - const rest = absolutePath.slice(ensureTrailingDirectorySeparator(baseDirectory).length); - if (versionPaths) { - addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); - } + forEachKey(foundFiles, foundFile => { + result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement)); + }); + } + + // If possible, get folder completion as well + const directories = tryGetDirectories(host, baseDirectory); + + if (directories) { + for (const directory of directories) { + const directoryName = getBaseFileName(normalizePath(directory)); + if (directoryName !== "@types") { + result.push(nameAndKind(directoryName, ScriptElementKind.directory)); + } + } + } + + // check for a version redirect + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const typesVersions = (packageJson as any).typesVersions; + if (typeof typesVersions === "object") { + const versionResult = getPackageJsonTypesVersionsPaths(typesVersions); + const versionPaths = versionResult && versionResult.paths; + const rest = absolutePath.slice(ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); } } } @@ -198,22 +205,22 @@ namespace ts.Completions.PathCompletions { const result: NameAndKind[] = []; - const fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); + const extensionOptions = getExtensionOptions(compilerOptions); if (baseUrl) { const projectDir = compilerOptions.project || host.getCurrentDirectory(); const absolute = normalizePath(combinePaths(projectDir, baseUrl)); - getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result); if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host); } } - const fragmentDirectory = containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; + const fragmentDirectory = getFragmentDirectory(fragment); for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs) { // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. @@ -231,7 +238,7 @@ namespace ts.Completions.PathCompletions { forEachAncestorDirectory(scriptPath, ancestor => { const nodeModules = combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, extensionOptions, host, /*exclude*/ undefined, result); } }); } @@ -240,6 +247,10 @@ namespace ts.Completions.PathCompletions { return result; } + function getFragmentDirectory(fragment: string): string | undefined { + return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : undefined; + } + function getCompletionsForPathMapping( path: string, patterns: ReadonlyArray, fragment: string, baseUrl: string, fileExtensions: ReadonlyArray, host: LanguageServiceHost, ): ReadonlyArray { @@ -339,53 +350,45 @@ namespace ts.Completions.PathCompletions { const [, prefix, kind, toComplete] = match; const scriptPath = getDirectoryPath(sourceFile.path); - const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) - : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) - : undefined; - return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); + const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, /*includeExtensions*/ true), host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions)) + : Debug.fail(); + return addReplacementSpans(toComplete, range.pos + prefix.length, names); } - function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, result: NameAndKind[] = []): NameAndKind[] { + function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result: NameAndKind[] = []): ReadonlyArray { // Check for typings specified in compiler options const seen = createMap(); - if (options.types) { - for (const typesName of options.types) { - const moduleName = unmangleScopedPackageName(typesName); - pushResult(moduleName); - } + + const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray; + + for (const root of typeRoots) { + getCompletionEntriesFromDirectories(root); } - else if (host.getDirectories) { - let typeRoots: ReadonlyArray | undefined; - try { - typeRoots = getEffectiveTypeRoots(options, host); - } - catch { /* Wrap in try catch because getEffectiveTypeRoots touches the filesystem */ } - if (typeRoots) { - for (const root of typeRoots) { - getCompletionEntriesFromDirectories(root); - } - } - - // Also get all @types typings installed in visible node_modules directories - for (const packageJson of findPackageJsons(scriptPath, host)) { - const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + // Also get all @types typings installed in visible node_modules directories + for (const packageJson of findPackageJsons(scriptPath, host)) { + const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; - function getCompletionEntriesFromDirectories(directory: string) { - Debug.assert(!!host.getDirectories); - if (tryDirectoryExists(host, directory)) { - const directories = tryGetDirectories(host, directory); - if (directories) { - for (let typeDirectory of directories) { - typeDirectory = normalizePath(typeDirectory); - const directoryName = getBaseFileName(typeDirectory); - const moduleName = unmangleScopedPackageName(directoryName); - pushResult(moduleName); + function getCompletionEntriesFromDirectories(directory: string): void { + if (!tryDirectoryExists(host, directory)) return; + + for (const typeDirectoryName of tryGetDirectories(host, directory)) { + const packageName = unmangleScopedPackageName(typeDirectoryName); + if (options.types && !contains(options.types, packageName)) continue; + + if (fragmentDirectory === undefined) { + pushResult(packageName); + } + else { + const baseDirectory = combinePaths(directory, typeDirectoryName); + const remainingFragment = tryRemoveDirectoryPrefix(fragmentDirectory, packageName, hostGetCanonicalFileName(host)); + if (remainingFragment !== undefined) { + getCompletionEntriesForDirectoryFragment(remainingFragment, baseDirectory, extensionOptions, host, /*exclude*/ undefined, result); } } } @@ -476,7 +479,7 @@ namespace ts.Completions.PathCompletions { */ const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; function tryGetDirectories(host: LanguageServiceHost, directoryName: string): string[] { return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; @@ -491,19 +494,16 @@ namespace ts.Completions.PathCompletions { } function tryDirectoryExists(host: LanguageServiceHost, path: string): boolean { - try { - return directoryProbablyExists(path, host); - } - catch { /*ignore*/ } - return false; + return tryAndIgnoreErrors(() => directoryProbablyExists(path, host)) || false; } function tryIOAndConsumeErrors(host: LanguageServiceHost, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { - try { - return toApply && toApply.apply(host, args); - } - catch { /*ignore*/ } - return undefined; + return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); + } + + function tryAndIgnoreErrors(cb: () => T): T | undefined { + try { return cb(); } + catch { return undefined; } } function containsSlash(fragment: string) { diff --git a/tests/cases/fourslash/completionsPaths_fromTypings.ts b/tests/cases/fourslash/completionsPaths_fromTypings.ts new file mode 100644 index 00000000000..65547b3111d --- /dev/null +++ b/tests/cases/fourslash/completionsPaths_fromTypings.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /node_modules/@types/foo/index.d.ts +//// + +// @Filename: /node_modules/@types/foo/bar.d.ts +//// + +// @Filename: /a.ts +////import {} from "unrelated//*0*/"; +////import {} from "foo//*1*/"; +/////// + +verify.completions( + { marker: "0", exact: [], isNewIdentifierLocation: true }, + { marker: "1", exact: ["bar", "index"], isNewIdentifierLocation: true }, + { marker: "2", exact: ["bar", "index"], isNewIdentifierLocation: true }, +); From 5becc3b170ddaefce4f43d5e4fd185bc1e5f2ab7 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 22 Oct 2018 18:17:32 -0700 Subject: [PATCH 101/262] Rename of non-intrinsic JSX element should rename the declaration (#28066) --- src/compiler/utilities.ts | 2 +- src/services/services.ts | 2 +- tests/cases/fourslash/tsxRename4.ts | 16 ++++++++++++---- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 8cf7db15714..7c96bb653b2 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3089,7 +3089,7 @@ namespace ts { export function isIntrinsicJsxName(name: __String | string) { const ch = (name as string).charCodeAt(0); - return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || (name as string).indexOf("-") > -1; + return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains((name as string), "-"); } function get16BitUnicodeEscapeSequence(charCode: number): string { diff --git a/src/services/services.ts b/src/services/services.ts index 27a458bf1ef..725decf18f2 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1542,7 +1542,7 @@ namespace ts { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getTouchingPropertyName(sourceFile, position); - if (isIdentifier(node) && isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) { + if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) { const { openingElement, closingElement } = node.parent.parent; return [openingElement, closingElement].map((node): RenameLocation => ({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) })); diff --git a/tests/cases/fourslash/tsxRename4.ts b/tests/cases/fourslash/tsxRename4.ts index ac25b048008..e46c2b7ebcb 100644 --- a/tests/cases/fourslash/tsxRename4.ts +++ b/tests/cases/fourslash/tsxRename4.ts @@ -1,15 +1,23 @@ /// +// @jsx: preserve + //@Filename: file.tsx ////declare module JSX { //// interface Element {} -//// interface IntrinsicElements {} +//// interface IntrinsicElements { +//// div: {}; +//// } ////} ////class [|MyClass|] {} //// ////<[|MyClass|]>; ////<[|MyClass|]/>; +//// +////<[|div|]> -const [r0, r1, r2, r3] = test.ranges(); -verify.renameLocations([r0, r3], [r0, r1, r2, r3]); -verify.renameLocations([r1, r2], [r1, r2]); +verify.noErrors(); + +const [r0, r1, r2, r3, d0, d1] = test.ranges(); +verify.rangesAreRenameLocations([r0, r1, r2, r3]); +verify.rangesAreRenameLocations([d0, d1]); From fbd6cad437390693e69707928896d7da620a803e Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 22 Oct 2018 19:18:20 -0700 Subject: [PATCH 102/262] Like #27964 but for JSX (#28068) --- src/compiler/visitor.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index b2ab3b19b47..18b7c3f4a74 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -1378,6 +1378,7 @@ namespace ts { case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxOpeningElement: result = reduceNode((node).tagName, cbNode, result); + result = reduceNodes((node).typeArguments, cbNode, result); result = reduceNode((node).attributes, cbNode, result); break; From de318651f36c1e6d59175520f5a6c355c5003fba Mon Sep 17 00:00:00 2001 From: Philip Pesca Date: Mon, 22 Oct 2018 23:03:09 -0700 Subject: [PATCH 103/262] Improve code fix for missing members --- src/services/codefixes/fixAddMissingMember.ts | 4 ++++ tests/cases/fourslash/codeFixAddMissingMember12.ts | 14 ++++++++++++++ tests/cases/fourslash/codeFixAddMissingMember13.ts | 14 ++++++++++++++ .../codeFixAddMissingMember_typeParameter.ts | 2 +- 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/codeFixAddMissingMember12.ts create mode 100644 tests/cases/fourslash/codeFixAddMissingMember13.ts diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index dda0903562a..d1d0afb9059 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -185,6 +185,10 @@ namespace ts.codefix { const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } + else { + const contextualType = checker.getContextualType(token.parent as Expression); + typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + } return typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); } diff --git a/tests/cases/fourslash/codeFixAddMissingMember12.ts b/tests/cases/fourslash/codeFixAddMissingMember12.ts new file mode 100644 index 00000000000..c45939f1d17 --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingMember12.ts @@ -0,0 +1,14 @@ +/// + +//// class C {} +//// const x: number = new C().x; + +verify.codeFix({ + description: "Declare property 'x'", + index: 0, + newFileContent: +`class C { + x: number; +} +const x: number = new C().x;` +}); diff --git a/tests/cases/fourslash/codeFixAddMissingMember13.ts b/tests/cases/fourslash/codeFixAddMissingMember13.ts new file mode 100644 index 00000000000..17c6f3aa0e1 --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingMember13.ts @@ -0,0 +1,14 @@ +/// + +//// class C {} +//// const x: number = new C().x; + +verify.codeFix({ + description: "Add index signature for property 'x'", + index: 1, + newFileContent: +`class C { + [x: string]: number; +} +const x: number = new C().x;` +}); diff --git a/tests/cases/fourslash/codeFixAddMissingMember_typeParameter.ts b/tests/cases/fourslash/codeFixAddMissingMember_typeParameter.ts index 51d476220bb..cbf31744b3b 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_typeParameter.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_typeParameter.ts @@ -19,7 +19,7 @@ verify.codeFix({ index: 0, newFileContent: `interface I { - bar: any; + bar: number; } function f(t: T): number { From 0a7c92864d628c02e450f23ab2547ed1f5954b56 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 23 Oct 2018 09:33:53 -0700 Subject: [PATCH 104/262] Fix Object.defineProperty declaration expando-ness and renames (#28061) * Allow object.defineProperty calls to be expando properties * Fix rename locations for object.defineProperty assignments --- src/compiler/binder.ts | 3 + src/compiler/checker.ts | 6 + src/compiler/utilities.ts | 14 +- src/services/findAllReferences.ts | 2 +- .../checkExportsObjectAssignProperty.symbols | 122 ++++++++++-------- ...portsObjectAssignPrototypeProperty.symbols | 59 +++++---- .../checkObjectDefineProperty.symbols | 66 +++++----- .../checkOtherObjectAssignProperty.symbols | 36 +++--- ...nmentDefineProperrtyPotentialMerge.symbols | 2 + .../jsExpandoObjectDefineProperty.symbols | 20 +++ .../jsExpandoObjectDefineProperty.types | 27 ++++ .../compiler/jsExpandoObjectDefineProperty.ts | 7 + .../jsObjectDefinePropertyRenameLocations.ts | 17 +++ 13 files changed, 249 insertions(+), 132 deletions(-) create mode 100644 tests/baselines/reference/jsExpandoObjectDefineProperty.symbols create mode 100644 tests/baselines/reference/jsExpandoObjectDefineProperty.types create mode 100644 tests/cases/compiler/jsExpandoObjectDefineProperty.ts create mode 100644 tests/cases/fourslash/jsObjectDefinePropertyRenameLocations.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 3fba2894002..c35a62b8448 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2607,6 +2607,9 @@ namespace ts { return true; } const node = symbol.valueDeclaration; + if (isCallExpression(node)) { + return !!getAssignedExpandoInitializer(node); + } let init = !node ? undefined : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index acfcc313490..fd786799b8b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4306,6 +4306,9 @@ namespace ts { const declaration = symbol.declarations[0]; const name = getNameOfDeclaration(declaration); if (name) { + if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { + return symbolName(symbol); + } return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { @@ -27819,6 +27822,9 @@ namespace ts { ) { return resolveExternalModuleName(node, node); } + if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case SyntaxKind.NumericLiteral: diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 7c96bb653b2..fa3885d4b76 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1790,16 +1790,26 @@ namespace ts { return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } + function hasExpandoValueProperty(node: ObjectLiteralExpression, isPrototypeAssignment: boolean) { + return forEach(node.properties, p => isPropertyAssignment(p) && isIdentifier(p.name) && p.name.escapedText === "value" && p.initializer && getExpandoInitializer(p.initializer, isPrototypeAssignment)); + } + /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - export function getAssignedExpandoInitializer(node: Node) { + export function getAssignedExpandoInitializer(node: Node | undefined) { if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) { const isPrototypeAssignment = isPrototypeAccess(node.parent.left); return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || getDefaultedExpandoInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); } + if (node && isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) { + const result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype"); + if (result) { + return result; + } + } } /** @@ -2016,7 +2026,7 @@ namespace ts { case SyntaxKind.ExternalModuleReference: return (node.parent as ExternalModuleReference).parent as AnyValidImportOrReExport; case SyntaxKind.CallExpression: - return node.parent as AnyValidImportOrReExport; + return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent as RequireOrImportCall : undefined; case SyntaxKind.LiteralType: Debug.assert(isStringLiteral(node)); return tryCast(node.parent.parent, isImportTypeNode) as ValidImportTypeNode | undefined; diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 2a3e4de87b1..41aae6ae825 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -920,7 +920,7 @@ namespace ts.FindAllReferences.Core { case SyntaxKind.StringLiteral: { const str = node as StringLiteral; - return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || (isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node)) && str.text.length === searchSymbolName.length; } diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols index d33e2de1e20..e1dcacbfe2c 100644 --- a/tests/baselines/reference/checkExportsObjectAssignProperty.symbols +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols @@ -5,141 +5,141 @@ import m1 = require("./mod1"); >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) m1.thing; ->m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) m1.readonlyProp; ->m1.readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>m1.readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) m1.rwAccessors; ->m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) m1.readonlyAccessor; ->m1.readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>m1.readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) m1.setonlyAccessor; ->m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) // allowed assignments m1.thing = 10; ->m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) m1.rwAccessors = 11; ->m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) m1.setonlyAccessor = "yes"; ->m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) // disallowed assignments m1.readonlyProp = "name"; ->m1.readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>m1.readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->readonlyProp : Symbol(m1["readonlyProp"], Decl(mod1.js, 0, 71)) +>readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) m1.readonlyAccessor = 12; ->m1.readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>m1.readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->readonlyAccessor : Symbol(m1["readonlyAccessor"], Decl(mod1.js, 2, 97)) +>readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) m1.thing = "no"; ->m1.thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->thing : Symbol(m1["thing"], Decl(mod1.js, 0, 0)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) m1.rwAccessors = "no"; ->m1.rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->rwAccessors : Symbol(m1["rwAccessors"], Decl(mod1.js, 1, 84)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) m1.setonlyAccessor = 0; ->m1.setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) >m1 : Symbol(m1, Decl(validator.ts, 0, 12)) ->setonlyAccessor : Symbol(m1["setonlyAccessor"], Decl(mod1.js, 3, 79)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) import m2 = require("./mod2"); >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) m2.thing; ->m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) m2.readonlyProp; ->m2.readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>m2.readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) m2.rwAccessors; ->m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) m2.readonlyAccessor; ->m2.readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>m2.readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) m2.setonlyAccessor; ->m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) // allowed assignments m2.thing = "ok"; ->m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) m2.rwAccessors = 11; ->m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) m2.setonlyAccessor = "yes"; ->m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) // disallowed assignments m2.readonlyProp = "name"; ->m2.readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>m2.readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->readonlyProp : Symbol(m2["readonlyProp"], Decl(mod2.js, 0, 81)) +>readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) m2.readonlyAccessor = 12; ->m2.readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>m2.readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->readonlyAccessor : Symbol(m2["readonlyAccessor"], Decl(mod2.js, 2, 104)) +>readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) m2.thing = 0; ->m2.thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->thing : Symbol(m2["thing"], Decl(mod2.js, 0, 0)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) m2.rwAccessors = "no"; ->m2.rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->rwAccessors : Symbol(m2["rwAccessors"], Decl(mod2.js, 1, 91)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) m2.setonlyAccessor = 0; ->m2.setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) >m2 : Symbol(m2, Decl(validator.ts, 20, 23)) ->setonlyAccessor : Symbol(m2["setonlyAccessor"], Decl(mod2.js, 3, 86)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) === tests/cases/conformance/jsdoc/mod1.js === Object.defineProperty(exports, "thing", { value: 42, writable: true }); @@ -147,6 +147,7 @@ Object.defineProperty(exports, "thing", { value: 42, writable: true }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"thing" : Symbol(thing, Decl(mod1.js, 0, 0)) >value : Symbol(value, Decl(mod1.js, 0, 41)) >writable : Symbol(writable, Decl(mod1.js, 0, 52)) @@ -155,6 +156,7 @@ Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"readonlyProp" : Symbol(readonlyProp, Decl(mod1.js, 0, 71)) >value : Symbol(value, Decl(mod1.js, 1, 48)) >writable : Symbol(writable, Decl(mod1.js, 1, 64)) @@ -163,6 +165,7 @@ Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"rwAccessors" : Symbol(rwAccessors, Decl(mod1.js, 1, 84)) >get : Symbol(get, Decl(mod1.js, 2, 47)) >set : Symbol(set, Decl(mod1.js, 2, 71)) >_ : Symbol(_, Decl(mod1.js, 2, 76)) @@ -172,6 +175,7 @@ Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"readonlyAccessor" : Symbol(readonlyAccessor, Decl(mod1.js, 2, 97)) >get : Symbol(get, Decl(mod1.js, 3, 52)) Object.defineProperty(exports, "setonlyAccessor", { @@ -179,6 +183,7 @@ Object.defineProperty(exports, "setonlyAccessor", { >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"setonlyAccessor" : Symbol(setonlyAccessor, Decl(mod1.js, 3, 79)) /** @param {string} str */ set(str) { @@ -200,6 +205,7 @@ Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) >module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) >module : Symbol(module, Decl(mod2.js, 0, 22)) >exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"thing" : Symbol(thing, Decl(mod2.js, 0, 0)) >value : Symbol(value, Decl(mod2.js, 0, 48)) >writable : Symbol(writable, Decl(mod2.js, 0, 62)) @@ -210,6 +216,7 @@ Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable >module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) >module : Symbol(module, Decl(mod2.js, 0, 22)) >exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"readonlyProp" : Symbol(readonlyProp, Decl(mod2.js, 0, 81)) >value : Symbol(value, Decl(mod2.js, 1, 55)) >writable : Symbol(writable, Decl(mod2.js, 1, 71)) @@ -220,6 +227,7 @@ Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, s >module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) >module : Symbol(module, Decl(mod2.js, 0, 22)) >exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"rwAccessors" : Symbol(rwAccessors, Decl(mod2.js, 1, 91)) >get : Symbol(get, Decl(mod2.js, 2, 54)) >set : Symbol(set, Decl(mod2.js, 2, 78)) >_ : Symbol(_, Decl(mod2.js, 2, 83)) @@ -231,6 +239,7 @@ Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 >module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) >module : Symbol(module, Decl(mod2.js, 0, 22)) >exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"readonlyAccessor" : Symbol(readonlyAccessor, Decl(mod2.js, 2, 104)) >get : Symbol(get, Decl(mod2.js, 3, 59)) Object.defineProperty(module.exports, "setonlyAccessor", { @@ -240,6 +249,7 @@ Object.defineProperty(module.exports, "setonlyAccessor", { >module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) >module : Symbol(module, Decl(mod2.js, 0, 22)) >exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"setonlyAccessor" : Symbol(setonlyAccessor, Decl(mod2.js, 3, 86)) /** @param {string} str */ set(str) { @@ -259,18 +269,18 @@ Object.defineProperty(module.exports, "setonlyAccessor", { */ const q = require("./mod1").thing; >q : Symbol(q, Decl(index.js, 3, 5)) ->require("./mod1").thing : Symbol("thing", Decl(mod1.js, 0, 0)) +>require("./mod1").thing : Symbol(thing, Decl(mod1.js, 0, 0)) >require : Symbol(require) >"./mod1" : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) ->thing : Symbol("thing", Decl(mod1.js, 0, 0)) +>thing : Symbol(thing, Decl(mod1.js, 0, 0)) /** * @type {string} */ const u = require("./mod2").thing; >u : Symbol(u, Decl(index.js, 8, 5)) ->require("./mod2").thing : Symbol("thing", Decl(mod2.js, 0, 0)) +>require("./mod2").thing : Symbol(thing, Decl(mod2.js, 0, 0)) >require : Symbol(require) >"./mod2" : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) ->thing : Symbol("thing", Decl(mod2.js, 0, 0)) +>thing : Symbol(thing, Decl(mod2.js, 0, 0)) diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols index 9f04a3600cc..051a342a2b5 100644 --- a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols @@ -9,71 +9,71 @@ const m1 = new Person("Name") >Person : Symbol(Person, Decl(validator.ts, 0, 12)) m1.thing; ->m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) m1.readonlyProp; ->m1.readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>m1.readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) m1.rwAccessors; ->m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) m1.readonlyAccessor; ->m1.readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>m1.readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) m1.setonlyAccessor; ->m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) // allowed assignments m1.thing = 10; ->m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) m1.rwAccessors = 11; ->m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) m1.setonlyAccessor = "yes"; ->m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) // disallowed assignments m1.readonlyProp = "name"; ->m1.readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>m1.readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->readonlyProp : Symbol(Person["readonlyProp"], Decl(mod1.js, 10, 80)) +>readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) m1.readonlyAccessor = 12; ->m1.readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>m1.readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->readonlyAccessor : Symbol(Person["readonlyAccessor"], Decl(mod1.js, 12, 106)) +>readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) m1.thing = "no"; ->m1.thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->thing : Symbol(Person["thing"], Decl(mod1.js, 9, 2)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) m1.rwAccessors = "no"; ->m1.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) m1.setonlyAccessor = 0; ->m1.setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) >m1 : Symbol(m1, Decl(validator.ts, 4, 5)) ->setonlyAccessor : Symbol(Person["setonlyAccessor"], Decl(mod1.js, 13, 88)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) === tests/cases/conformance/jsdoc/mod1.js === @@ -110,6 +110,7 @@ Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); >Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) >Person : Symbol(Person, Decl(mod1.js, 0, 0)) >prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"thing" : Symbol(Person.thing, Decl(mod1.js, 9, 2)) >value : Symbol(value, Decl(mod1.js, 10, 50)) >writable : Symbol(writable, Decl(mod1.js, 10, 61)) @@ -120,6 +121,7 @@ Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writab >Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) >Person : Symbol(Person, Decl(mod1.js, 0, 0)) >prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"readonlyProp" : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) >value : Symbol(value, Decl(mod1.js, 11, 57)) >writable : Symbol(writable, Decl(mod1.js, 11, 73)) @@ -130,6 +132,7 @@ Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, >Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) >Person : Symbol(Person, Decl(mod1.js, 0, 0)) >prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"rwAccessors" : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) >get : Symbol(get, Decl(mod1.js, 12, 56)) >set : Symbol(set, Decl(mod1.js, 12, 80)) >_ : Symbol(_, Decl(mod1.js, 12, 85)) @@ -141,6 +144,7 @@ Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21. >Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) >Person : Symbol(Person, Decl(mod1.js, 0, 0)) >prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"readonlyAccessor" : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) >get : Symbol(get, Decl(mod1.js, 13, 61)) Object.defineProperty(Person.prototype, "setonlyAccessor", { @@ -150,6 +154,7 @@ Object.defineProperty(Person.prototype, "setonlyAccessor", { >Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) >Person : Symbol(Person, Decl(mod1.js, 0, 0)) >prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"setonlyAccessor" : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) /** @param {string} str */ set(str) { @@ -157,7 +162,7 @@ Object.defineProperty(Person.prototype, "setonlyAccessor", { >str : Symbol(str, Decl(mod1.js, 16, 8)) this.rwAccessors = Number(str) ->this.rwAccessors : Symbol(Person["rwAccessors"], Decl(mod1.js, 11, 93)) +>this.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) >this : Symbol(Person, Decl(mod1.js, 0, 0)) >rwAccessors : Symbol(rwAccessors, Decl(mod1.js, 16, 14)) >Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) diff --git a/tests/baselines/reference/checkObjectDefineProperty.symbols b/tests/baselines/reference/checkObjectDefineProperty.symbols index d3eea1a0a74..28512d018a4 100644 --- a/tests/baselines/reference/checkObjectDefineProperty.symbols +++ b/tests/baselines/reference/checkObjectDefineProperty.symbols @@ -4,69 +4,69 @@ import x = require("./"); >x : Symbol(x, Decl(validate.ts, 0, 0)) x.name; ->x.name : Symbol(x["name"], Decl(index.js, 0, 13)) +>x.name : Symbol(x.name, Decl(index.js, 0, 13)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->name : Symbol(x["name"], Decl(index.js, 0, 13)) +>name : Symbol(x.name, Decl(index.js, 0, 13)) x.middleInit; ->x.middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>x.middleInit : Symbol(x.middleInit, Decl(index.js, 1, 71)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>middleInit : Symbol(x.middleInit, Decl(index.js, 1, 71)) x.lastName; ->x.lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>x.lastName : Symbol(x.lastName, Decl(index.js, 2, 55)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>lastName : Symbol(x.lastName, Decl(index.js, 2, 55)) x.zip; ->x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x.zip : Symbol(x.zip, Decl(index.js, 3, 74)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>zip : Symbol(x.zip, Decl(index.js, 3, 74)) x.houseNumber; ->x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x.houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) x.zipStr; ->x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x.zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) x.name = "Another"; ->x.name : Symbol(x["name"], Decl(index.js, 0, 13)) +>x.name : Symbol(x.name, Decl(index.js, 0, 13)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->name : Symbol(x["name"], Decl(index.js, 0, 13)) +>name : Symbol(x.name, Decl(index.js, 0, 13)) x.zip = 98123; ->x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x.zip : Symbol(x.zip, Decl(index.js, 3, 74)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>zip : Symbol(x.zip, Decl(index.js, 3, 74)) x.zipStr = "OK"; ->x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x.zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) x.lastName = "should fail"; ->x.lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>x.lastName : Symbol(x.lastName, Decl(index.js, 2, 55)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->lastName : Symbol(x["lastName"], Decl(index.js, 2, 55)) +>lastName : Symbol(x.lastName, Decl(index.js, 2, 55)) x.houseNumber = 12; // should also fail ->x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x.houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) x.zipStr = 12; // should fail ->x.zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>x.zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->zipStr : Symbol(x["zipStr"], Decl(index.js, 5, 68)) +>zipStr : Symbol(x.zipStr, Decl(index.js, 5, 68)) x.middleInit = "R"; // should also fail ->x.middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>x.middleInit : Symbol(x.middleInit, Decl(index.js, 1, 71)) >x : Symbol(x, Decl(validate.ts, 0, 0)) ->middleInit : Symbol(x["middleInit"], Decl(index.js, 1, 71)) +>middleInit : Symbol(x.middleInit, Decl(index.js, 1, 71)) === tests/cases/conformance/jsdoc/index.js === const x = {}; @@ -77,6 +77,7 @@ Object.defineProperty(x, "name", { value: "Charles", writable: true }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"name" : Symbol(x.name, Decl(index.js, 0, 13)) >value : Symbol(value, Decl(index.js, 1, 34)) >writable : Symbol(writable, Decl(index.js, 1, 52)) @@ -85,6 +86,7 @@ Object.defineProperty(x, "middleInit", { value: "H" }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"middleInit" : Symbol(x.middleInit, Decl(index.js, 1, 71)) >value : Symbol(value, Decl(index.js, 2, 40)) Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); @@ -92,6 +94,7 @@ Object.defineProperty(x, "lastName", { value: "Smith", writable: false }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"lastName" : Symbol(x.lastName, Decl(index.js, 2, 55)) >value : Symbol(value, Decl(index.js, 3, 38)) >writable : Symbol(writable, Decl(index.js, 3, 54)) @@ -100,6 +103,7 @@ Object.defineProperty(x, "zip", { get() { return 98122 }, set(_) { /*ignore*/ } >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"zip" : Symbol(x.zip, Decl(index.js, 3, 74)) >get : Symbol(get, Decl(index.js, 4, 33)) >set : Symbol(set, Decl(index.js, 4, 57)) >_ : Symbol(_, Decl(index.js, 4, 62)) @@ -109,6 +113,7 @@ Object.defineProperty(x, "houseNumber", { get() { return 21.75 } }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"houseNumber" : Symbol(x.houseNumber, Decl(index.js, 4, 83)) >get : Symbol(get, Decl(index.js, 5, 41)) Object.defineProperty(x, "zipStr", { @@ -116,6 +121,7 @@ Object.defineProperty(x, "zipStr", { >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) +>"zipStr" : Symbol(x.zipStr, Decl(index.js, 5, 68)) /** @param {string} str */ set(str) { @@ -148,18 +154,18 @@ takeName(x); */ var a = x.zip; >a : Symbol(a, Decl(index.js, 22, 3)) ->x.zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>x.zip : Symbol(x.zip, Decl(index.js, 3, 74)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) ->zip : Symbol(x["zip"], Decl(index.js, 3, 74)) +>zip : Symbol(x.zip, Decl(index.js, 3, 74)) /** * @type {number} */ var b = x.houseNumber; >b : Symbol(b, Decl(index.js, 27, 3)) ->x.houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>x.houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) >x : Symbol(x, Decl(index.js, 0, 5), Decl(index.js, 1, 22)) ->houseNumber : Symbol(x["houseNumber"], Decl(index.js, 4, 83)) +>houseNumber : Symbol(x.houseNumber, Decl(index.js, 4, 83)) const returnExemplar = () => x; >returnExemplar : Symbol(returnExemplar, Decl(index.js, 29, 5)) diff --git a/tests/baselines/reference/checkOtherObjectAssignProperty.symbols b/tests/baselines/reference/checkOtherObjectAssignProperty.symbols index efc0a463156..f72bf16a3b0 100644 --- a/tests/baselines/reference/checkOtherObjectAssignProperty.symbols +++ b/tests/baselines/reference/checkOtherObjectAssignProperty.symbols @@ -5,9 +5,9 @@ const mod = require("./mod1"); >"./mod1" : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) mod.thing; ->mod.thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>mod.thing : Symbol(thing, Decl(mod1.js, 0, 42)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>thing : Symbol(thing, Decl(mod1.js, 0, 42)) mod.other; >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) @@ -16,25 +16,25 @@ mod.prop; >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) mod.bad1; ->mod.bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>mod.bad1 : Symbol(bad1, Decl(mod1.js, 10, 72)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>bad1 : Symbol(bad1, Decl(mod1.js, 10, 72)) mod.bad2; ->mod.bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>mod.bad2 : Symbol(bad2, Decl(mod1.js, 13, 44)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>bad2 : Symbol(bad2, Decl(mod1.js, 13, 44)) mod.bad3; ->mod.bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>mod.bad3 : Symbol(bad3, Decl(mod1.js, 14, 77)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>bad3 : Symbol(bad3, Decl(mod1.js, 14, 77)) mod.thing = 0; ->mod.thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>mod.thing : Symbol(thing, Decl(mod1.js, 0, 42)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->thing : Symbol("thing", Decl(mod1.js, 0, 42)) +>thing : Symbol(thing, Decl(mod1.js, 0, 42)) mod.other = 0; >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) @@ -43,19 +43,19 @@ mod.prop = 0; >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) mod.bad1 = 0; ->mod.bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>mod.bad1 : Symbol(bad1, Decl(mod1.js, 10, 72)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad1 : Symbol("bad1", Decl(mod1.js, 10, 72)) +>bad1 : Symbol(bad1, Decl(mod1.js, 10, 72)) mod.bad2 = 0; ->mod.bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>mod.bad2 : Symbol(bad2, Decl(mod1.js, 13, 44)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad2 : Symbol("bad2", Decl(mod1.js, 13, 44)) +>bad2 : Symbol(bad2, Decl(mod1.js, 13, 44)) mod.bad3 = 0; ->mod.bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>mod.bad3 : Symbol(bad3, Decl(mod1.js, 14, 77)) >mod : Symbol(mod, Decl(importer.js, 0, 5), Decl(importer.js, 6, 9)) ->bad3 : Symbol("bad3", Decl(mod1.js, 14, 77)) +>bad3 : Symbol(bad3, Decl(mod1.js, 14, 77)) === tests/cases/conformance/jsdoc/mod1.js === const obj = { value: 42, writable: true }; @@ -68,6 +68,7 @@ Object.defineProperty(exports, "thing", obj); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"thing" : Symbol(thing, Decl(mod1.js, 0, 42)) >obj : Symbol(obj, Decl(mod1.js, 0, 5)) /** @@ -103,12 +104,14 @@ Object.defineProperty(exports, "bad1", { }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"bad1" : Symbol(bad1, Decl(mod1.js, 10, 72)) Object.defineProperty(exports, "bad2", { get() { return 12 }, value: "no" }); >Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"bad2" : Symbol(bad2, Decl(mod1.js, 13, 44)) >get : Symbol(get, Decl(mod1.js, 14, 40)) >value : Symbol(value, Decl(mod1.js, 14, 61)) @@ -117,5 +120,6 @@ Object.defineProperty(exports, "bad3", { writable: true }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"bad3" : Symbol(bad3, Decl(mod1.js, 14, 77)) >writable : Symbol(writable, Decl(mod1.js, 15, 40)) diff --git a/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols index 5b0883f227a..9d6f464619f 100644 --- a/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols +++ b/tests/baselines/reference/ensureNoCrashExportAssignmentDefineProperrtyPotentialMerge.symbols @@ -14,6 +14,7 @@ Object.defineProperty(module, "exports", { value: "oh no" }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >module : Symbol(module, Decl(index.js, 0, 38), Decl(index.js, 2, 22)) +>"exports" : Symbol(module.exports, Decl(index.js, 1, 20)) >value : Symbol(value, Decl(index.js, 2, 42)) === tests/cases/compiler/namespacey.js === @@ -48,6 +49,7 @@ Object.defineProperty(B, "NS", { value: "why though", writable: true }); >Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) >B : Symbol(B, Decl(namespacer.js, 0, 5), Decl(namespacer.js, 0, 12)) +>"NS" : Symbol(B.NS, Decl(namespacer.js, 0, 12), Decl(namespacer.js, 1, 31)) >value : Symbol(value, Decl(namespacer.js, 2, 32)) >writable : Symbol(writable, Decl(namespacer.js, 2, 53)) diff --git a/tests/baselines/reference/jsExpandoObjectDefineProperty.symbols b/tests/baselines/reference/jsExpandoObjectDefineProperty.symbols new file mode 100644 index 00000000000..03a603921bc --- /dev/null +++ b/tests/baselines/reference/jsExpandoObjectDefineProperty.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/index.js === +var chrome = {} +>chrome : Symbol(chrome, Decl(index.js, 0, 3), Decl(index.js, 1, 22), Decl(index.js, 1, 74)) + +Object.defineProperty(chrome, 'devtools', { value: {}, enumerable: true }) +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>chrome : Symbol(chrome, Decl(index.js, 0, 3), Decl(index.js, 1, 22), Decl(index.js, 1, 74)) +>'devtools' : Symbol(chrome.devtools, Decl(index.js, 0, 15), Decl(index.js, 2, 7)) +>value : Symbol(value, Decl(index.js, 1, 43)) +>enumerable : Symbol(enumerable, Decl(index.js, 1, 54)) + +chrome.devtools.inspectedWindow = {} +>chrome.devtools.inspectedWindow : Symbol(chrome.devtools.inspectedWindow, Decl(index.js, 1, 74)) +>chrome.devtools : Symbol(chrome.devtools, Decl(index.js, 0, 15), Decl(index.js, 2, 7)) +>chrome : Symbol(chrome, Decl(index.js, 0, 3), Decl(index.js, 1, 22), Decl(index.js, 1, 74)) +>devtools : Symbol(chrome.devtools, Decl(index.js, 0, 15), Decl(index.js, 2, 7)) +>inspectedWindow : Symbol(chrome.devtools.inspectedWindow, Decl(index.js, 1, 74)) + diff --git a/tests/baselines/reference/jsExpandoObjectDefineProperty.types b/tests/baselines/reference/jsExpandoObjectDefineProperty.types new file mode 100644 index 00000000000..3eb9a456220 --- /dev/null +++ b/tests/baselines/reference/jsExpandoObjectDefineProperty.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/index.js === +var chrome = {} +>chrome : typeof chrome +>{} : {} + +Object.defineProperty(chrome, 'devtools', { value: {}, enumerable: true }) +>Object.defineProperty(chrome, 'devtools', { value: {}, enumerable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>chrome : typeof chrome +>'devtools' : "devtools" +>{ value: {}, enumerable: true } : { value: {}; enumerable: true; } +>value : {} +>{} : {} +>enumerable : true +>true : true + +chrome.devtools.inspectedWindow = {} +>chrome.devtools.inspectedWindow = {} : {} +>chrome.devtools.inspectedWindow : {} +>chrome.devtools : typeof chrome.devtools +>chrome : typeof chrome +>devtools : typeof chrome.devtools +>inspectedWindow : {} +>{} : {} + diff --git a/tests/cases/compiler/jsExpandoObjectDefineProperty.ts b/tests/cases/compiler/jsExpandoObjectDefineProperty.ts new file mode 100644 index 00000000000..f968e978da5 --- /dev/null +++ b/tests/cases/compiler/jsExpandoObjectDefineProperty.ts @@ -0,0 +1,7 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @filename: index.js +var chrome = {} +Object.defineProperty(chrome, 'devtools', { value: {}, enumerable: true }) +chrome.devtools.inspectedWindow = {} \ No newline at end of file diff --git a/tests/cases/fourslash/jsObjectDefinePropertyRenameLocations.ts b/tests/cases/fourslash/jsObjectDefinePropertyRenameLocations.ts new file mode 100644 index 00000000000..bbaf2c66715 --- /dev/null +++ b/tests/cases/fourslash/jsObjectDefinePropertyRenameLocations.ts @@ -0,0 +1,17 @@ +/// +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: index.js +////var CircularList = (function () { +//// var CircularList = function() {}; +//// Object.defineProperty(CircularList.prototype, "[|maxLength|]", { value: 0, writable: true }); +//// CircularList.prototype.push = function (value) { +//// // ... +//// this.[|maxLength|] + this.[|maxLength|] +//// } +//// return CircularList; +////})() + +verify.rangesWithSameTextAreRenameLocations(); \ No newline at end of file From 3c5f1a6819943240fac8899ee00badf3909ec643 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 23 Oct 2018 12:51:59 -0700 Subject: [PATCH 105/262] Update user baselines (#28076) --- tests/baselines/reference/user/uglify-js.log | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 5bd01b81213..56c7d551683 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -14,7 +14,7 @@ node_modules/uglify-js/lib/compress.js(817,18): error TS2554: Expected 0 argumen node_modules/uglify-js/lib/compress.js(1072,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. node_modules/uglify-js/lib/compress.js(1086,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'true | ((node: any) => any)' has no compatible call signatures. node_modules/uglify-js/lib/compress.js(1150,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1192,112): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(1192,112): error TS2454: Variable 'args' is used before being assigned. node_modules/uglify-js/lib/compress.js(1193,29): error TS2532: Object is possibly 'undefined'. node_modules/uglify-js/lib/compress.js(1202,87): error TS2322: Type 'false' is not assignable to type 'number'. node_modules/uglify-js/lib/compress.js(1210,29): error TS2322: Type 'false' is not assignable to type 'never'. From 996fb78445a9ec2a97c0fd6e850268f8a28180c0 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 23 Oct 2018 15:24:56 -0700 Subject: [PATCH 106/262] Test update of DOM. (#28050) Based on the few changes that have been accepted since Mohamed left. --- src/lib/dom.generated.d.ts | 42 ++++++++++++++++++-------------- src/lib/webworker.generated.d.ts | 31 ++++++++++++++++++++--- 2 files changed, 52 insertions(+), 21 deletions(-) diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 2746b0466d9..c3edaa329d0 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -142,6 +142,7 @@ interface BiquadFilterOptions extends AudioNodeOptions { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -200,11 +201,12 @@ interface ComputedEffectTiming extends EffectTiming { progress?: number | null; } -interface ComputedKeyframe extends Record { - composite?: CompositeOperation | null; - computedOffset?: number; - easing?: string; - offset?: number | null; +interface ComputedKeyframe { + composite: CompositeOperationOrAuto; + computedOffset: number; + easing: string; + offset: number | null; + [property: string]: string | number | null | undefined; } interface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation { @@ -566,10 +568,11 @@ interface KeyboardEventInit extends EventModifierInit { repeat?: boolean; } -interface Keyframe extends Record { - composite?: CompositeOperation | null; +interface Keyframe { + composite?: CompositeOperationOrAuto; easing?: string; offset?: number | null; + [property: string]: string | number | null | undefined; } interface KeyframeAnimationOptions extends KeyframeEffectOptions { @@ -921,10 +924,11 @@ interface PromiseRejectionEventInit extends EventInit { reason?: any; } -interface PropertyIndexedKeyframes extends Record { - composite?: CompositeOperation | (CompositeOperation | null)[]; +interface PropertyIndexedKeyframes { + composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; easing?: string | string[]; offset?: number | (number | null)[]; + [property: string]: string | string[] | number | null | (number | null)[] | undefined; } interface PushSubscriptionJSON { @@ -3984,7 +3988,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Gets a reference to the root node of the document. */ - readonly documentElement: HTMLElement | null; + readonly documentElement: HTMLElement; /** * Returns document's URL. */ @@ -4016,7 +4020,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Returns the head element. */ - readonly head: HTMLHeadElement | null; + readonly head: HTMLHeadElement; readonly hidden: boolean; /** * Retrieves a collection, in source order, of img objects in the document. @@ -4046,7 +4050,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par /** * Contains information about the current URL. */ - location: Location | null; + location: Location; onfullscreenchange: ((this: Document, ev: Event) => any) | null; onfullscreenerror: ((this: Document, ev: Event) => any) | null; /** @@ -4329,7 +4333,7 @@ interface Document extends Node, NonElementParentNode, DocumentOrShadowRoot, Par */ elementFromPoint(x: number, y: number): Element | null; elementsFromPoint(x: number, y: number): Element[]; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; /** * Executes a command on the current document, current selection, or the given range. * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script. @@ -5013,7 +5017,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -7135,7 +7139,7 @@ interface HTMLMediaElement extends HTMLElement { */ readonly seekable: TimeRanges; /** - * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource. + * Gets a flag that indicates whether the client is currently moving to a new playback position in the media resource. */ readonly seeking: boolean; /** @@ -11799,7 +11803,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -16752,7 +16756,7 @@ declare var XMLSerializer: { interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver?: Node): XPathNSResolver; - evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; + evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | ((prefix: string) => string | null) | null, type: number, result: XPathResult | null): XPathResult; } declare var XPathEvaluator: { @@ -16770,7 +16774,7 @@ declare var XPathExpression: { }; interface XPathNSResolver { - lookupNamespaceURI(prefix: string): string; + lookupNamespaceURI(prefix: string): string | null; } declare var XPathNSResolver: { @@ -17648,11 +17652,13 @@ type ChannelCountMode = "max" | "clamped-max" | "explicit"; type ChannelInterpretation = "speakers" | "discrete"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; type CompositeOperation = "replace" | "add" | "accumulate"; +type CompositeOperationOrAuto = "replace" | "add" | "accumulate" | "auto"; type DirectionSetting = "" | "rl" | "lr"; type DisplayCaptureSurfaceType = "monitor" | "window" | "application" | "browser"; type DistanceModelType = "linear" | "inverse" | "exponential"; type DocumentReadyState = "loading" | "interactive" | "complete"; type EndOfStreamError = "network" | "decode"; +type EndingType = "transparent" | "native"; type FillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type GamepadHand = "" | "left" | "right"; type GamepadHapticActuatorType = "vibration"; diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 16e5d85d20b..553f6fa14b2 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -39,6 +39,7 @@ interface Algorithm { } interface BlobPropertyBag { + endings?: EndingType; type?: string; } @@ -1197,7 +1198,7 @@ interface FileReader extends EventTarget { readAsArrayBuffer(blob: Blob): void; readAsBinaryString(blob: Blob): void; readAsDataURL(blob: Blob): void; - readAsText(blob: Blob, label?: string): void; + readAsText(blob: Blob, encoding?: string): void; readonly DONE: number; readonly EMPTY: number; readonly LOADING: number; @@ -1219,7 +1220,7 @@ interface FileReaderSync { readAsArrayBuffer(blob: Blob): ArrayBuffer; readAsBinaryString(blob: Blob): string; readAsDataURL(blob: Blob): string; - readAsText(blob: Blob, label?: string): string; + readAsText(blob: Blob, encoding?: string): string; } declare var FileReaderSync: { @@ -2202,7 +2203,7 @@ declare var ReadableStreamReader: { interface Request extends Body { /** * Returns the cache mode associated with request, which is a string indicating - * how the the request will interact with the browser's cache when fetching. + * how the request will interact with the browser's cache when fetching. */ readonly cache: RequestCache; /** @@ -2524,6 +2525,29 @@ declare var TextEncoder: { new(): TextEncoder; }; +interface TextMetrics { + readonly actualBoundingBoxAscent: number; + readonly actualBoundingBoxDescent: number; + readonly actualBoundingBoxLeft: number; + readonly actualBoundingBoxRight: number; + readonly alphabeticBaseline: number; + readonly emHeightAscent: number; + readonly emHeightDescent: number; + readonly fontBoundingBoxAscent: number; + readonly fontBoundingBoxDescent: number; + readonly hangingBaseline: number; + /** + * Returns the measurement described below. + */ + readonly ideographicBaseline: number; + readonly width: number; +} + +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +}; + interface URL { hash: string; host: string; @@ -2967,6 +2991,7 @@ type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey; type Transferable = ArrayBuffer | MessagePort | ImageBitmap; type BinaryType = "blob" | "arraybuffer"; type ClientTypes = "window" | "worker" | "sharedworker" | "all"; +type EndingType = "transparent" | "native"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "pending" | "done"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; From eadf44d073ec8f58a006eb7a663bdca3be047a6a Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 23 Oct 2018 16:10:26 -0700 Subject: [PATCH 107/262] Add generateTypesForModule to public API (#28069) * Add generateTypesForModule to public API * Avoid parameter initializer and update baselines --- src/harness/fourslash.ts | 31 ++----- src/server/editorServices.ts | 2 +- src/server/scriptInfo.ts | 2 +- src/server/utilities.ts | 24 ------ src/services/codefixes/generateTypes.ts | 25 ++++-- src/services/textChanges.ts | 2 +- src/services/types.ts | 82 ++++++++++--------- .../unittests/tsserverProjectSystem.ts | 11 +-- .../reference/api/tsserverlibrary.d.ts | 40 +++++---- tests/baselines/reference/api/typescript.d.ts | 39 +++++---- .../reference/generateTypes/global.d.ts | 2 +- .../reference/generateTypes/lodash.d.ts | 2 +- tests/cases/fourslash/fourslash.ts | 1 + tests/cases/fourslash/generateTypes.ts | 70 +++++++++++++--- .../cases/fourslash/generateTypes_classes.ts | 15 ++-- tests/cases/fourslash/moveToNewFile.ts | 3 +- .../moveToNewFile_bindingPatterns.ts | 3 +- .../moveToNewFile_declarationKinds.ts | 3 +- .../fourslash/moveToNewFile_defaultExport.ts | 3 +- .../fourslash/moveToNewFile_defaultImport.ts | 3 +- .../fourslash/moveToNewFile_exportImport.ts | 3 +- tests/cases/fourslash/moveToNewFile_format.ts | 3 +- tests/cases/fourslash/moveToNewFile_getter.ts | 3 +- tests/cases/fourslash/moveToNewFile_global.ts | 3 +- .../fourslash/moveToNewFile_importEquals.ts | 3 +- .../moveToNewFile_inferQuoteStyle.ts | 3 +- tests/cases/fourslash/moveToNewFile_js.ts | 3 +- tests/cases/fourslash/moveToNewFile_jsx.ts | 3 +- .../fourslash/moveToNewFile_moveImport.ts | 3 +- .../cases/fourslash/moveToNewFile_multiple.ts | 3 +- .../moveToNewFile_namespaceImport.ts | 3 +- .../moveToNewFile_newModuleNameUnique.ts | 3 +- .../fourslash/moveToNewFile_onlyStatements.ts | 3 +- .../fourslash/moveToNewFile_rangeSemiValid.ts | 3 +- .../moveToNewFile_selectionOnName.ts | 3 +- .../cases/fourslash/moveToNewFile_tsconfig.ts | 3 +- .../fourslash/moveToNewFile_updateUses.ts | 3 +- .../fourslash/moveToNewFile_updateUses_js.ts | 3 +- ...le_variableDeclarationWithNoInitializer.ts | 3 +- 39 files changed, 236 insertions(+), 184 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 844f7b26598..c297d25e207 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -329,29 +329,7 @@ namespace FourSlash { }); } - this.formatCodeSettings = { - baseIndentSize: 0, - indentSize: 4, - tabSize: 4, - newLineCharacter: "\n", - convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterConstructor: false, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceAfterTypeAssertion: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - insertSpaceBeforeTypeAnnotation: false - }; + this.formatCodeSettings = ts.testFormatSettings; // Open the first file by default this.openFile(0); @@ -3389,8 +3367,8 @@ Actual: ${stringify(fullActual)}`); } public generateTypes(examples: ReadonlyArray): void { - for (const { name = "example", value, output, outputBaseline } of examples) { - const actual = ts.generateTypesForModule(name, value, this.formatCodeSettings); + for (const { name = "example", value, global, output, outputBaseline } of examples) { + const actual = (global ? ts.generateTypesForGlobal : ts.generateTypesForModule)(name, value, this.formatCodeSettings); if (outputBaseline) { if (actual === undefined) throw ts.Debug.fail(); Harness.Baseline.runBaseline(ts.combinePaths("generateTypes", outputBaseline + ts.Extension.Dts), actual); @@ -4536,6 +4514,7 @@ namespace FourSlashInterface { export interface GenerateTypesOptions { readonly name?: string; readonly value: unknown; + readonly global?: boolean; // Exactly one of these should be set: readonly output?: string; readonly outputBaseline?: string; @@ -4689,7 +4668,7 @@ namespace FourSlashInterface { } public setOption(name: keyof ts.FormatCodeSettings, value: number | string | boolean): void { - this.state.formatCodeSettings[name] = value; + this.state.formatCodeSettings = { ...this.state.formatCodeSettings, [name]: value }; } } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 34d32eb2cc0..1a7e668b25e 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -561,7 +561,7 @@ namespace ts.server { this.typingsCache = new TypingsCache(this.typingsInstaller); this.hostConfiguration = { - formatCodeOptions: getDefaultFormatCodeSettings(this.host), + formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine), preferences: emptyOptions, hostInfo: "Unknown host", extraFileExtensions: [] diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 5434e76072c..ea029f3d9d0 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -438,7 +438,7 @@ namespace ts.server { setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void { if (formatSettings) { if (!this.formatSettings) { - this.formatSettings = getDefaultFormatCodeSettings(this.host); + this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine); assign(this.formatSettings, formatSettings); } else { diff --git a/src/server/utilities.ts b/src/server/utilities.ts index d6cfe269c8d..6dcfff6f7e2 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -56,30 +56,6 @@ namespace ts.server { } } - export function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings { - return { - indentSize: 4, - tabSize: 4, - newLineCharacter: host.newLine || "\n", - convertTabsToSpaces: true, - indentStyle: IndentStyle.Smart, - insertSpaceAfterConstructor: false, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceBeforeFunctionParenthesis: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - }; - } - export type NormalizedPath = string & { __normalizedPathTag: any }; export function toNormalizedPath(fileName: string): NormalizedPath { diff --git a/src/services/codefixes/generateTypes.ts b/src/services/codefixes/generateTypes.ts index 6af72da562d..14807ff45b1 100644 --- a/src/services/codefixes/generateTypes.ts +++ b/src/services/codefixes/generateTypes.ts @@ -1,14 +1,22 @@ -/* @internal */ namespace ts { export function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string { - return valueInfoToDeclarationFileText(inspectValue(name, moduleValue), formatSettings); + return generateTypesForModuleOrGlobal(name, moduleValue, formatSettings, OutputKind.ExportEquals); } - export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings): string { - return textChanges.getNewFileText(toStatements(valueInfo, OutputKind.ExportEquals), ScriptKind.TS, "\n", formatting.getFormatContext(formatSettings)); + export function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string { + return generateTypesForModuleOrGlobal(name, globalValue, formatSettings, OutputKind.Global); } - const enum OutputKind { ExportEquals, NamedExport, NamespaceMember } + function generateTypesForModuleOrGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global): string { + return valueInfoToDeclarationFileText(inspectValue(name, globalValue), formatSettings, outputKind); + } + + /* @internal */ + export function valueInfoToDeclarationFileText(valueInfo: ValueInfo, formatSettings: FormatCodeSettings, outputKind: OutputKind.ExportEquals | OutputKind.Global = OutputKind.ExportEquals): string { + return textChanges.getNewFileText(toStatements(valueInfo, outputKind), ScriptKind.TS, formatSettings.newLineCharacter || "\n", formatting.getFormatContext(formatSettings)); + } + + const enum OutputKind { ExportEquals, NamedExport, NamespaceMember, Global } function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray { return toStatements(info, OutputKind.NamespaceMember); } @@ -18,7 +26,7 @@ namespace ts { if (!isValidIdentifier(name) || isDefault && kind !== OutputKind.NamedExport) return emptyArray; const modifiers = isDefault && info.kind === ValueKind.FunctionOrClass ? [createModifier(SyntaxKind.ExportKeyword), createModifier(SyntaxKind.DefaultKeyword)] - : kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] + : kind === OutputKind.Global || kind === OutputKind.ExportEquals ? [createModifier(SyntaxKind.DeclareKeyword)] : kind === OutputKind.NamedExport ? [createModifier(SyntaxKind.ExportKeyword)] : undefined; const exportEquals = () => kind === OutputKind.ExportEquals ? [exportEqualsOrDefault(info.name, /*isExportEquals*/ true)] : emptyArray; @@ -132,11 +140,14 @@ namespace ts { case ValueKind.FunctionOrClass: return createTypeReferenceNode("Function", /*typeArguments*/ undefined); // Normally we create a FunctionDeclaration, but this can happen for a function in an array. case ValueKind.Object: - return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, m.name, /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); + return createTypeLiteralNode(info.members.map(m => createPropertySignature(/*modifiers*/ undefined, toPropertyName(m.name), /*questionToken*/ undefined, toType(m), /*initializer*/ undefined))); default: return Debug.assertNever(info); } } + function toPropertyName(name: string): Identifier | StringLiteral { + return isIdentifierText(name, ScriptTarget.ESNext) ? createIdentifier(name) : createStringLiteral(name); + } // Parses assignments to "this.x" in the constructor into class property declarations function getConstructorFunctionInstanceProperties(fnAst: FunctionOrConstructorNode): ReadonlyArray { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index b9a13fc5420..ab12e097f7a 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -816,7 +816,7 @@ namespace ts.textChanges { const nonFormattedText = statements.map(s => getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); const sourceFile = createSourceFile("any file name", nonFormattedText, ScriptTarget.ESNext, /*setParentNodes*/ true, scriptKind); const changes = formatting.formatDocument(sourceFile, formatContext); - return applyChanges(nonFormattedText, changes); + return applyChanges(nonFormattedText, changes) + newLineCharacter; } function computeNewText(change: Change, sourceFile: SourceFile, newLineCharacter: string, formatContext: formatting.FormatContext, validate: ValidateNonFormattedText | undefined): string { diff --git a/src/services/types.ts b/src/services/types.ts index 72ded445dba..21ce83070df 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -712,49 +712,51 @@ namespace ts { } export interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + } + + export function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: newLineCharacter || "\n", + convertTabsToSpaces: true, + indentStyle: IndentStyle.Smart, + insertSpaceAfterConstructor: false, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + insertSpaceBeforeFunctionParenthesis: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false, + }; } /* @internal */ - export const testFormatSettings: FormatCodeSettings = { - baseIndentSize: 0, - indentSize: 4, - tabSize: 4, - newLineCharacter: "\n", - convertTabsToSpaces: true, - indentStyle: IndentStyle.Smart, - insertSpaceAfterCommaDelimiter: true, - insertSpaceAfterSemicolonInForStatements: true, - insertSpaceBeforeAndAfterBinaryOperators: true, - insertSpaceAfterConstructor: false, - insertSpaceAfterKeywordsInControlFlowStatements: true, - insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - insertSpaceAfterTypeAssertion: false, - placeOpenBraceOnNewLineForFunctions: false, - placeOpenBraceOnNewLineForControlBlocks: false, - insertSpaceBeforeTypeAnnotation: false - }; + export const testFormatSettings = getDefaultFormatCodeSettings("\n"); export interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9d00047c1ce..38d2d4867a0 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -4497,8 +4497,7 @@ namespace ts.projectSystem { const defaultSettings = projectService.getFormatCodeOptions(f1.path as server.NormalizedPath); // set global settings - const newGlobalSettings1 = clone(defaultSettings); - newGlobalSettings1.placeOpenBraceOnNewLineForControlBlocks = !newGlobalSettings1.placeOpenBraceOnNewLineForControlBlocks; + const newGlobalSettings1 = { ...defaultSettings, placeOpenBraceOnNewLineForControlBlocks: !defaultSettings.placeOpenBraceOnNewLineForControlBlocks }; projectService.setHostConfiguration({ formatOptions: newGlobalSettings1 }); // get format options for file - should be equal to new global settings @@ -4506,8 +4505,7 @@ namespace ts.projectSystem { assert.deepEqual(s1, newGlobalSettings1, "file settings should be the same with global settings"); // set per file format options - const newPerFileSettings = clone(defaultSettings); - newPerFileSettings.insertSpaceAfterCommaDelimiter = !newPerFileSettings.insertSpaceAfterCommaDelimiter; + const newPerFileSettings = { ...defaultSettings, insertSpaceAfterCommaDelimiter: !defaultSettings.insertSpaceAfterCommaDelimiter }; projectService.setHostConfiguration({ formatOptions: newPerFileSettings, file: f1.path }); // get format options for file - should be equal to new per-file settings @@ -4515,8 +4513,7 @@ namespace ts.projectSystem { assert.deepEqual(s2, newPerFileSettings, "file settings should be the same with per-file settings"); // set new global settings - they should not affect ones that were set per-file - const newGlobalSettings2 = clone(defaultSettings); - newGlobalSettings2.insertSpaceAfterSemicolonInForStatements = !newGlobalSettings2.insertSpaceAfterSemicolonInForStatements; + const newGlobalSettings2 = { ...defaultSettings, insertSpaceAfterSemicolonInForStatements: !defaultSettings.insertSpaceAfterSemicolonInForStatements }; projectService.setHostConfiguration({ formatOptions: newGlobalSettings2 }); // get format options for file - should be equal to new per-file settings @@ -6837,7 +6834,7 @@ namespace ts.projectSystem { { start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, - newText: "export const a = 0;", + newText: "export const a = 0;\n", }, ], } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 5921a644444..9356951e1ee 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -5042,24 +5042,25 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -5508,6 +5509,10 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; @@ -5597,7 +5602,6 @@ declare namespace ts.server { function ThrowProjectLanguageServiceDisabled(): never; function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; } - function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; type NormalizedPath = string & { __normalizedPathTag: any; }; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 573d470fde5..66e30ee2a49 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -5042,24 +5042,25 @@ declare namespace ts { insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter?: boolean; - insertSpaceAfterSemicolonInForStatements?: boolean; - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - insertSpaceAfterConstructor?: boolean; - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - insertSpaceAfterTypeAssertion?: boolean; - insertSpaceBeforeFunctionParenthesis?: boolean; - placeOpenBraceOnNewLineForFunctions?: boolean; - placeOpenBraceOnNewLineForControlBlocks?: boolean; - insertSpaceBeforeTypeAnnotation?: boolean; - indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; + readonly insertSpaceAfterCommaDelimiter?: boolean; + readonly insertSpaceAfterSemicolonInForStatements?: boolean; + readonly insertSpaceBeforeAndAfterBinaryOperators?: boolean; + readonly insertSpaceAfterConstructor?: boolean; + readonly insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + readonly insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + readonly insertSpaceAfterTypeAssertion?: boolean; + readonly insertSpaceBeforeFunctionParenthesis?: boolean; + readonly placeOpenBraceOnNewLineForFunctions?: boolean; + readonly placeOpenBraceOnNewLineForControlBlocks?: boolean; + readonly insertSpaceBeforeTypeAnnotation?: boolean; + readonly indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } + function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; @@ -5508,6 +5509,10 @@ declare namespace ts { function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; } +declare namespace ts { + function generateTypesForModule(name: string, moduleValue: unknown, formatSettings: FormatCodeSettings): string; + function generateTypesForGlobal(name: string, globalValue: unknown, formatSettings: FormatCodeSettings): string; +} declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.8"; diff --git a/tests/baselines/reference/generateTypes/global.d.ts b/tests/baselines/reference/generateTypes/global.d.ts index a49c80258ae..000e38953a2 100644 --- a/tests/baselines/reference/generateTypes/global.d.ts +++ b/tests/baselines/reference/generateTypes/global.d.ts @@ -233,4 +233,4 @@ export class Symbol { static toStringTag: symbol; static unscopables: symbol; valueOf(): any; -} \ No newline at end of file +} diff --git a/tests/baselines/reference/generateTypes/lodash.d.ts b/tests/baselines/reference/generateTypes/lodash.d.ts index 6354df710db..ff729b36320 100644 --- a/tests/baselines/reference/generateTypes/lodash.d.ts +++ b/tests/baselines/reference/generateTypes/lodash.d.ts @@ -665,4 +665,4 @@ declare namespace example { // Circular reference from example.partialRight const placeholder: any; } -} \ No newline at end of file +} diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index e58e12a9ecf..57b5af7e1b6 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -642,6 +642,7 @@ declare namespace FourSlashInterface { interface GenerateTypesOptions { readonly name?: string; readonly value: unknown; + readonly global?: boolean; readonly output?: string | undefined; readonly outputBaseline?: string; } diff --git a/tests/cases/fourslash/generateTypes.ts b/tests/cases/fourslash/generateTypes.ts index bfe521e2046..3a26e9829b2 100644 --- a/tests/cases/fourslash/generateTypes.ts +++ b/tests/cases/fourslash/generateTypes.ts @@ -3,17 +3,56 @@ ////dummy text verify.generateTypes( +{ + value: 0, + global: true, + output: "declare const example: number;\n", +}, +{ + value: { x: 0, f() {} }, + global: true, + output: +`declare namespace example { + function f(): void; + const x: number; +} +`, +}, +{ + value: { "*": 10, "default": true, "with": 10, " ": 3 }, + global: true, + output: +`declare const example: { + " ": number; + "*": number; + default: boolean; + with: number; +}; +`, +}, +{ + value: { "*": 10, f() {} }, + global: true, + output: +`declare namespace example { + function f(): void; +} +`, +}, + { value: 0, output: `export = example; -declare const example: number;`, +declare const example: number; +`, }, { value: (x, y) => x + y, output: `export = example; -declare function example(x: any, y: any): void;`, +declare function example(x: any, y: any): void; +`, }, { // non-arrow functions have different toString(), so important to test @@ -25,46 +64,53 @@ declare function example(x: any, y: any): void;`, }, output: `export = example; -declare function example(x: any, y: any): any;`, +declare function example(x: any, y: any): any; +`, }, { value: function(x) { arguments; }, output: `export = example; -declare function example(x: any, ...args: any[]): void;`, +declare function example(x: any, ...args: any[]): void; +`, }, { value: ({ default() {} }), output: -`export default function _default(): void;`, +`export default function _default(): void; +`, }, { value: ({ default: class {} }), output: `export default class _default { -}`, +} +`, }, { value: new Date(), output: `export = example; -declare const example: Date;`, +declare const example: Date; +`, }, { value: [0], output: `export = example; -declare const example: number[];`, +declare const example: number[]; +`, }, { value: [() => 0, () => ""], output: `export = example; -declare const example: Function[];`, +declare const example: Function[]; +`, }, { value: (() => { @@ -74,7 +120,8 @@ declare const example: Function[];`, })(), output: `export = example; -declare const example: any[];`, +declare const example: any[]; +`, }, { value: (() => { @@ -104,6 +151,7 @@ export namespace ns2 { function fn(x: any): void; } // Circular reference from example -export const self: any;`, +export const self: any; +`, }, ); diff --git a/tests/cases/fourslash/generateTypes_classes.ts b/tests/cases/fourslash/generateTypes_classes.ts index 94fd43fe529..e1d6479f926 100644 --- a/tests/cases/fourslash/generateTypes_classes.ts +++ b/tests/cases/fourslash/generateTypes_classes.ts @@ -8,7 +8,8 @@ verify.generateTypes( output: `export = example; declare class example { -}`, +} +`, }, { @@ -28,11 +29,13 @@ declare class example { declare class example { constructor(x: any); x: any; -}`, +} +`, }, { value: { x: 0, export: 0 }, - output: `export const x: number;`, + output: `export const x: number; +`, }, { value: (() => { @@ -87,7 +90,8 @@ declare namespace example { namespace staticMethod { const staticMethodProperty: number; } -}`, +} +`, }, { @@ -103,7 +107,8 @@ declare class example { static staticMethod(): void; x: any; method(): void; -}`, +} +`, }, ); diff --git a/tests/cases/fourslash/moveToNewFile.ts b/tests/cases/fourslash/moveToNewFile.ts index f07daa8e371..b1a7e9e6b26 100644 --- a/tests/cases/fourslash/moveToNewFile.ts +++ b/tests/cases/fourslash/moveToNewFile.ts @@ -23,7 +23,8 @@ a; y;`, "/y.ts": `import { b } from './other'; import { p } from './a'; -export const y: Date = p + b;`, +export const y: Date = p + b; +`, }, preferences: { diff --git a/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts b/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts index f004fdbdde9..128eadb471a 100644 --- a/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts +++ b/tests/cases/fourslash/moveToNewFile_bindingPatterns.ts @@ -13,7 +13,8 @@ verify.moveToNewFile({ "/a.ts": "", "/x.ts": -`export const [x, { p: y }] = [0, { p: 1 }];`, +`export const [x, { p: y }] = [0, { p: 1 }]; +`, "/b.ts": ` diff --git a/tests/cases/fourslash/moveToNewFile_declarationKinds.ts b/tests/cases/fourslash/moveToNewFile_declarationKinds.ts index 6420a9e8ce1..90c5eb6973a 100644 --- a/tests/cases/fourslash/moveToNewFile_declarationKinds.ts +++ b/tests/cases/fourslash/moveToNewFile_declarationKinds.ts @@ -33,6 +33,7 @@ export namespace N { } export type T = number; export interface I { -}`, +} +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_defaultExport.ts b/tests/cases/fourslash/moveToNewFile_defaultExport.ts index 2a7e3e47a67..3881b7163fd 100644 --- a/tests/cases/fourslash/moveToNewFile_defaultExport.ts +++ b/tests/cases/fourslash/moveToNewFile_defaultExport.ts @@ -16,7 +16,8 @@ verify.moveToNewFile({ f();`, "/f.ts": -`export default function f() { }`, +`export default function f() { } +`, "/user.ts": `import f from "./f"; diff --git a/tests/cases/fourslash/moveToNewFile_defaultImport.ts b/tests/cases/fourslash/moveToNewFile_defaultImport.ts index 031da380885..c3e7eb63aef 100644 --- a/tests/cases/fourslash/moveToNewFile_defaultImport.ts +++ b/tests/cases/fourslash/moveToNewFile_defaultImport.ts @@ -12,6 +12,7 @@ verify.moveToNewFile({ "/x.ts": `import f from "./a"; -const x = f();`, +const x = f(); +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_exportImport.ts b/tests/cases/fourslash/moveToNewFile_exportImport.ts index 657aa2f8075..49e33cf5aa3 100644 --- a/tests/cases/fourslash/moveToNewFile_exportImport.ts +++ b/tests/cases/fourslash/moveToNewFile_exportImport.ts @@ -15,6 +15,7 @@ M;`, "/O.ts": `import { N } from "./a"; -export import O = N;`, +export import O = N; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_format.ts b/tests/cases/fourslash/moveToNewFile_format.ts index 821e0ebae7e..a9712ed14d2 100644 --- a/tests/cases/fourslash/moveToNewFile_format.ts +++ b/tests/cases/fourslash/moveToNewFile_format.ts @@ -16,6 +16,7 @@ verify.moveToNewFile({ "/f.ts": `function f() { const x = 0; -}`, +} +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_getter.ts b/tests/cases/fourslash/moveToNewFile_getter.ts index d595d92cf07..f4420e860e3 100644 --- a/tests/cases/fourslash/moveToNewFile_getter.ts +++ b/tests/cases/fourslash/moveToNewFile_getter.ts @@ -23,7 +23,8 @@ verify.moveToNewFile({ "/g.ts": `import { C } from "./a"; -export const { g, h: i } = new C();`, +export const { g, h: i } = new C(); +`, "/b.ts": ` diff --git a/tests/cases/fourslash/moveToNewFile_global.ts b/tests/cases/fourslash/moveToNewFile_global.ts index 04443c50cb2..940b4df8a52 100644 --- a/tests/cases/fourslash/moveToNewFile_global.ts +++ b/tests/cases/fourslash/moveToNewFile_global.ts @@ -11,6 +11,7 @@ verify.moveToNewFile({ `, "/y.ts": -`const y = x;`, +`const y = x; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_importEquals.ts b/tests/cases/fourslash/moveToNewFile_importEquals.ts index a87c84c0004..7a339817462 100644 --- a/tests/cases/fourslash/moveToNewFile_importEquals.ts +++ b/tests/cases/fourslash/moveToNewFile_importEquals.ts @@ -13,6 +13,7 @@ verify.moveToNewFile({ j;`, "/y.ts": `import i = require("./i"); -const y = i;`, +const y = i; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_inferQuoteStyle.ts b/tests/cases/fourslash/moveToNewFile_inferQuoteStyle.ts index a891e9b717a..c26277bd6b5 100644 --- a/tests/cases/fourslash/moveToNewFile_inferQuoteStyle.ts +++ b/tests/cases/fourslash/moveToNewFile_inferQuoteStyle.ts @@ -15,6 +15,7 @@ import { x } from './x'; x;`, "/x.ts": -`export const x = 0;`, +`export const x = 0; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_js.ts b/tests/cases/fourslash/moveToNewFile_js.ts index e70bfa5f430..5e0bb712b9e 100644 --- a/tests/cases/fourslash/moveToNewFile_js.ts +++ b/tests/cases/fourslash/moveToNewFile_js.ts @@ -30,6 +30,7 @@ const { p } = require("./a"); const y = p + b; exports.y = y; const z = 0; -exports.z = 0;`, +exports.z = 0; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_jsx.ts b/tests/cases/fourslash/moveToNewFile_jsx.ts index b969794af30..bc73f25282f 100644 --- a/tests/cases/fourslash/moveToNewFile_jsx.ts +++ b/tests/cases/fourslash/moveToNewFile_jsx.ts @@ -9,6 +9,7 @@ verify.moveToNewFile({ ``, "/newFile.tsx": -`
a
;`, +`
a
; +`, } }); diff --git a/tests/cases/fourslash/moveToNewFile_moveImport.ts b/tests/cases/fourslash/moveToNewFile_moveImport.ts index d1560e03aba..3bd661020d7 100644 --- a/tests/cases/fourslash/moveToNewFile_moveImport.ts +++ b/tests/cases/fourslash/moveToNewFile_moveImport.ts @@ -14,6 +14,7 @@ b;`, "/l.ts": `import { a } from "m"; let l; -a;`, +a; +`, } }); diff --git a/tests/cases/fourslash/moveToNewFile_multiple.ts b/tests/cases/fourslash/moveToNewFile_multiple.ts index 2a235ad9d8f..847b50ce08b 100644 --- a/tests/cases/fourslash/moveToNewFile_multiple.ts +++ b/tests/cases/fourslash/moveToNewFile_multiple.ts @@ -23,6 +23,7 @@ x; y;`, export const x = 0; a; export const y = 1; -b;`, +b; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_namespaceImport.ts b/tests/cases/fourslash/moveToNewFile_namespaceImport.ts index 152d1fcaeb5..edd3ddaae13 100644 --- a/tests/cases/fourslash/moveToNewFile_namespaceImport.ts +++ b/tests/cases/fourslash/moveToNewFile_namespaceImport.ts @@ -27,7 +27,8 @@ verify.moveToNewFile({ `export const y = 0;`, "/x.ts": -`export const x = 0;`, +`export const x = 0; +`, "/b.ts": `import * as a from "./a"; diff --git a/tests/cases/fourslash/moveToNewFile_newModuleNameUnique.ts b/tests/cases/fourslash/moveToNewFile_newModuleNameUnique.ts index 58cebf993da..2a0a1c67f4e 100644 --- a/tests/cases/fourslash/moveToNewFile_newModuleNameUnique.ts +++ b/tests/cases/fourslash/moveToNewFile_newModuleNameUnique.ts @@ -15,6 +15,7 @@ verify.moveToNewFile({ ``, "/x.2.ts": -`export const x = 0;`, +`export const x = 0; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_onlyStatements.ts b/tests/cases/fourslash/moveToNewFile_onlyStatements.ts index fe019d5e9af..a46519581a6 100644 --- a/tests/cases/fourslash/moveToNewFile_onlyStatements.ts +++ b/tests/cases/fourslash/moveToNewFile_onlyStatements.ts @@ -11,6 +11,7 @@ verify.moveToNewFile({ `, "/newFile.ts": -`console.log("goodbye");`, +`console.log("goodbye"); +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_rangeSemiValid.ts b/tests/cases/fourslash/moveToNewFile_rangeSemiValid.ts index bfd4d93a7c6..a18a017ee72 100644 --- a/tests/cases/fourslash/moveToNewFile_rangeSemiValid.ts +++ b/tests/cases/fourslash/moveToNewFile_rangeSemiValid.ts @@ -13,6 +13,7 @@ verify.moveToNewFile({ const y = 0;`, "/x.ts": -`const x = 0;`, +`const x = 0; +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_selectionOnName.ts b/tests/cases/fourslash/moveToNewFile_selectionOnName.ts index 0db64279291..075dd0ebc0c 100644 --- a/tests/cases/fourslash/moveToNewFile_selectionOnName.ts +++ b/tests/cases/fourslash/moveToNewFile_selectionOnName.ts @@ -14,6 +14,7 @@ export {}; export function gee() { eff(); }`, "/eff.ts": `import { gee } from "./a"; -export function eff() { gee(); }`, +export function eff() { gee(); } +`, }, }); diff --git a/tests/cases/fourslash/moveToNewFile_tsconfig.ts b/tests/cases/fourslash/moveToNewFile_tsconfig.ts index 264f2a85ef2..a8437bace14 100644 --- a/tests/cases/fourslash/moveToNewFile_tsconfig.ts +++ b/tests/cases/fourslash/moveToNewFile_tsconfig.ts @@ -18,7 +18,8 @@ verify.moveToNewFile({ `, "/src/newFile.ts": -`1;`, +`1; +`, "/src/tsconfig.json": `{ diff --git a/tests/cases/fourslash/moveToNewFile_updateUses.ts b/tests/cases/fourslash/moveToNewFile_updateUses.ts index b1ab56cd763..7b29c07acdd 100644 --- a/tests/cases/fourslash/moveToNewFile_updateUses.ts +++ b/tests/cases/fourslash/moveToNewFile_updateUses.ts @@ -17,7 +17,8 @@ verify.moveToNewFile({ `, "/y.ts": -`export const y = 0;`, +`export const y = 0; +`, "/user.ts": `import { x } from "./a"; diff --git a/tests/cases/fourslash/moveToNewFile_updateUses_js.ts b/tests/cases/fourslash/moveToNewFile_updateUses_js.ts index 09fbf32a313..8addd342197 100644 --- a/tests/cases/fourslash/moveToNewFile_updateUses_js.ts +++ b/tests/cases/fourslash/moveToNewFile_updateUses_js.ts @@ -19,7 +19,8 @@ verify.moveToNewFile({ `, "/y.js": -`exports.y = 0;`, +`exports.y = 0; +`, "/user.js": // TODO: GH#22330 diff --git a/tests/cases/fourslash/moveToNewFile_variableDeclarationWithNoInitializer.ts b/tests/cases/fourslash/moveToNewFile_variableDeclarationWithNoInitializer.ts index ef62f9b8d0f..49d9d464130 100644 --- a/tests/cases/fourslash/moveToNewFile_variableDeclarationWithNoInitializer.ts +++ b/tests/cases/fourslash/moveToNewFile_variableDeclarationWithNoInitializer.ts @@ -14,6 +14,7 @@ export let x; "/y.ts": `import { x } from "./a"; -const y = x;`, +const y = x; +`, }, }); From ff6f94791feeb9c2b22ff1ada41c173a61f347fb Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 24 Oct 2018 11:27:39 -0700 Subject: [PATCH 108/262] Use regex+getTokenAtPosition to find dynamic import (#28104) Instead of walking the entire tree. This stack overflows for large trees. Still need to adapt a test. --- src/compiler/program.ts | 50 ++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index fa86ef147cb..9424fc98bc3 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1895,12 +1895,9 @@ namespace ts { for (const node of file.statements) { collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & NodeFlags.PossiblyContainsDynamicImport) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } } if ((file.flags & NodeFlags.PossiblyContainsDynamicImport) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(file.endOfFileToken); + collectDynamicImportOrRequireCalls(file); } file.imports = imports || emptyArray; @@ -1952,25 +1949,38 @@ namespace ts { } } - function collectDynamicImportOrRequireCalls(node: Node): void { - if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { - imports = append(imports, node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) { - imports = append(imports, node.arguments[0] as StringLiteralLike); - } - else if (isLiteralImportTypeNode(node)) { - imports = append(imports, node.argument.literal); - } - collectDynamicImportOrRequireCallsForEachChild(node); - if (hasJSDocNodes(node)) { - forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + function collectDynamicImportOrRequireCalls(file: SourceFile) { + const r = /import|require/g; + while (r.exec(file.text) !== null) { + const node = getTokenAtPosition(file, r.lastIndex); + if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) { + imports = append(imports, node.arguments[0] as StringLiteralLike); + } + else if (isLiteralImportTypeNode(node)) { + imports = append(imports, node.argument.literal); + } } } - function collectDynamicImportOrRequireCallsForEachChild(node: Node) { - forEachChild(node, collectDynamicImportOrRequireCalls); + /** Returns a token if position is in [start-of-leading-trivia, end) */ + function getTokenAtPosition(sourceFile: SourceFile, position: number): Node { + let current: Node = sourceFile; + const getContainingChild = (child: Node) => { + if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === SyntaxKind.EndOfFileToken)))) { + return child; + } + }; + while (true) { + const child = hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } } } From 0db3038b57572a76ad39f91c14d9af244f64c13f Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 24 Oct 2018 13:03:29 -0700 Subject: [PATCH 109/262] Fix tests for node 11 (#28108) 1. Sort is now stable in node 11, which exposed a lack in the sorting of nested ranges. Ranges now sort based on last ending if the start positions are the same. This means nested ranges sort the containing range first, even if a range contains another range that starts at the same position. 2. Symbol has a new member description which can't be accessed through the prototype. In addition, Array now has flat and flatMap, which I excluded to keep baselines the same between Node 6-11. --- src/harness/fourslash.ts | 2 +- tests/cases/fourslash/generateTypes_baselines.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index c297d25e207..d69df1d6cbd 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3846,7 +3846,7 @@ ${code} } // put ranges in the correct order - localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : 1); + localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1); localRanges.forEach((r) => { ranges.push(r); }); return { diff --git a/tests/cases/fourslash/generateTypes_baselines.ts b/tests/cases/fourslash/generateTypes_baselines.ts index a8363b30283..9508f83d31f 100644 --- a/tests/cases/fourslash/generateTypes_baselines.ts +++ b/tests/cases/fourslash/generateTypes_baselines.ts @@ -6,14 +6,14 @@ verify.generateTypes( // would like to test against the real "global" but that may vary between node versions. { value: { - Array: ignore(Array, ["values"]), + Array: ignore(Array, ["values", "flat", "flatMap"]), Boolean, Date, Math, Number, RegExp, String: ignore(String, ["padStart", "padEnd", "trimStart", "trimEnd"]), - Symbol: ignore(Symbol, ["asyncIterator"]), + Symbol: ignore(Symbol, ["asyncIterator", "description"]), }, outputBaseline: "global", }, From 64091950546f18209bca48edfa2e3433036c4756 Mon Sep 17 00:00:00 2001 From: Noel Yoo Date: Thu, 25 Oct 2018 05:21:58 +0900 Subject: [PATCH 110/262] Update CI (#28082) * Use 'node' instead of 'stable' * Add node 10 * Drop node 8 --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6d000dd7165..20b47dbe30c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,8 @@ language: node_js node_js: - - 'stable' - - '8' + - 'node' + - '10' - '6' sudo: false From 6fbd2a5f59c1b5428944ab188cb1b3868f6cfbb2 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 24 Oct 2018 13:51:11 -0700 Subject: [PATCH 111/262] Reset narrowing of 'x.y' only when 'x' has a narrowable type --- src/compiler/checker.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fd786799b8b..4305227dab7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14340,6 +14340,11 @@ namespace ts { return false; } + function hasNarrowableDeclaredType(expr: Node) { + const type = getDeclaredTypeOfReference(expr); + return !!(type && type.flags & TypeFlags.Union); + } + function findDiscriminantProperties(sourceProperties: Symbol[], target: Type): Symbol[] | undefined { let result: Symbol[] | undefined; for (const sourceProperty of sourceProperties) { @@ -15373,9 +15378,9 @@ namespace ts { // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands const target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a + // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { return declaredType; } return type; @@ -15516,9 +15521,9 @@ namespace ts { function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { const left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an + // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { return declaredType; } return type; From ba8310ab8d3a9fd4f0b432267e990ab18728a4d9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 24 Oct 2018 13:51:24 -0700 Subject: [PATCH 112/262] Add regression test --- .../cases/compiler/narrowingOfDottedNames.ts | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/tests/cases/compiler/narrowingOfDottedNames.ts b/tests/cases/compiler/narrowingOfDottedNames.ts index af417f0830c..4e504e4133e 100644 --- a/tests/cases/compiler/narrowingOfDottedNames.ts +++ b/tests/cases/compiler/narrowingOfDottedNames.ts @@ -1,11 +1,13 @@ +// @strict: true + // Repro from #8383 class A { - prop: { a: string; }; + prop!: { a: string; }; } class B { - prop: { b: string; } + prop!: { b: string; } } function isA(x: any): x is A { @@ -37,3 +39,21 @@ function f2(x: A | B) { } } } + +// Repro from #28100 + +class Foo1 +{ + x: number; // Error + constructor() { + if (this instanceof Boolean) { + } + } +} + +class Foo2 +{ + x: number; // Error + constructor() { + } +} From cc9f45d517cf6efdb9baa5959ec1bbff89ec874b Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 24 Oct 2018 13:51:35 -0700 Subject: [PATCH 113/262] Accept new baselines --- .../narrowingOfDottedNames.errors.txt | 67 +++++++++++++++++++ .../reference/narrowingOfDottedNames.js | 36 +++++++++- .../reference/narrowingOfDottedNames.symbols | 50 ++++++++++---- .../reference/narrowingOfDottedNames.types | 31 ++++++++- 4 files changed, 168 insertions(+), 16 deletions(-) create mode 100644 tests/baselines/reference/narrowingOfDottedNames.errors.txt diff --git a/tests/baselines/reference/narrowingOfDottedNames.errors.txt b/tests/baselines/reference/narrowingOfDottedNames.errors.txt new file mode 100644 index 00000000000..f5bf833c4e0 --- /dev/null +++ b/tests/baselines/reference/narrowingOfDottedNames.errors.txt @@ -0,0 +1,67 @@ +tests/cases/compiler/narrowingOfDottedNames.ts(45,5): error TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor. +tests/cases/compiler/narrowingOfDottedNames.ts(54,5): error TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor. + + +==== tests/cases/compiler/narrowingOfDottedNames.ts (2 errors) ==== + // Repro from #8383 + + class A { + prop!: { a: string; }; + } + + class B { + prop!: { b: string; } + } + + function isA(x: any): x is A { + return x instanceof A; + } + + function isB(x: any): x is B { + return x instanceof B; + } + + function f1(x: A | B) { + while (true) { + if (x instanceof A) { + x.prop.a; + } + else if (x instanceof B) { + x.prop.b; + } + } + } + + function f2(x: A | B) { + while (true) { + if (isA(x)) { + x.prop.a; + } + else if (isB(x)) { + x.prop.b; + } + } + } + + // Repro from #28100 + + class Foo1 + { + x: number; // Error + ~ +!!! error TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor. + constructor() { + if (this instanceof Boolean) { + } + } + } + + class Foo2 + { + x: number; // Error + ~ +!!! error TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor. + constructor() { + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/narrowingOfDottedNames.js b/tests/baselines/reference/narrowingOfDottedNames.js index 292678ce57b..5d6ef2aaaa0 100644 --- a/tests/baselines/reference/narrowingOfDottedNames.js +++ b/tests/baselines/reference/narrowingOfDottedNames.js @@ -2,11 +2,11 @@ // Repro from #8383 class A { - prop: { a: string; }; + prop!: { a: string; }; } class B { - prop: { b: string; } + prop!: { b: string; } } function isA(x: any): x is A { @@ -38,9 +38,28 @@ function f2(x: A | B) { } } } + +// Repro from #28100 + +class Foo1 +{ + x: number; // Error + constructor() { + if (this instanceof Boolean) { + } + } +} + +class Foo2 +{ + x: number; // Error + constructor() { + } +} //// [narrowingOfDottedNames.js] +"use strict"; // Repro from #8383 var A = /** @class */ (function () { function A() { @@ -78,3 +97,16 @@ function f2(x) { } } } +// Repro from #28100 +var Foo1 = /** @class */ (function () { + function Foo1() { + if (this instanceof Boolean) { + } + } + return Foo1; +}()); +var Foo2 = /** @class */ (function () { + function Foo2() { + } + return Foo2; +}()); diff --git a/tests/baselines/reference/narrowingOfDottedNames.symbols b/tests/baselines/reference/narrowingOfDottedNames.symbols index 98f75372a4e..a045c83cae4 100644 --- a/tests/baselines/reference/narrowingOfDottedNames.symbols +++ b/tests/baselines/reference/narrowingOfDottedNames.symbols @@ -4,17 +4,17 @@ class A { >A : Symbol(A, Decl(narrowingOfDottedNames.ts, 0, 0)) - prop: { a: string; }; + prop!: { a: string; }; >prop : Symbol(A.prop, Decl(narrowingOfDottedNames.ts, 2, 9)) ->a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 11)) +>a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 12)) } class B { >B : Symbol(B, Decl(narrowingOfDottedNames.ts, 4, 1)) - prop: { b: string; } + prop!: { b: string; } >prop : Symbol(B.prop, Decl(narrowingOfDottedNames.ts, 6, 9)) ->b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 11)) +>b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 12)) } function isA(x: any): x is A { @@ -51,22 +51,22 @@ function f1(x: A | B) { >A : Symbol(A, Decl(narrowingOfDottedNames.ts, 0, 0)) x.prop.a; ->x.prop.a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 11)) +>x.prop.a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 12)) >x.prop : Symbol(A.prop, Decl(narrowingOfDottedNames.ts, 2, 9)) >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 18, 12)) >prop : Symbol(A.prop, Decl(narrowingOfDottedNames.ts, 2, 9)) ->a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 11)) +>a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 12)) } else if (x instanceof B) { >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 18, 12)) >B : Symbol(B, Decl(narrowingOfDottedNames.ts, 4, 1)) x.prop.b; ->x.prop.b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 11)) +>x.prop.b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 12)) >x.prop : Symbol(B.prop, Decl(narrowingOfDottedNames.ts, 6, 9)) >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 18, 12)) >prop : Symbol(B.prop, Decl(narrowingOfDottedNames.ts, 6, 9)) ->b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 11)) +>b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 12)) } } } @@ -83,23 +83,49 @@ function f2(x: A | B) { >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 29, 12)) x.prop.a; ->x.prop.a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 11)) +>x.prop.a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 12)) >x.prop : Symbol(A.prop, Decl(narrowingOfDottedNames.ts, 2, 9)) >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 29, 12)) >prop : Symbol(A.prop, Decl(narrowingOfDottedNames.ts, 2, 9)) ->a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 11)) +>a : Symbol(a, Decl(narrowingOfDottedNames.ts, 3, 12)) } else if (isB(x)) { >isB : Symbol(isB, Decl(narrowingOfDottedNames.ts, 12, 1)) >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 29, 12)) x.prop.b; ->x.prop.b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 11)) +>x.prop.b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 12)) >x.prop : Symbol(B.prop, Decl(narrowingOfDottedNames.ts, 6, 9)) >x : Symbol(x, Decl(narrowingOfDottedNames.ts, 29, 12)) >prop : Symbol(B.prop, Decl(narrowingOfDottedNames.ts, 6, 9)) ->b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 11)) +>b : Symbol(b, Decl(narrowingOfDottedNames.ts, 7, 12)) } } } +// Repro from #28100 + +class Foo1 +>Foo1 : Symbol(Foo1, Decl(narrowingOfDottedNames.ts, 38, 1)) +{ + x: number; // Error +>x : Symbol(Foo1.x, Decl(narrowingOfDottedNames.ts, 43, 1)) + + constructor() { + if (this instanceof Boolean) { +>this : Symbol(Foo1, Decl(narrowingOfDottedNames.ts, 38, 1)) +>Boolean : Symbol(Boolean, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + } + } +} + +class Foo2 +>Foo2 : Symbol(Foo2, Decl(narrowingOfDottedNames.ts, 49, 1)) +{ + x: number; // Error +>x : Symbol(Foo2.x, Decl(narrowingOfDottedNames.ts, 52, 1)) + + constructor() { + } +} + diff --git a/tests/baselines/reference/narrowingOfDottedNames.types b/tests/baselines/reference/narrowingOfDottedNames.types index f64bc4e663d..5638a349fd9 100644 --- a/tests/baselines/reference/narrowingOfDottedNames.types +++ b/tests/baselines/reference/narrowingOfDottedNames.types @@ -4,7 +4,7 @@ class A { >A : A - prop: { a: string; }; + prop!: { a: string; }; >prop : { a: string; } >a : string } @@ -12,7 +12,7 @@ class A { class B { >B : B - prop: { b: string; } + prop!: { b: string; } >prop : { b: string; } >b : string } @@ -105,3 +105,30 @@ function f2(x: A | B) { } } +// Repro from #28100 + +class Foo1 +>Foo1 : Foo1 +{ + x: number; // Error +>x : number + + constructor() { + if (this instanceof Boolean) { +>this instanceof Boolean : boolean +>this : this +>Boolean : BooleanConstructor + } + } +} + +class Foo2 +>Foo2 : Foo2 +{ + x: number; // Error +>x : number + + constructor() { + } +} + From 854f20e90f2631278a6af9afd1058d3eb800bbc8 Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 24 Oct 2018 15:34:15 -0700 Subject: [PATCH 114/262] Remove 'verify.fileAfterCodeFix', use 'verify.codeFix' (#28110) --- src/harness/fourslash.ts | 61 ++++++------------- .../codeFixInferFromUsageMemberJS.ts | 10 +-- ...deFixInferFromUsageMultipleParametersJS.ts | 9 ++- ...FixInferFromUsageNumberIndexSignatureJS.ts | 8 ++- .../codeFixInferFromUsageOptionalParamJS.ts | 10 ++- ...FixInferFromUsagePartialParameterListJS.ts | 12 ++-- .../codeFixInferFromUsagePropertyAccessJS.ts | 8 ++- .../codeFixInferFromUsageRestParam2JS.ts | 8 ++- .../codeFixInferFromUsageRestParam3JS.ts | 10 ++- .../codeFixInferFromUsageRestParamJS.ts | 8 ++- .../codeFixInferFromUsageSetterJS.ts | 11 ++-- .../codeFixInferFromUsageSingleLineClassJS.ts | 11 ++-- 12 files changed, 88 insertions(+), 78 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index d69df1d6cbd..406985f1efa 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2422,7 +2422,20 @@ Actual: ${stringify(fullActual)}`); */ public getAndApplyCodeActions(errorCode?: number, index?: number) { const fileName = this.activeFile.fileName; - this.applyCodeActions(this.getCodeFixes(fileName, errorCode), index); + const fixes = this.getCodeFixes(fileName, errorCode); + if (index === undefined) { + if (!(fixes && fixes.length === 1)) { + this.raiseError(`Should find exactly one codefix, but ${fixes ? fixes.length : "none"} found. ${fixes ? fixes.map(a => `${Harness.IO.newLine()} "${a.description}"`) : ""}`); + } + index = 0; + } + else { + if (!(fixes && fixes.length >= index + 1)) { + this.raiseError(`Should find at least ${index + 1} codefix(es), but ${fixes ? fixes.length : "none"} found.`); + } + } + + this.applyChanges(fixes[index].changes); } public applyCodeActionFromCompletion(markerName: string, options: FourSlashInterface.VerifyCompletionActionOptions) { @@ -2433,12 +2446,12 @@ Actual: ${stringify(fullActual)}`); if (codeActions.length !== 1) { this.raiseError(`Expected one code action, got ${codeActions.length}`); } + const codeAction = ts.first(codeActions); - if (codeActions[0].description !== options.description) { + if (codeAction.description !== options.description) { this.raiseError(`Expected description to be:\n${options.description}\ngot:\n${codeActions[0].description}`); } - - this.applyCodeActions(codeActions); + this.applyChanges(codeAction.changes); this.verifyNewContentAfterChange(options, ts.flatMap(codeActions, a => a.changes.map(c => c.fileName))); } @@ -2483,26 +2496,6 @@ Actual: ${stringify(fullActual)}`); this.verifyNewContent({ newFileContent }, changes); } - /** - * Applies fixes for the errors in fileName and compares the results to - * expectedContents after all fixes have been applied. - * - * Note: applying one codefix may generate another (eg: remove duplicate implements - * may generate an extends -> interface conversion fix). - * @param expectedContents The contents of the file after the fixes are applied. - * @param fileName The file to check. If not supplied, the current open file is used. - */ - public verifyFileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { - fileName = fileName ? fileName : this.activeFile.fileName; - - this.applyCodeActions(this.getCodeFixes(fileName), index); - - const actualContents: string = this.getFileContent(fileName); - if (this.removeWhitespace(actualContents) !== this.removeWhitespace(expectedContents)) { - this.raiseError(`Actual text doesn't match expected text. Actual:\n${actualContents}\n\nExpected:\n${expectedContents}`); - } - } - public verifyCodeFix(options: FourSlashInterface.VerifyCodeFixOptions) { const fileName = this.activeFile.fileName; const actions = this.getCodeFixes(fileName, options.errorCode, options.preferences); @@ -2607,22 +2600,6 @@ Actual: ${stringify(fullActual)}`); }); } - private applyCodeActions(actions: ReadonlyArray, index?: number): void { - if (index === undefined) { - if (!(actions && actions.length === 1)) { - this.raiseError(`Should find exactly one codefix, but ${actions ? actions.length : "none"} found. ${actions ? actions.map(a => `${Harness.IO.newLine()} "${a.description}"`) : ""}`); - } - index = 0; - } - else { - if (!(actions && actions.length >= index + 1)) { - this.raiseError(`Should find at least ${index + 1} codefix(es), but ${actions ? actions.length : "none"} found.`); - } - } - - this.applyChanges(actions[index].changes); - } - private applyChanges(changes: ReadonlyArray): void { for (const change of changes) { this.applyEdits(change.fileName, change.textChanges, /*isFormattingEdit*/ false); @@ -4364,10 +4341,6 @@ namespace FourSlashInterface { this.state.verifyRangeAfterCodeFix(expectedText, includeWhiteSpace, errorCode, index); } - public fileAfterCodeFix(expectedContents: string, fileName?: string, index?: number) { - this.state.verifyFileAfterCodeFix(expectedContents, fileName, index); - } - public codeFixAll(options: VerifyCodeFixAllOptions): void { this.state.verifyCodeFixAll(options); } diff --git a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts index cb86347cb9f..3fd76defd21 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts @@ -14,10 +14,12 @@ //// } ////} - // Note: Should be number[] | undefined, but inference currently privileges assignments // over usage (even when the only result is undefined) and infers only undefined. -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer type of 'p' from usage", + index: 2, + newFileContent: `class C { constructor() { /** @type {undefined} */ @@ -26,5 +28,5 @@ verify.fileAfterCodeFix( method() { this.p.push(1) } -} -`, undefined, 2); +}` +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts index 8f544df4323..d57f3292375 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts @@ -9,8 +9,10 @@ //// } //// f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string"); - -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 6, + newFileContent: `/** * @param {number} a * @param {string} b @@ -20,4 +22,5 @@ verify.fileAfterCodeFix( */ function f(a, b, c, d, e = 0, ...d ) { } -f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");`, undefined, 6); +f(1, "string", { a: 1 }, {shouldNotBeHere: 2}, {shouldNotBeHere: 2}, 3, "string");`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts index b6b8fe4c25f..d494d1dbb7b 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts @@ -8,10 +8,14 @@ //// return a[0] + 1; ////} -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: `/** * @param {number[]} a */ function f(a) { return a[0] + 1; -}`, undefined, 2); +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts index cc00c1ddb5d..7003950b7ff 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts @@ -10,12 +10,16 @@ ////f(); ////f(1); -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: `/** * @param {number} [a] */ -function f(a) { +function f(a){ a; } f(); -f(1);`, undefined, 2); +f(1);`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts index 67795b6a178..308041dd09c 100644 --- a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts @@ -13,9 +13,11 @@ ////} ////f(1, 2, 3) -verify.fileAfterCodeFix( -` -/** +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: +`/** * @param {*} y */ /** @@ -25,5 +27,5 @@ verify.fileAfterCodeFix( function f(x, y, z) { return x } -f(1, 2, 3) -`, undefined, 2); +f(1, 2, 3)`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts index a52c66312fc..322d51a79ab 100644 --- a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts @@ -16,7 +16,10 @@ //// return x.y.z ////} -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: `/** * @param {{ b: { c: any; }; }} a * @param {{ n: () => number; }} m @@ -31,4 +34,5 @@ function foo(a, m, x) { x.y.z x.y.z.push(0); return x.y.z -}`, undefined, 2); +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts index 0504816c597..85ee0de9cef 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts @@ -13,7 +13,10 @@ ////f(3, false, "s2"); ////f(4, "s1", "s2", false, "s4"); -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: `/** @param {number} a */ /** * @param {(string | boolean)[]} rest @@ -24,4 +27,5 @@ function f(a, ...rest){ f(1); f(2, "s1"); f(3, false, "s2"); -f(4, "s1", "s2", false, "s4");`, undefined, 2); +f(4, "s1", "s2", false, "s4");`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts index bda7090ba06..689d12c783a 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts @@ -5,12 +5,15 @@ // @noImplicitAny: true // @Filename: important.js /////** @param {number} a */ -////function f(a, [|...rest |]){ +////function f(a, [|...rest|]){ //// a; //// rest.push(22); ////} -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: `/** @param {number} a */ /** * @param {number[]} rest @@ -18,4 +21,5 @@ verify.fileAfterCodeFix( function f(a, ...rest){ a; rest.push(22); -}`, undefined, 2); +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts index 36582bfa7db..b46bd7dd843 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts @@ -13,7 +13,10 @@ ////f(3, "s1", "s2"); ////f(3, "s1", "s2", "s3", "s4"); -verify.fileAfterCodeFix( +verify.codeFix({ + description: "Infer parameter types from usage", + index: 4, + newFileContent: `/** @param {number} a */ /** * @param {string[]} rest @@ -24,4 +27,5 @@ function f(a: number, ...rest){ f(1); f(2, "s1"); f(3, "s1", "s2"); -f(3, "s1", "s2", "s3", "s4");`, undefined, 4); +f(3, "s1", "s2", "s3", "s4");`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts index 71621f48239..c9c0c719de4 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts @@ -11,9 +11,11 @@ ////} ////(new C).x = 1; -verify.fileAfterCodeFix( -` -class C { +verify.codeFix({ + description: "Infer type of \'x\' from usage", + index: 2, + newFileContent: +`class C { /** * @param {number} v */ @@ -21,4 +23,5 @@ class C { v; } } -(new C).x = 1;`, undefined, 2); +(new C).x = 1;`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts index f78a70aa14a..0ea9a4d5719 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts @@ -9,11 +9,14 @@ ////var c = new C() ////c.m(1) -verify.fileAfterCodeFix( -` -class C {/** +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: +`class C {/** * @param {number} x */ m(x) {return x;}} var c = new C() -c.m(1)`, undefined, 2); +c.m(1)`, +}); From e46c846ee6e20687ea4a39055f1081ba73ca89ec Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 24 Oct 2018 15:37:46 -0700 Subject: [PATCH 115/262] Remove getBucketForCompilationSettings (#28088) --- src/services/documentRegistry.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 5720c69be68..4744f25ac7b 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -121,14 +121,6 @@ namespace ts { const buckets = createMap>(); const getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); - function getBucketForCompilationSettings(key: DocumentRegistryBucketKey, createIfMissing: boolean): Map { - let bucket = buckets.get(key); - if (!bucket && createIfMissing) { - buckets.set(key, bucket = createMap()); - } - return bucket!; // TODO: GH#18217 - } - function reportStats() { const bucketInfoArray = arrayFrom(buckets.keys()).filter(name => name && name.charAt(0) === "_").map(name => { const entries = buckets.get(name)!; @@ -178,7 +170,7 @@ namespace ts { acquiring: boolean, scriptKind?: ScriptKind): SourceFile { - const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); + const bucket = getOrUpdate>(buckets, key, createMap); let entry = bucket.get(path); const scriptTarget = scriptKind === ScriptKind.JSON ? ScriptTarget.JSON : compilationSettings.target || ScriptTarget.ES5; if (!entry && externalCache) { @@ -238,9 +230,7 @@ namespace ts { } function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void { - const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false); - Debug.assert(bucket !== undefined); - + const bucket = Debug.assertDefined(buckets.get(key)); const entry = bucket.get(path)!; entry.languageServiceRefCount--; From fe2a33fcbcb8973bb4d88ad5ff56eb7f5ebaa70b Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 24 Oct 2018 16:14:52 -0700 Subject: [PATCH 116/262] Merge existing JSDoc comments (#27978) * Correct indentation, using correct (I hope) indentation code Note that part of the code, in formatting.ts, is cloned but should be extracted to a function instead. * Remove some possibly-superfluous code But I see 4 failures with whitespace, so perhaps not. * Restrict indentation change to avoid breaking baselines The indentation code is very complex so I'm just going to avoid breaking our single-line tests for now, plus add a simple jsdoc test to show that multiline jsdoc indentation isn't destroyed in the common case. * Switched over to construction for @return/@type Still doesn't merge correctly though * Add @return tags to emitter * Merge multiple jsdocs (not for @param yet) * Merge multiple jsdoc for parameters too * Emit more jsdoc tags Not all of them; I got cold feet since I'll have to write tests for them. I'll do that tomorrow. * Many fixes to JSDoc emit And single tests (at least) for all tags * Cleanup in textChanges.ts * Cleanup in formatting.ts (Plus a little more in textChanges.ts) * Cleanup in inferFromUsage.ts * Fix minor omissions * Separate merged top-level JSDoc comments with \n instead of space. * Don't delete intrusive non-jsdoc comments * Cleanup from PR comments 1. Refactor emit code into smaller functions. 2. Preceding-whitespace utility is slightly easier to use. 3. Better casts and types in inferFromUsage make it easier to read. * Fix bogus newline * Use @andy-ms' cleanup annotateJSDocParameters --- src/compiler/emitter.ts | 189 +++++++++++++++++- src/compiler/factory.ts | 51 +++++ src/compiler/types.ts | 36 ++-- src/services/codefixes/inferFromUsage.ts | 58 +++++- src/services/formatting/formatting.ts | 85 ++++---- src/services/formatting/smartIndenter.ts | 6 +- src/services/textChanges.ts | 61 ++---- src/services/utilities.ts | 7 + .../reference/api/tsserverlibrary.d.ts | 108 +++++----- tests/baselines/reference/api/typescript.d.ts | 108 +++++----- .../codeFixInferFromUsageExistingJSDoc.ts | 95 +++++++++ .../codeFixInferFromUsageMemberJS.ts | 22 +- ...FixInferFromUsagePartialParameterListJS.ts | 2 - .../codeFixInferFromUsageRestParam2JS.ts | 4 +- .../codeFixInferFromUsageRestParam3JS.ts | 4 +- .../codeFixInferFromUsageRestParamJS.ts | 4 +- .../codeFixInferFromUsageSingleLineClassJS.ts | 6 +- .../fourslash/formatDocumentWithJSDoc.ts | 29 +++ .../fourslash/formatDocumentWithTrivia.ts | 20 +- .../smartIndentOnFunctionParameters.ts | 8 +- 20 files changed, 654 insertions(+), 249 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageExistingJSDoc.ts create mode 100644 tests/cases/fourslash/formatDocumentWithJSDoc.ts diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 8617c8fccde..50644552efe 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -862,7 +862,34 @@ namespace ts { case SyntaxKind.EnumMember: return emitEnumMember(node); - // JSDoc nodes (ignored) + // JSDoc nodes (only used in codefixes currently) + case SyntaxKind.JSDocParameterTag: + case SyntaxKind.JSDocPropertyTag: + return emitJSDocPropertyLikeTag(node as JSDocPropertyLikeTag); + case SyntaxKind.JSDocReturnTag: + case SyntaxKind.JSDocTypeTag: + case SyntaxKind.JSDocThisTag: + case SyntaxKind.JSDocEnumTag: + return emitJSDocSimpleTypedTag(node as JSDocTypeTag); + case SyntaxKind.JSDocAugmentsTag: + return emitJSDocAugmentsTag(node as JSDocAugmentsTag); + case SyntaxKind.JSDocTemplateTag: + return emitJSDocTemplateTag(node as JSDocTemplateTag); + case SyntaxKind.JSDocTypedefTag: + return emitJSDocTypedefTag(node as JSDocTypedefTag); + case SyntaxKind.JSDocCallbackTag: + return emitJSDocCallbackTag(node as JSDocCallbackTag); + case SyntaxKind.JSDocSignature: + return emitJSDocSignature(node as JSDocSignature); + case SyntaxKind.JSDocTypeLiteral: + return emitJSDocTypeLiteral(node as JSDocTypeLiteral); + case SyntaxKind.JSDocClassTag: + case SyntaxKind.JSDocTag: + return emitJSDocSimpleTag(node as JSDocTag); + + case SyntaxKind.JSDocComment: + return emitJSDoc(node as JSDoc); + // Transformation nodes (ignored) } @@ -2584,6 +2611,154 @@ namespace ts { emitInitializer(node.initializer, node.name.end, node); } + // + // JSDoc + // + function emitJSDoc(node: JSDoc) { + write("/**"); + if (node.comment) { + const lines = node.comment.split(/\r\n?|\n/g); + for (const line of lines) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + write(line); + } + } + if (node.tags) { + if (node.tags.length === 1 && node.tags[0].kind === SyntaxKind.JSDocTypeTag && !node.comment) { + writeSpace(); + emit(node.tags[0]); + } + else { + emitList(node, node.tags, ListFormat.JSDocComment); + } + } + writeSpace(); + write("*/"); + } + + function emitJSDocSimpleTypedTag(tag: JSDocTypeTag | JSDocThisTag | JSDocEnumTag | JSDocReturnTag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.typeExpression); + emitJSDocComment(tag.comment); + } + + function emitJSDocAugmentsTag(tag: JSDocAugmentsTag) { + emitJSDocTagName(tag.tagName); + writeSpace(); + writePunctuation("{"); + emit(tag.class); + writePunctuation("}"); + emitJSDocComment(tag.comment); + } + + function emitJSDocTemplateTag(tag: JSDocTemplateTag) { + emitJSDocTagName(tag.tagName); + emitJSDocTypeExpression(tag.constraint); + writeSpace(); + emitList(tag, tag.typeParameters, ListFormat.CommaListElements); + emitJSDocComment(tag.comment); + } + + function emitJSDocTypedefTag(tag: JSDocTypedefTag) { + emitJSDocTagName(tag.tagName); + if (tag.typeExpression) { + if (tag.typeExpression.kind === SyntaxKind.JSDocTypeExpression) { + emitJSDocTypeExpression(tag.typeExpression); + } + else { + writeSpace(); + writePunctuation("{"); + write("Object"); + if (tag.typeExpression.isArrayType) { + writePunctuation("["); + writePunctuation("]"); + } + writePunctuation("}"); + } + } + if (tag.fullName) { + writeSpace(); + emit(tag.fullName); + } + emitJSDocComment(tag.comment); + if (tag.typeExpression && tag.typeExpression.kind === SyntaxKind.JSDocTypeLiteral) { + emitJSDocTypeLiteral(tag.typeExpression); + } + } + + function emitJSDocCallbackTag(tag: JSDocCallbackTag) { + emitJSDocTagName(tag.tagName); + if (tag.name) { + writeSpace(); + emit(tag.name); + } + emitJSDocComment(tag.comment); + emitJSDocSignature(tag.typeExpression); + } + + function emitJSDocSimpleTag(tag: JSDocTag) { + emitJSDocTagName(tag.tagName); + emitJSDocComment(tag.comment); + } + + function emitJSDocTypeLiteral(lit: JSDocTypeLiteral) { + emitList(lit, createNodeArray(lit.jsDocPropertyTags), ListFormat.JSDocComment); + } + + function emitJSDocSignature(sig: JSDocSignature) { + if (sig.typeParameters) { + emitList(sig, createNodeArray(sig.typeParameters), ListFormat.JSDocComment); + } + if (sig.parameters) { + emitList(sig, createNodeArray(sig.parameters), ListFormat.JSDocComment); + } + if (sig.type) { + writeLine(); + writeSpace(); + writePunctuation("*"); + writeSpace(); + emit(sig.type); + } + } + + function emitJSDocPropertyLikeTag(param: JSDocPropertyLikeTag) { + emitJSDocTagName(param.tagName); + emitJSDocTypeExpression(param.typeExpression); + writeSpace(); + if (param.isBracketed) { + writePunctuation("["); + } + emit(param.name); + if (param.isBracketed) { + writePunctuation("]"); + } + emitJSDocComment(param.comment); + } + + function emitJSDocTagName(tagName: Identifier) { + writePunctuation("@"); + emit(tagName); + } + + function emitJSDocComment(comment: string | undefined) { + if (comment) { + writeSpace(); + write(comment); + } + } + + function emitJSDocTypeExpression(typeExpression: JSDocTypeExpression | undefined) { + if (typeExpression) { + writeSpace(); + writePunctuation("{"); + emit(typeExpression.type); + writePunctuation("}"); + } + } + // // Top-level nodes // @@ -2875,6 +3050,11 @@ namespace ts { writeSpace(); writePunctuation("|"); break; + case ListFormat.AsteriskDelimited: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case ListFormat.AmpersandDelimited: writeSpace(); writePunctuation("&"); @@ -2944,7 +3124,12 @@ namespace ts { const child = children![start + i]; // Write the delimiter if this is not the first node. - if (previousSibling) { + if (format & ListFormat.AsteriskDelimited) { + // always write JSDoc in the format "\n *" + writeLine(); + writeDelimiter(format); + } + else if (previousSibling) { // i.e // function commentedParameters( // /* Parameter a */ diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 4b2855790a9..01de5850471 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2170,6 +2170,57 @@ namespace ts { : node; } + // JSDoc + + /* @internal */ + export function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression { + const node = createSynthesizedNode(SyntaxKind.JSDocTypeExpression) as JSDocTypeExpression; + node.type = type; + return node; + } + + /* @internal */ + export function createJSDocTypeTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocTypeTag { + const tag = createJSDocTag(SyntaxKind.JSDocTypeTag, "type"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocReturnTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag { + const tag = createJSDocTag(SyntaxKind.JSDocReturnTag, "returns"); + tag.typeExpression = typeExpression; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag { + const tag = createJSDocTag(SyntaxKind.JSDocParameterTag, "param"); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isBracketed = isBracketed; + tag.comment = comment; + return tag; + } + + /* @internal */ + export function createJSDocComment(comment?: string | undefined, tags?: NodeArray | undefined) { + const node = createSynthesizedNode(SyntaxKind.JSDocComment) as JSDoc; + node.comment = comment; + node.tags = tags; + return node; + } + + /* @internal */ + function createJSDocTag(kind: T["kind"], tagName: string): T { + const node = createSynthesizedNode(kind) as T; + node.atToken = createToken(SyntaxKind.AtToken); + node.tagName = createIdentifier(tagName); + return node; + } + // JSX export function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement) { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 07848b19c62..85a51db27c5 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2447,7 +2447,7 @@ namespace ts { export interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } @@ -5532,33 +5532,34 @@ namespace ts { BarDelimited = 1 << 2, // Each list item is space-and-bar (" |") delimited. AmpersandDelimited = 1 << 3, // Each list item is space-and-ampersand (" &") delimited. CommaDelimited = 1 << 4, // Each list item is comma (",") delimited. - DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited, + AsteriskDelimited = 1 << 5, // Each list item is asterisk ("\n *") delimited, used with JSDoc. + DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited | AsteriskDelimited, - AllowTrailingComma = 1 << 5, // Write a trailing comma (",") if present. + AllowTrailingComma = 1 << 6, // Write a trailing comma (",") if present. // Whitespace - Indented = 1 << 6, // The list should be indented. - SpaceBetweenBraces = 1 << 7, // Inserts a space after the opening brace and before the closing brace. - SpaceBetweenSiblings = 1 << 8, // Inserts a space between each sibling node. + Indented = 1 << 7, // The list should be indented. + SpaceBetweenBraces = 1 << 8, // Inserts a space after the opening brace and before the closing brace. + SpaceBetweenSiblings = 1 << 9, // Inserts a space between each sibling node. // Brackets/Braces - Braces = 1 << 9, // The list is surrounded by "{" and "}". - Parenthesis = 1 << 10, // The list is surrounded by "(" and ")". - AngleBrackets = 1 << 11, // The list is surrounded by "<" and ">". - SquareBrackets = 1 << 12, // The list is surrounded by "[" and "]". + Braces = 1 << 10, // The list is surrounded by "{" and "}". + Parenthesis = 1 << 11, // The list is surrounded by "(" and ")". + AngleBrackets = 1 << 12, // The list is surrounded by "<" and ">". + SquareBrackets = 1 << 13, // The list is surrounded by "[" and "]". BracketsMask = Braces | Parenthesis | AngleBrackets | SquareBrackets, - OptionalIfUndefined = 1 << 13, // Do not emit brackets if the list is undefined. - OptionalIfEmpty = 1 << 14, // Do not emit brackets if the list is empty. + OptionalIfUndefined = 1 << 14, // Do not emit brackets if the list is undefined. + OptionalIfEmpty = 1 << 15, // Do not emit brackets if the list is empty. Optional = OptionalIfUndefined | OptionalIfEmpty, // Other - PreferNewLine = 1 << 15, // Prefer adding a LineTerminator between synthesized nodes. - NoTrailingNewLine = 1 << 16, // Do not emit a trailing NewLine for a MultiLine list. - NoInterveningComments = 1 << 17, // Do not emit comments between each node + PreferNewLine = 1 << 16, // Prefer adding a LineTerminator between synthesized nodes. + NoTrailingNewLine = 1 << 17, // Do not emit a trailing NewLine for a MultiLine list. + NoInterveningComments = 1 << 18, // Do not emit comments between each node - NoSpaceIfEmpty = 1 << 18, // If the literal is empty, do not add spaces between braces. - SingleElement = 1 << 19, + NoSpaceIfEmpty = 1 << 19, // If the literal is empty, do not add spaces between braces. + SingleElement = 1 << 20, // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments, @@ -5598,6 +5599,7 @@ namespace ts { TypeParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional, Parameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, IndexSignatureParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented | SquareBrackets, + JSDocComment = MultiLine | AsteriskDelimited, } /* @internal */ diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 62f73df9f80..2055bbf3b31 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -73,7 +73,9 @@ namespace ts.codefix { const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); const typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { - changes.tryInsertJSDocType(sourceFile, parent, typeNode); + // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags + const typeTag = createJSDocTypeTag(createJSDocTypeExpression(typeNode), /*comment*/ ""); + addJSDocTags(changes, sourceFile, cast(parent.parent.parent, isExpressionStatement), [typeTag]); } return parent; } @@ -192,7 +194,13 @@ namespace ts.codefix { const typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { - changes.tryInsertJSDocType(sourceFile, declaration, typeNode); + const parent = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; + if (!parent) { + return; + } + const typeExpression = createJSDocTypeExpression(typeNode); + const typeTag = isGetAccessorDeclaration(declaration) ? createJSDocReturnTag(typeExpression, "") : createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); } else { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); @@ -200,16 +208,52 @@ namespace ts.codefix { } } - function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ParameterInference[], program: Program, host: LanguageServiceHost): void { - const result = mapDefined(parameterInferences, inference => { + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: ReadonlyArray, program: Program, host: LanguageServiceHost): void { + const signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + const paramTags = mapDefined(parameterInferences, inference => { const param = inference.declaration; + // only infer parameters that have (1) no type and (2) an accessible inferred type + if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) return; + const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); - return typeNode && !param.initializer && !getJSDocType(param) ? { ...inference, typeNode } : undefined; + return typeNode && createJSDocParamTag(param.name, !!inference.isOptional, createJSDocTypeExpression(typeNode), ""); }); - changes.tryInsertJSDocParameters(sourceFile, result); + addJSDocTags(changes, sourceFile, signature, paramTags); } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: ReadonlyArray): void { + const comments = mapDefined(parent.jsDoc, j => j.comment); + const oldTags = flatMap(parent.jsDoc, j => j.tags); + const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { + const merged = tryMergeJsdocTags(tag, newTag); + if (merged) oldTags[i] = merged; + return !!merged; + })); + const tag = createJSDocComment(comments.join("\n"), createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags])); + changes.insertJsdocCommentBefore(sourceFile, parent, tag); + } + + function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case SyntaxKind.JSDocParameterTag: { + const oldParam = oldTag as JSDocParameterTag; + const newParam = newTag as JSDocParameterTag; + return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + : undefined; + } + case SyntaxKind.JSDocReturnTag: + return createJSDocReturnTag((newTag as JSDocReturnTag).typeExpression, oldTag.comment); + } + } + + function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => { typeIsAccessible = false; }; diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 0ed6e84e2c3..215585f238e 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -365,16 +365,21 @@ namespace ts.formatting { function formatSpan(originalRange: TextRange, sourceFile: SourceFile, formatContext: FormatContext, requestKind: FormattingRequestKind): TextChange[] { // find the smallest node that fully wraps the range and compute the initial indentation for the node const enclosingNode = findEnclosingNode(originalRange, sourceFile); - return getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, scanner => formatSpanWorker( - originalRange, - enclosingNode, - SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), - getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), - scanner, - formatContext, - requestKind, - prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), - sourceFile)); + return getFormattingScanner( + sourceFile.text, + sourceFile.languageVariant, + getScanStartPosition(enclosingNode, originalRange, sourceFile), + originalRange.end, + scanner => formatSpanWorker( + originalRange, + enclosingNode, + SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), + getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), + scanner, + formatContext, + requestKind, + prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), + sourceFile)); } function formatSpanWorker(originalRange: TextRange, @@ -413,7 +418,8 @@ namespace ts.formatting { if (!formattingScanner.isOnToken()) { const leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!); // TODO: GH#18217 + indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, + item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!)); trimTrailingWhitespacesForRemainingRange(); } } @@ -814,27 +820,8 @@ namespace ts.formatting { let indentNextTokenOrTrivia = true; if (currentTokenInfo.leadingTrivia) { const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container); - - for (const triviaItem of currentTokenInfo.leadingTrivia) { - const triviaInRange = rangeContainsRange(originalRange, triviaItem); - switch (triviaItem.kind) { - case SyntaxKind.MultiLineCommentTrivia: - if (triviaInRange) { - indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); - } - indentNextTokenOrTrivia = false; - break; - case SyntaxKind.SingleLineCommentTrivia: - if (indentNextTokenOrTrivia && triviaInRange) { - insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false); - } - indentNextTokenOrTrivia = false; - break; - case SyntaxKind.NewLineTrivia: - indentNextTokenOrTrivia = true; - break; - } - } + indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia, + item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ false)); } // indent token only if is it is in target range and does not overlap with any error ranges @@ -852,6 +839,34 @@ namespace ts.formatting { } } + function indentTriviaItems( + trivia: TextRangeWithKind[], + commentIndentation: number, + indentNextTokenOrTrivia: boolean, + indentSingleLine: (item: TextRangeWithKind) => void) { + for (const triviaItem of trivia) { + const triviaInRange = rangeContainsRange(originalRange, triviaItem); + switch (triviaItem.kind) { + case SyntaxKind.MultiLineCommentTrivia: + if (triviaInRange) { + indentMultilineCommentOrJsxText(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia); + } + indentNextTokenOrTrivia = false; + break; + case SyntaxKind.SingleLineCommentTrivia: + if (indentNextTokenOrTrivia && triviaInRange) { + indentSingleLine(triviaItem); + } + indentNextTokenOrTrivia = false; + break; + case SyntaxKind.NewLineTrivia: + indentNextTokenOrTrivia = true; + break; + } + } + return indentNextTokenOrTrivia; + } + function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void { for (const triviaItem of trivia) { if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) { @@ -861,7 +876,6 @@ namespace ts.formatting { } } - // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range: TextRangeWithKind, rangeStart: LineAndCharacter, parent: Node, @@ -1072,7 +1086,10 @@ namespace ts.formatting { * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - const startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + const startPosition = previousRange.end; const startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; const endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index c5554afd45e..ccc05d84426 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -79,14 +79,14 @@ namespace ts.formatting { return findFirstNonWhitespaceColumn(getStartPositionOfLine(commentStartLine, sourceFile), position, sourceFile, options); } - const startPostionOfLine = getStartPositionOfLine(previousLine, sourceFile); - const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPostionOfLine, position, sourceFile, options); + const startPositionOfLine = getStartPositionOfLine(previousLine, sourceFile); + const { column, character } = findFirstNonWhitespaceCharacterAndColumn(startPositionOfLine, position, sourceFile, options); if (column === 0) { return column; } - const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPostionOfLine + character); + const firstNonWhitespaceCharacterCode = sourceFile.text.charCodeAt(startPositionOfLine + character); return firstNonWhitespaceCharacterCode === CharacterCodes.asterisk ? column - 1 : column; } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index ab12e097f7a..cf850cd63ab 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -209,12 +209,6 @@ namespace ts.textChanges { export type TypeAnnotatable = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature; - interface JSDocParameter { - declaration: ParameterDeclaration; - typeNode: TypeNode; - isOptional?: boolean; - } - export class ChangeTracker { private readonly changes: Change[] = []; private readonly newFiles: { readonly oldFile: SourceFile | undefined, readonly fileName: string, readonly statements: ReadonlyArray }[] = []; @@ -345,10 +339,19 @@ namespace ts.textChanges { this.insertText(sourceFile, token.getStart(sourceFile), text); } - public insertCommentThenNewline(sourceFile: SourceFile, character: number, position: number, commentText: string): void { - const token = getTouchingToken(sourceFile, position); - const text = "/**" + commentText + "*/" + this.newLineCharacter + repeatString(" ", character); - this.insertText(sourceFile, token.getStart(sourceFile), text); + public insertJsdocCommentBefore(sourceFile: SourceFile, node: HasJSDoc, tag: JSDoc) { + const fnStart = node.getStart(sourceFile); + if (node.jsDoc) { + for (const jsdoc of node.jsDoc) { + this.deleteRange(sourceFile, { + pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile), + end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}) + }); + } + } + const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1); + const indent = sourceFile.text.slice(startPosition, fnStart); + this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); } public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string) { @@ -359,23 +362,6 @@ namespace ts.textChanges { this.replaceRangeWithText(sourceFile, createRange(pos), text); } - public tryInsertJSDocParameters(sourceFile: SourceFile, parameters: JSDocParameter[]) { - if (parameters.length === 0) { - return; - } - const parent = parameters[0].declaration.parent; - const indent = getLineAndCharacterOfPosition(sourceFile, parent.getStart()).character; - let commentText = "\n"; - for (const { declaration, typeNode, isOptional } of parameters) { - if (isIdentifier(declaration.name)) { - const printed = changesToText.getNonformattedText(typeNode, sourceFile, this.newLineCharacter).text; - commentText += this.printJSDocParameter(indent, printed, declaration.name, isOptional); - } - } - commentText += repeatString(" ", indent + 1); - this.insertCommentThenNewline(sourceFile, indent, parent.getStart(), commentText); - } - /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void { let endNode: Node | undefined; @@ -394,27 +380,6 @@ namespace ts.textChanges { this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); } - public tryInsertJSDocType(sourceFile: SourceFile, node: Node, type: TypeNode): void { - const printed = changesToText.getNonformattedText(type, sourceFile, this.newLineCharacter).text; - let commentText; - if (isGetAccessorDeclaration(node)) { - commentText = ` @return {${printed}} `; - } - else { - commentText = ` @type {${printed}} `; - node = node.parent; - } - this.insertCommentThenNewline(sourceFile, getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)).character, node.getStart(sourceFile), commentText); - } - - private printJSDocParameter(indent: number, printed: string, name: Identifier, isOptionalParameter: boolean | undefined) { - let printName = unescapeLeadingUnderscores(name.escapedText); - if (isOptionalParameter) { - printName = `[${printName}]`; - } - return repeatString(" ", indent) + ` * @param {${printed}} ${printName}\n`; - } - public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: ReadonlyArray): void { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter const start = (findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile) || first(node.parameters)).getStart(sourceFile); diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 7a713fed749..da026510c56 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1672,6 +1672,13 @@ namespace ts { return position; } + export function getPrecedingNonSpaceCharacterPosition(text: string, position: number) { + while (position > -1 && isWhiteSpaceSingleLine(text.charCodeAt(position))) { + position -= 1; + } + return position + 1; + } + /** * Creates a deep, memberwise clone of a node with no source map location. * diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9356951e1ee..324d76f2f87 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1573,7 +1573,7 @@ declare namespace ts { } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -2942,60 +2942,62 @@ declare namespace ts { BarDelimited = 4, AmpersandDelimited = 8, CommaDelimited = 16, - DelimitersMask = 28, - AllowTrailingComma = 32, - Indented = 64, - SpaceBetweenBraces = 128, - SpaceBetweenSiblings = 256, - Braces = 512, - Parenthesis = 1024, - AngleBrackets = 2048, - SquareBrackets = 4096, - BracketsMask = 7680, - OptionalIfUndefined = 8192, - OptionalIfEmpty = 16384, - Optional = 24576, - PreferNewLine = 32768, - NoTrailingNewLine = 65536, - NoInterveningComments = 131072, - NoSpaceIfEmpty = 262144, - SingleElement = 524288, - Modifiers = 131328, - HeritageClauses = 256, - SingleLineTypeLiteralMembers = 384, - MultiLineTypeLiteralMembers = 16449, - TupleTypeElements = 272, - UnionTypeConstituents = 260, - IntersectionTypeConstituents = 264, - ObjectBindingPatternElements = 262576, - ArrayBindingPatternElements = 262448, - ObjectLiteralExpressionProperties = 263122, - ArrayLiteralExpressionElements = 4466, - CommaListElements = 272, - CallExpressionArguments = 1296, - NewExpressionArguments = 9488, - TemplateExpressionSpans = 131072, - SingleLineBlockStatements = 384, - MultiLineBlockStatements = 65, - VariableDeclarationList = 272, - SingleLineFunctionBodyStatements = 384, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, MultiLineFunctionBodyStatements = 1, ClassHeritageClauses = 0, - ClassMembers = 65, - InterfaceMembers = 65, - EnumMembers = 81, - CaseBlockClauses = 65, - NamedImportsOrExportsElements = 262576, - JsxElementOrFragmentChildren = 131072, - JsxElementAttributes = 131328, - CaseOrDefaultClauseStatements = 81985, - HeritageClauseTypes = 272, - SourceFileStatements = 65537, - Decorators = 24577, - TypeArguments = 26896, - TypeParameters = 26896, - Parameters = 1296, - IndexSignatureParameters = 4432 + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 } interface UserPreferences { readonly disableSuggestions?: boolean; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 66e30ee2a49..c95f50f6ca0 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1573,7 +1573,7 @@ declare namespace ts { } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { @@ -2942,60 +2942,62 @@ declare namespace ts { BarDelimited = 4, AmpersandDelimited = 8, CommaDelimited = 16, - DelimitersMask = 28, - AllowTrailingComma = 32, - Indented = 64, - SpaceBetweenBraces = 128, - SpaceBetweenSiblings = 256, - Braces = 512, - Parenthesis = 1024, - AngleBrackets = 2048, - SquareBrackets = 4096, - BracketsMask = 7680, - OptionalIfUndefined = 8192, - OptionalIfEmpty = 16384, - Optional = 24576, - PreferNewLine = 32768, - NoTrailingNewLine = 65536, - NoInterveningComments = 131072, - NoSpaceIfEmpty = 262144, - SingleElement = 524288, - Modifiers = 131328, - HeritageClauses = 256, - SingleLineTypeLiteralMembers = 384, - MultiLineTypeLiteralMembers = 16449, - TupleTypeElements = 272, - UnionTypeConstituents = 260, - IntersectionTypeConstituents = 264, - ObjectBindingPatternElements = 262576, - ArrayBindingPatternElements = 262448, - ObjectLiteralExpressionProperties = 263122, - ArrayLiteralExpressionElements = 4466, - CommaListElements = 272, - CallExpressionArguments = 1296, - NewExpressionArguments = 9488, - TemplateExpressionSpans = 131072, - SingleLineBlockStatements = 384, - MultiLineBlockStatements = 65, - VariableDeclarationList = 272, - SingleLineFunctionBodyStatements = 384, + AsteriskDelimited = 32, + DelimitersMask = 60, + AllowTrailingComma = 64, + Indented = 128, + SpaceBetweenBraces = 256, + SpaceBetweenSiblings = 512, + Braces = 1024, + Parenthesis = 2048, + AngleBrackets = 4096, + SquareBrackets = 8192, + BracketsMask = 15360, + OptionalIfUndefined = 16384, + OptionalIfEmpty = 32768, + Optional = 49152, + PreferNewLine = 65536, + NoTrailingNewLine = 131072, + NoInterveningComments = 262144, + NoSpaceIfEmpty = 524288, + SingleElement = 1048576, + Modifiers = 262656, + HeritageClauses = 512, + SingleLineTypeLiteralMembers = 768, + MultiLineTypeLiteralMembers = 32897, + TupleTypeElements = 528, + UnionTypeConstituents = 516, + IntersectionTypeConstituents = 520, + ObjectBindingPatternElements = 525136, + ArrayBindingPatternElements = 524880, + ObjectLiteralExpressionProperties = 526226, + ArrayLiteralExpressionElements = 8914, + CommaListElements = 528, + CallExpressionArguments = 2576, + NewExpressionArguments = 18960, + TemplateExpressionSpans = 262144, + SingleLineBlockStatements = 768, + MultiLineBlockStatements = 129, + VariableDeclarationList = 528, + SingleLineFunctionBodyStatements = 768, MultiLineFunctionBodyStatements = 1, ClassHeritageClauses = 0, - ClassMembers = 65, - InterfaceMembers = 65, - EnumMembers = 81, - CaseBlockClauses = 65, - NamedImportsOrExportsElements = 262576, - JsxElementOrFragmentChildren = 131072, - JsxElementAttributes = 131328, - CaseOrDefaultClauseStatements = 81985, - HeritageClauseTypes = 272, - SourceFileStatements = 65537, - Decorators = 24577, - TypeArguments = 26896, - TypeParameters = 26896, - Parameters = 1296, - IndexSignatureParameters = 4432 + ClassMembers = 129, + InterfaceMembers = 129, + EnumMembers = 145, + CaseBlockClauses = 129, + NamedImportsOrExportsElements = 525136, + JsxElementOrFragmentChildren = 262144, + JsxElementAttributes = 262656, + CaseOrDefaultClauseStatements = 163969, + HeritageClauseTypes = 528, + SourceFileStatements = 131073, + Decorators = 49153, + TypeArguments = 53776, + TypeParameters = 53776, + Parameters = 2576, + IndexSignatureParameters = 8848, + JSDocComment = 33 } interface UserPreferences { readonly disableSuggestions?: boolean; diff --git a/tests/cases/fourslash/codeFixInferFromUsageExistingJSDoc.ts b/tests/cases/fourslash/codeFixInferFromUsageExistingJSDoc.ts new file mode 100644 index 00000000000..e2490c57930 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageExistingJSDoc.ts @@ -0,0 +1,95 @@ +/// +// @allowJs: true +// @checkJs: true +// @noImplicitAny: true +// @strictNullChecks: false +// @Filename: important.js + +/////** @param x no types here! */ +/////** +//// * 1 +//// * @param x a duplicate! +//// * @param y yy +//// */ +/////** +//// * 2 +//// * @param z zz +//// */ +////function f(x) { +//// return x * 1 +////} +//// +////var o = { +//// /** 1 +//// * @return First one +//// */ +//// // intrusive comment (should not be deleted) +//// /** 2 +//// * @see also +//// */ +//// /** 3 +//// * @return Second one +//// * @extends {C} nothing really +//// * @class +//// * @this {*} doesn't make sense here +//// * @enum wat +//// */ +//// /** +//// * @typedef {number} Meter or something +//// * @typedef {Object} Position Comment! +//// * @property {number} x what a horrible place for a type +//// * @property {number} y please don't do this +//// */ +//// /** +//// * @template {string} T postfix comment +//// * @callback Action not sure what this will do +//// * @param {T} thing +//// * @returns {string} oh no +//// */ +//// get m() { return undefined } +////} +////o.m = 1 + +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", + newFileContent: +`/** + * 1 + * 2 + * @param {number} x no types here! + * @param x a duplicate! + * @param y yy + * @param z zz + */ +function f(x) { + return x * 1 +} + +var o = { + // intrusive comment (should not be deleted) + /** + * 1 + * 2 + * 3 + * @returns {number} First one + * @see also + * @return Second one + * @extends {C} nothing really + * @class + * @this {*} doesn't make sense here + * @enum {wat} + * @typedef {number} Meter or something + * @typedef {Object} Position Comment! + * @property {number} x what a horrible place for a type + * @property {number} y please don't do this + * @template {string} T postfix comment + * @callback Action not sure what this will do + * @param {T} thing + * @returns {string} oh no + */ + get m() { return undefined } +} +o.m = 1`, +}); + diff --git a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts index 3fd76defd21..2a97b3dca32 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts @@ -7,26 +7,34 @@ // @Filename: important.js ////class C { //// constructor() { -//// [|this.p|] = undefined; +//// /** this is fine */ +//// this.p = undefined; +//// this.q = undefined //// } //// method() { //// this.p.push(1) +//// this.q.push(1); //// } ////} // Note: Should be number[] | undefined, but inference currently privileges assignments // over usage (even when the only result is undefined) and infers only undefined. -verify.codeFix({ - description: "Infer type of 'p' from usage", - index: 2, +verify.codeFixAll({ + fixId: "inferFromUsage", + fixAllDescription: "Infer all types from usage", newFileContent: `class C { constructor() { - /** @type {undefined} */ + /** + * this is fine + * @type {undefined} + */ this.p = undefined; + /** @type {undefined} */ + this.q = undefined } method() { this.p.push(1) + this.q.push(1); } -}` -}); +}`}); diff --git a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts index 308041dd09c..034fe7d0411 100644 --- a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts @@ -19,8 +19,6 @@ verify.codeFix({ newFileContent: `/** * @param {*} y - */ -/** * @param {number} x * @param {number} z */ diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts index 85ee0de9cef..609ab76b787 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts @@ -17,8 +17,8 @@ verify.codeFix({ description: "Infer parameter types from usage", index: 2, newFileContent: -`/** @param {number} a */ -/** +`/** + * @param {number} a * @param {(string | boolean)[]} rest */ function f(a, ...rest){ diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts index 689d12c783a..2c6da348852 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts @@ -14,8 +14,8 @@ verify.codeFix({ description: "Infer parameter types from usage", index: 2, newFileContent: -`/** @param {number} a */ -/** +`/** + * @param {number} a * @param {number[]} rest */ function f(a, ...rest){ diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts index b46bd7dd843..7e87bc3d256 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts @@ -17,8 +17,8 @@ verify.codeFix({ description: "Infer parameter types from usage", index: 4, newFileContent: -`/** @param {number} a */ -/** +`/** + * @param {number} a * @param {string[]} rest */ function f(a: number, ...rest){ diff --git a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts index 0ea9a4d5719..42f5481f143 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts @@ -14,9 +14,9 @@ verify.codeFix({ index: 2, newFileContent: `class C {/** - * @param {number} x - */ - m(x) {return x;}} + * @param {number} x + */ +m(x) {return x;}} var c = new C() c.m(1)`, }); diff --git a/tests/cases/fourslash/formatDocumentWithJSDoc.ts b/tests/cases/fourslash/formatDocumentWithJSDoc.ts new file mode 100644 index 00000000000..4697bbedb71 --- /dev/null +++ b/tests/cases/fourslash/formatDocumentWithJSDoc.ts @@ -0,0 +1,29 @@ +/// + +/////** +//// * JSDoc for things +//// */ +////function f() { +//// /** more +//// jsdoc */ +//// var t; +//// /** +//// * multiline +//// */ +//// var multiline; +////} + +format.document(); + +verify.currentFileContentIs(`/** + * JSDoc for things + */ +function f() { + /** more + jsdoc */ + var t; + /** + * multiline + */ + var multiline; +}`); diff --git a/tests/cases/fourslash/formatDocumentWithTrivia.ts b/tests/cases/fourslash/formatDocumentWithTrivia.ts index d51677be81d..e1716dafa7f 100644 --- a/tests/cases/fourslash/formatDocumentWithTrivia.ts +++ b/tests/cases/fourslash/formatDocumentWithTrivia.ts @@ -1,9 +1,9 @@ /// //// -////// whitespace below +////// 1 below //// -////// whitespace above +////// 2 above //// ////let x; //// @@ -11,25 +11,25 @@ //// ////let y; //// -////// whitespace above again +////// 3 above //// ////while (true) { //// while (true) { //// } //// -//// // whitespace above +//// // 4 above ////} //// -////// whitespace above again +////// 5 above //// //// format.document(); verify.currentFileContentIs(` -// whitespace below +// 1 below -// whitespace above +// 2 above let x; @@ -37,15 +37,15 @@ let x; let y; -// whitespace above again +// 3 above while (true) { while (true) { } - // whitespace above + // 4 above } -// whitespace above again +// 5 above `); diff --git a/tests/cases/fourslash/smartIndentOnFunctionParameters.ts b/tests/cases/fourslash/smartIndentOnFunctionParameters.ts index 1bc42fe2a67..bb2a7940286 100644 --- a/tests/cases/fourslash/smartIndentOnFunctionParameters.ts +++ b/tests/cases/fourslash/smartIndentOnFunctionParameters.ts @@ -2,12 +2,12 @@ ////function foo(a, //// /*2*/b,/*0*/ -//// //comment/*3*/ +//// //ABC/*3*/ //// /*4*/c //// ) { ////}; ////var x = [ -//// /*5*///comment/*1*/ +//// /*5*///DEF/*1*/ //// 1,/*6*/ //// 2/*7*/ ////] @@ -17,14 +17,14 @@ verify.indentationIs(4); goTo.marker("2"); verify.currentLineContentIs(" b,"); goTo.marker("3"); -verify.currentLineContentIs(" //comment"); +verify.currentLineContentIs(" //ABC"); goTo.marker("4"); verify.currentLineContentIs(" c"); goTo.marker("1"); edit.insert("\n"); verify.indentationIs(4); goTo.marker("5"); -verify.currentLineContentIs(" //comment"); +verify.currentLineContentIs(" //DEF"); goTo.marker("6"); verify.currentLineContentIs(" 1,"); goTo.marker("7"); From 42740d66c2621dae3740a5f849fccbe988d0d7ad Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 24 Oct 2018 21:23:47 -0700 Subject: [PATCH 117/262] Improve performance of suggestionDiagnostics for convertToAsyncFunction (#28089) --- .../codefixes/convertToAsyncFunction.ts | 16 +++-- src/services/suggestionDiagnostics.ts | 58 +++++++------------ 2 files changed, 32 insertions(+), 42 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 676a5fb1795..aae1d205de3 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -58,9 +58,9 @@ namespace ts.codefix { const allVarNames: SymbolAndIdentifier[] = []; const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); - const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); + const functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); const constIdentifiers = getConstIdentifiers(synthNamesMap); - const returnStatements = getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); + const returnStatements = functionToConvertRenamed.body && isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : emptyArray; const transformer: Transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { @@ -87,6 +87,14 @@ namespace ts.codefix { } } + function getReturnStatementsWithPromiseHandlers(body: Block): ReadonlyArray { + const res: ReturnStatement[] = []; + forEachReturnStatement(body, ret => { + if (isReturnStatementWithFixablePromiseHandler(ret)) res.push(ret); + }); + return res; + } + // Returns the identifiers that are never reassigned in the refactor function getConstIdentifiers(synthNamesMap: ReadonlyMap): Identifier[] { const constIdentifiers: Identifier[] = []; @@ -442,7 +450,7 @@ namespace ts.codefix { seenReturnStatement = true; } - if (getReturnStatementsWithPromiseHandlers(statement).length) { + if (isReturnStatementWithFixablePromiseHandler(statement)) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } else { @@ -458,7 +466,7 @@ namespace ts.codefix { seenReturnStatement); } else { - const innerRetStmts = getReturnStatementsWithPromiseHandlers(createReturn(funcBody)); + const innerRetStmts = isFixablePromiseHandler(funcBody) ? [createReturn(funcBody)] : emptyArray; const innerCbBody = getInnerTransformationBody(transformer, innerRetStmts, prevArgName); if (innerCbBody.length > 0) { diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index fcbb02d4023..b7b2ce8466d 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -113,59 +113,41 @@ namespace ts { } } - function addConvertToAsyncFunctionDiagnostics(node: FunctionLikeDeclaration, checker: TypeChecker, diags: DiagnosticWithLocation[]): void { - - if (isAsyncFunction(node) || !node.body) { - return; + function addConvertToAsyncFunctionDiagnostics(node: FunctionLikeDeclaration, checker: TypeChecker, diags: Push): void { + if (!isAsyncFunction(node) && + node.body && + isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + diags.push(createDiagnosticForNode( + !node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, + Diagnostics.This_may_be_converted_to_an_async_function)); } + } + function returnsPromise(node: FunctionLikeDeclaration, checker: TypeChecker): boolean { const functionType = checker.getTypeAtLocation(node); - const callSignatures = checker.getSignaturesOfType(functionType, SignatureKind.Call); const returnType = callSignatures.length ? checker.getReturnTypeOfSignature(callSignatures[0]) : undefined; - - if (!returnType || !checker.getPromisedTypeOfPromise(returnType)) { - return; - } - - // collect all the return statements - // check that a property access expression exists in there and that it is a handler - const returnStatements = getReturnStatementsWithPromiseHandlers(node); - if (returnStatements.length > 0) { - diags.push(createDiagnosticForNode(!node.name && isVariableDeclaration(node.parent) && isIdentifier(node.parent.name) ? node.parent.name : node, Diagnostics.This_may_be_converted_to_an_async_function)); - } + return !!returnType && !!checker.getPromisedTypeOfPromise(returnType); } function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator: Node): Node { return isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; } - /** @internal */ - export function getReturnStatementsWithPromiseHandlers(node: Node): ReturnStatement[] { - const returnStatements: ReturnStatement[] = []; - if (isFunctionLike(node)) { - forEachChild(node, visit); - } - else { - visit(node); - } + function hasReturnStatementWithPromiseHandler(body: Block): boolean { + return !!forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); + } - function visit(child: Node) { - if (isFunctionLike(child)) { - return; - } - - if (isReturnStatement(child) && child.expression && isFixablePromiseHandler(child.expression)) { - returnStatements.push(child); - } - - forEachChild(child, visit); - } - return returnStatements; + /* @internal */ + export function isReturnStatementWithFixablePromiseHandler(node: Node): node is ReturnStatement { + return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); } // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - function isFixablePromiseHandler(node: Node): boolean { + /* @internal */ + export function isFixablePromiseHandler(node: Node): boolean { // ensure outermost call exists and is a promise handler if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { return false; From 0aac87fd60e74fc1c15d4de6a5afa37a2d26a18f Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Thu, 25 Oct 2018 09:28:04 -0700 Subject: [PATCH 118/262] Update user baselines (#28129) --- .../user/chrome-devtools-frontend.log | 44 +++++-------------- 1 file changed, 12 insertions(+), 32 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 597f7977219..9eeb095f316 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -1,16 +1,16 @@ Exit Code: 1 Standard output: -../../../../built/local/lib.dom.d.ts(2354,11): error TS2300: Duplicate identifier 'CSSRule'. -../../../../built/local/lib.dom.d.ts(2373,13): error TS2300: Duplicate identifier 'CSSRule'. -../../../../built/local/lib.dom.d.ts(3150,11): error TS2300: Duplicate identifier 'Comment'. -../../../../built/local/lib.dom.d.ts(3153,13): error TS2300: Duplicate identifier 'Comment'. -../../../../built/local/lib.dom.d.ts(4846,11): error TS2300: Duplicate identifier 'Event'. -../../../../built/local/lib.dom.d.ts(4905,13): error TS2300: Duplicate identifier 'Event'. -../../../../built/local/lib.dom.d.ts(11124,11): error TS2300: Duplicate identifier 'Position'. -../../../../built/local/lib.dom.d.ts(11819,11): error TS2300: Duplicate identifier 'Request'. -../../../../built/local/lib.dom.d.ts(11899,13): error TS2300: Duplicate identifier 'Request'. -../../../../built/local/lib.dom.d.ts(16316,11): error TS2300: Duplicate identifier 'Window'. -../../../../built/local/lib.dom.d.ts(16447,13): error TS2300: Duplicate identifier 'Window'. +../../../../built/local/lib.dom.d.ts(2358,11): error TS2300: Duplicate identifier 'CSSRule'. +../../../../built/local/lib.dom.d.ts(2377,13): error TS2300: Duplicate identifier 'CSSRule'. +../../../../built/local/lib.dom.d.ts(3154,11): error TS2300: Duplicate identifier 'Comment'. +../../../../built/local/lib.dom.d.ts(3157,13): error TS2300: Duplicate identifier 'Comment'. +../../../../built/local/lib.dom.d.ts(4850,11): error TS2300: Duplicate identifier 'Event'. +../../../../built/local/lib.dom.d.ts(4909,13): error TS2300: Duplicate identifier 'Event'. +../../../../built/local/lib.dom.d.ts(11128,11): error TS2300: Duplicate identifier 'Position'. +../../../../built/local/lib.dom.d.ts(11823,11): error TS2300: Duplicate identifier 'Request'. +../../../../built/local/lib.dom.d.ts(11903,13): error TS2300: Duplicate identifier 'Request'. +../../../../built/local/lib.dom.d.ts(16320,11): error TS2300: Duplicate identifier 'Window'. +../../../../built/local/lib.dom.d.ts(16451,13): error TS2300: Duplicate identifier 'Window'. ../../../../built/local/lib.es5.d.ts(1406,11): error TS2300: Duplicate identifier 'ArrayLike'. ../../../../built/local/lib.es5.d.ts(1442,6): error TS2300: Duplicate identifier 'Record'. ../../../../node_modules/@types/node/index.d.ts(150,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type '{}', but here has type 'NodeModule'. @@ -366,12 +366,9 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(4 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(450,37): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(457,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(484,36): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(566,10): error TS2322: Type '{ transform: string; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ transform: string; }' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(566,42): error TS2322: Type '{ transform: string; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ transform: string; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(571,18): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(587,44): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(588,9): error TS2367: This condition will always return 'false' since the types 'AnimationPlayState' and '"pending"' have no overlap. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(589,20): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(605,38): error TS2339: Property 'x' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(612,41): error TS2339: Property 'x' does not exist on type 'Event'. @@ -3617,10 +3614,6 @@ node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(217,25) node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(241,27): error TS2339: Property 'focus' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(251,13): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(251,39): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(253,24): error TS2322: Type '{ opacity: number; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ opacity: number; }' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(253,38): error TS2322: Type '{ opacity: number; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ opacity: number; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(254,13): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(259,36): error TS2694: Namespace 'ColorPicker.Spectrum' has no exported member 'Palette'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(272,22): error TS2339: Property '__mutable' does not exist on type 'Element'. @@ -5538,12 +5531,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/PropertiesWidget.js(153 node_modules/chrome-devtools-frontend/front_end/elements/PropertiesWidget.js(162,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(29,25): error TS2339: Property 'property' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(43,42): error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(46,11): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(47,11): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/elements/StylePropertyHighlighter.js(47,69): error TS2322: Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string | string[] | Keyframe'. - Type '{ offset: number; backgroundColor: string; }' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(35,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(50,51): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(69,32): error TS2339: Property '_instance' does not exist on type 'typeof StylesSidebarPane'. @@ -6083,13 +6070,6 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(429,1 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(529,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(544,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(551,12): error TS2339: Property '_fire' does not exist on type 'EventSinkImpl'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(768,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(769,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(770,19): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(771,19): error TS2339: Property 'network' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(772,19): error TS2339: Property 'panels' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(773,19): error TS2339: Property 'panels' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(786,68): error TS2339: Property 'inspectedWindow' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(789,21): error TS2339: Property 'exposeWebInspectorNamespace' does not exist on type 'ExtensionDescriptor'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(790,12): error TS2339: Property 'webInspector' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(232,23): error TS2339: Property 'style' does not exist on type 'Element'. From 05716a74a50533796e82388d861cfba927f3fdea Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 25 Oct 2018 10:19:57 -0700 Subject: [PATCH 119/262] Add support for configuration inheritance via packages (#27348) * Add support for configuration inheritance via packages * Fix lint * Propagate trace into config parse hosts --- src/compiler/commandLineParser.ts | 28 +++--- src/compiler/moduleNameResolver.ts | 64 +++++++++---- src/compiler/program.ts | 3 +- src/compiler/types.ts | 1 + src/compiler/watch.ts | 3 +- .../unittests/configurationExtension.ts | 94 +++++++++++++++++-- .../reference/api/tsserverlibrary.d.ts | 1 + tests/baselines/reference/api/typescript.d.ts | 1 + 8 files changed, 156 insertions(+), 39 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 5a6ee2ec619..968e5bb756e 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -2191,20 +2191,24 @@ namespace ts { errors: Push, createDiagnostic: (message: DiagnosticMessage, arg1?: string) => Diagnostic) { extendedConfig = normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; - } - let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) { - extendedConfigPath = `${extendedConfigPath}.json`; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); - return undefined; + if (isRootedDiskPath(extendedConfig) || startsWith(extendedConfig, "./") || startsWith(extendedConfig, "../")) { + let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !endsWith(extendedConfigPath, Extension.Json)) { + extendedConfigPath = `${extendedConfigPath}.json`; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } } + return extendedConfigPath; } - return extendedConfigPath; + // If the path isn't a rooted or relative path, resolve like a module + const resolved = nodeModuleNameResolver(extendedConfig, combinePaths(basePath, "tsconfig.json"), { moduleResolution: ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true); + if (resolved.resolvedModule) { + return resolved.resolvedModule.resolvedFileName; + } + errors.push(createDiagnostic(Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; } function getExtendedConfig( diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 99b65c8946e..4d32cae86f7 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -62,6 +62,7 @@ namespace ts { TypeScript, /** '.ts', '.tsx', or '.d.ts' */ JavaScript, /** '.js' or '.jsx' */ Json, /** '.json' */ + TSConfig, /** '.json' with `tsconfig` used instead of `index` */ DtsOnly /** Only '.d.ts' */ } @@ -98,6 +99,7 @@ namespace ts { types?: string; typesVersions?: MapLike>; main?: string; + tsconfig?: string; } interface PackageJson extends PackageJsonPathFields { @@ -126,7 +128,7 @@ namespace ts { return value; } - function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { + function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { const fileName = readPackageJsonField(jsonContent, fieldName, "string", state); if (fileName === undefined) return; const path = normalizePath(combinePaths(baseDirectory, fileName)); @@ -141,6 +143,10 @@ namespace ts { || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); } + function readPackageJsonTSConfigField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state); + } + function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); } @@ -853,25 +859,27 @@ namespace ts { return resolvedModule && resolvedModule.resolvedFileName; } + const jsOnlyExtensions = [Extensions.JavaScript]; + const tsExtensions = [Extensions.TypeScript, Extensions.JavaScript]; + const tsPlusJsonExtensions = [...tsExtensions, Extensions.Json]; + const tsconfigExtensions = [Extensions.TSConfig]; function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*redirectedReference*/ undefined, /*jsOnly*/ true); + return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined); } - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, redirectedReference, /*jsOnly*/ false); + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations; + /* @internal */ export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations; // tslint:disable-line unified-signatures + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference); } - function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, extensions: Extensions[], redirectedReference: ResolvedProjectReference | undefined): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; - const result = jsOnly ? - tryResolve(Extensions.JavaScript) : - (tryResolve(Extensions.TypeScript) || - tryResolve(Extensions.JavaScript) || - (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); + const result = forEach(extensions, ext => tryResolve(ext)); if (result && result.value) { const { resolved, isExternalLibraryImport } = result.value; return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); @@ -1019,9 +1027,9 @@ namespace ts { * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { - if (extensions === Extensions.Json) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { const extensionLess = tryRemoveExtension(candidate, Extension.Json); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); + return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" @@ -1059,6 +1067,7 @@ namespace ts { return tryExtension(Extension.Ts) || tryExtension(Extension.Tsx) || tryExtension(Extension.Dts); case Extensions.JavaScript: return tryExtension(Extension.Js) || tryExtension(Extension.Jsx); + case Extensions.TSConfig: case Extensions.Json: return tryExtension(Extension.Json); } @@ -1156,11 +1165,27 @@ namespace ts { } function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, jsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined { - const packageFile = jsonContent && (extensions !== Extensions.JavaScript && extensions !== Extensions.Json - ? readPackageJsonTypesFields(jsonContent, candidate, state) || - // When resolving typescript modules, try resolving using main field as well - (extensions === Extensions.TypeScript ? readPackageJsonMainField(jsonContent, candidate, state) : undefined) - : readPackageJsonMainField(jsonContent, candidate, state)); + let packageFile: string | undefined; + if (jsonContent) { + switch (extensions) { + case Extensions.JavaScript: + case Extensions.Json: + packageFile = readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.TypeScript: + // When resolving typescript modules, try resolving using main field as well + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state); + break; + case Extensions.DtsOnly: + packageFile = readPackageJsonTypesFields(jsonContent, candidate, state); + break; + case Extensions.TSConfig: + packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state); + break; + default: + return Debug.assertNever(extensions); + } + } const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { const fromFile = tryFile(candidate, onlyRecordFailures, state); @@ -1182,7 +1207,7 @@ namespace ts { const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : undefined; const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host); - const indexPath = combinePaths(candidate, "index"); + const indexPath = combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index"); if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); @@ -1213,6 +1238,7 @@ namespace ts { switch (extensions) { case Extensions.JavaScript: return extension === Extension.Js || extension === Extension.Jsx; + case Extensions.TSConfig: case Extensions.Json: return extension === Extension.Json; case Extensions.TypeScript: @@ -1264,7 +1290,7 @@ namespace ts { if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { + if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) { const nodeModulesAtTypes = combinePaths(nodeModulesFolder, "@types"); let nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes, state.host)) { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 9424fc98bc3..955604e8e62 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2987,7 +2987,8 @@ namespace ts { readFile: f => host.readFile(f), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), - onUnRecoverableConfigFileDiagnostic: () => undefined + onUnRecoverableConfigFileDiagnostic: () => undefined, + trace: host.trace ? (s) => host.trace!(s) : undefined }; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 85a51db27c5..d382436ae42 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2802,6 +2802,7 @@ namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 7c9c0a28a34..427ec1e4bac 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -484,7 +484,8 @@ namespace ts { fileExists: path => host.fileExists(path), readFile, getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? s => host.trace!(s) : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames diff --git a/src/testRunner/unittests/configurationExtension.ts b/src/testRunner/unittests/configurationExtension.ts index fbb4950b9a5..57c899eb5a8 100644 --- a/src/testRunner/unittests/configurationExtension.ts +++ b/src/testRunner/unittests/configurationExtension.ts @@ -4,6 +4,83 @@ namespace ts { cwd, files: { [root]: { + "dev/node_modules/config-box/package.json": JSON.stringify({ + name: "config-box", + version: "1.0.0", + tsconfig: "./strict.json" + }), + "dev/node_modules/config-box/strict.json": JSON.stringify({ + compilerOptions: { + strict: true, + } + }), + "dev/node_modules/config-box/unstrict.json": JSON.stringify({ + compilerOptions: { + strict: false, + } + }), + "dev/tsconfig.extendsBox.json": JSON.stringify({ + extends: "config-box", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsStrict.json": JSON.stringify({ + extends: "config-box/strict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsUnStrict.json": JSON.stringify({ + extends: "config-box/unstrict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsStrictExtension.json": JSON.stringify({ + extends: "config-box/strict.json", + files: [ + "main.ts", + ] + }), + "dev/node_modules/config-box-implied/package.json": JSON.stringify({ + name: "config-box-implied", + version: "1.0.0", + }), + "dev/node_modules/config-box-implied/tsconfig.json": JSON.stringify({ + compilerOptions: { + strict: true, + } + }), + "dev/node_modules/config-box-implied/unstrict/tsconfig.json": JSON.stringify({ + compilerOptions: { + strict: false, + } + }), + "dev/tsconfig.extendsBoxImplied.json": JSON.stringify({ + extends: "config-box-implied", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedUnstrict.json": JSON.stringify({ + extends: "config-box-implied/unstrict", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedUnstrictExtension.json": JSON.stringify({ + extends: "config-box-implied/unstrict/tsconfig", + files: [ + "main.ts", + ] + }), + "dev/tsconfig.extendsBoxImpliedPath.json": JSON.stringify({ + extends: "config-box-implied/tsconfig.json", + files: [ + "main.ts", + ] + }), "dev/tsconfig.json": JSON.stringify({ extends: "./configs/base", files: [ @@ -226,12 +303,6 @@ namespace ts { messageText: `Compiler option 'extends' requires a value of type string.` }]); - testFailure("can error when 'extends' is neither relative nor rooted.", "extends2.json", [{ - code: 18001, - category: DiagnosticCategory.Error, - messageText: `A path in an 'extends' option must be relative or rooted, but 'configs/base' is not.` - }]); - testSuccess("can overwrite compiler options using extended 'null'", "configs/third.json", { allowJs: true, noImplicitAny: true, @@ -259,6 +330,17 @@ namespace ts { combinePaths(basePath, "tests/utils.ts") ]); + describe("finding extended configs from node_modules", () => { + testSuccess("can lookup via tsconfig field", "tsconfig.extendsBox.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via package-relative path", "tsconfig.extendsStrict.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via non-redirected-to package-relative path", "tsconfig.extendsUnStrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via package-relative path with extension", "tsconfig.extendsStrictExtension.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig", "tsconfig.extendsBoxImplied.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory", "tsconfig.extendsBoxImpliedUnstrict.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory with name", "tsconfig.extendsBoxImpliedUnstrictExtension.json", { strict: false }, [combinePaths(basePath, "main.ts")]); + testSuccess("can lookup via an implicit tsconfig in a package-relative directory with extension", "tsconfig.extendsBoxImpliedPath.json", { strict: true }, [combinePaths(basePath, "main.ts")]); + }); + it("adds extendedSourceFiles only once", () => { const sourceFile = readJsonConfigFile("configs/fourth.json", (path) => host.readFile(path)); const dir = combinePaths(basePath, "configs"); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 324d76f2f87..15606263db0 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1762,6 +1762,7 @@ declare namespace ts { */ fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** * Branded string for keeping track of when we've turned an ambiguous path diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index c95f50f6ca0..ad934eef56b 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1762,6 +1762,7 @@ declare namespace ts { */ fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** * Branded string for keeping track of when we've turned an ambiguous path From efc831e0ba66fb2c44acfc150d359a9a8cf56cab Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 25 Oct 2018 12:25:33 -0700 Subject: [PATCH 120/262] At '.' in array literal, don't close the array (#28120) --- src/compiler/parser.ts | 6 ++++-- .../completionsDotInArrayLiteralInObjectLiteral.ts | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index c88aebe799f..edb4835ae5f 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1518,8 +1518,10 @@ namespace ts { case ParsingContext.TypeParameters: return isIdentifier(); case ParsingContext.ArrayLiteralMembers: - if (token() === SyntaxKind.CommaToken) { - return true; + switch (token()) { + case SyntaxKind.CommaToken: + case SyntaxKind.DotToken: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) + return true; } // falls through case ParsingContext.ArgumentExpressions: diff --git a/tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts b/tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts new file mode 100644 index 00000000000..8d679b36168 --- /dev/null +++ b/tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts @@ -0,0 +1,11 @@ +/// + +////const o = { x: [[|.|][||]/**/ + +const [r0, r1] = test.ranges(); +verify.getSyntacticDiagnostics([ + { code: 1109, message: "Expression expected.", range: r0 }, + { code: 1003, message: "Identifier expected.", range: r1 }, +]); + +verify.completions({ marker: "", exact: undefined }); From 070218f8283ff08b2326f60b2798f0cd7bbe26bc Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 25 Oct 2018 15:03:46 -0700 Subject: [PATCH 121/262] Remove DirectoryOfFailedLookupWatch#ignore, use DirectoryOfFailedLookupWatch | undefined (#28091) --- src/compiler/resolutionCache.ts | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index b11de69b0e2..b22d90a76f6 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -69,7 +69,6 @@ namespace ts { dir: string; dirPath: Path; nonRecursive?: boolean; - ignore?: true; } export const maxNumberOfFilesToIterateForInvalidation = 256; @@ -401,14 +400,7 @@ namespace ts { return true; } - function filterFSRootDirectoriesToWatch(watchPath: DirectoryOfFailedLookupWatch, dirPath: Path): DirectoryOfFailedLookupWatch { - if (!canWatchDirectory(dirPath)) { - watchPath.ignore = true; - } - return watchPath; - } - - function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch { + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation: string, failedLookupLocationPath: Path): DirectoryOfFailedLookupWatch | undefined { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { // Ensure failed look up is normalized path failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); @@ -430,7 +422,7 @@ namespace ts { ); } - function getDirectoryToWatchFromFailedLookupLocationDirectory(dir: string, dirPath: Path) { + function getDirectoryToWatchFromFailedLookupLocationDirectory(dir: string, dirPath: Path): DirectoryOfFailedLookupWatch | undefined { // If directory path contains node module, get the most parent node_modules directory for watching while (pathContainsNodeModules(dirPath)) { dir = getDirectoryPath(dir); @@ -439,7 +431,7 @@ namespace ts { // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { - return filterFSRootDirectoriesToWatch({ dir, dirPath }, getDirectoryPath(dirPath)); + return canWatchDirectory(getDirectoryPath(dirPath)) ? { dir, dirPath } : undefined; } let nonRecursive = true; @@ -459,7 +451,7 @@ namespace ts { } } - return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive }, dirPath); + return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive } : undefined; } function isPathWithDefaultFailedLookupExtension(path: Path) { @@ -491,8 +483,9 @@ namespace ts { let setAtRoot = false; for (const failedLookupLocation of failedLookupLocations) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const { dir, dirPath, nonRecursive, ignore } = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (!ignore) { + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; // If the failed lookup location path is not one of the supported extensions, // store it in the custom path if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { @@ -551,8 +544,9 @@ namespace ts { let removeAtRoot = false; for (const failedLookupLocation of failedLookupLocations) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const { dirPath, ignore } = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); - if (!ignore) { + const toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath); + if (toWatch) { + const { dirPath } = toWatch; const refCount = customFailedLookupPaths.get(failedLookupLocationPath); if (refCount) { if (refCount === 1) { @@ -738,8 +732,8 @@ namespace ts { if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } - const { dirPath, ignore } = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; + const toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath); + return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined; } function createTypeRootsWatch(typeRootPath: Path, typeRoot: string): FileWatcher { From dc9a066f65f713daefbb61ecd6b0557af430ab3d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 25 Oct 2018 15:08:06 -0700 Subject: [PATCH 122/262] Do not merge commonJS exports into an alias (#28133) * Do not merge commonsjs exports onto an alias getCommonJSExportEquals merges export assignments and export property assignments. Something like this, which has no equivalent structure in TS: ```js module.exports = function() { } module.exports.expando = 1 ``` However, it is sometimes called with an alias, when its parent, resolveExternalModuleSymbol, is called with dontResolveAlias: true, and when the initialiser of the export assignment is an alias: ```js function alias() { } module.exports = alias module.exports.expando = 1 ``` In this case, (1) the actual value `alias` will have already merged in a previous call to getCommonJSExportEquals and (2) getTypeOfSymbol will follow the alias symbol to get the right type. So getCommonJSExportEquals should do nothing in this case. This bug manifests in the code for dynamic imports, which calls getTypeOfSymbol on the incorrectly merged alias, which now has enough value flags--Function, for example--to take the wrong branch and subsequently crash. * Update baselines --- src/compiler/checker.ts | 2 +- ...errorForConflictingExportEqualsValue.types | 2 +- .../moduleExportAliasImported.symbols | 19 +++++++++++++++ .../reference/moduleExportAliasImported.types | 23 +++++++++++++++++++ .../salsa/moduleExportAliasImported.ts | 12 ++++++++++ 5 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/moduleExportAliasImported.symbols create mode 100644 tests/baselines/reference/moduleExportAliasImported.types create mode 100644 tests/cases/conformance/salsa/moduleExportAliasImported.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4305227dab7..49caad2116e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2362,7 +2362,7 @@ namespace ts { } function getCommonJsExportEquals(exported: Symbol | undefined, moduleSymbol: Symbol): Symbol | undefined { - if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports!.size === 1) { + if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports!.size === 1 || exported.flags & SymbolFlags.Alias) { return exported; } const merged = cloneSymbol(exported); diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.types b/tests/baselines/reference/errorForConflictingExportEqualsValue.types index b9915169120..5d2b63f2e9a 100644 --- a/tests/baselines/reference/errorForConflictingExportEqualsValue.types +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.types @@ -6,6 +6,6 @@ export = x; >x : any import("./a"); ->import("./a") : Promise +>import("./a") : Promise >"./a" : "./a" diff --git a/tests/baselines/reference/moduleExportAliasImported.symbols b/tests/baselines/reference/moduleExportAliasImported.symbols new file mode 100644 index 00000000000..9649cc0a3b6 --- /dev/null +++ b/tests/baselines/reference/moduleExportAliasImported.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/salsa/bug28014.js === +exports.version = 1 +>exports.version : Symbol(version) +>exports : Symbol(version, Decl(bug28014.js, 0, 0)) +>version : Symbol(version, Decl(bug28014.js, 0, 0)) + +function alias() { } +>alias : Symbol(alias, Decl(bug28014.js, 0, 19)) + +module.exports = alias +>module.exports : Symbol("tests/cases/conformance/salsa/bug28014", Decl(bug28014.js, 0, 0)) +>module : Symbol(export=, Decl(bug28014.js, 1, 20)) +>exports : Symbol(export=, Decl(bug28014.js, 1, 20)) +>alias : Symbol(alias, Decl(bug28014.js, 0, 19)) + +=== tests/cases/conformance/salsa/importer.js === +import('./bug28014') +>'./bug28014' : Symbol("tests/cases/conformance/salsa/bug28014", Decl(bug28014.js, 0, 0)) + diff --git a/tests/baselines/reference/moduleExportAliasImported.types b/tests/baselines/reference/moduleExportAliasImported.types new file mode 100644 index 00000000000..9691acfab22 --- /dev/null +++ b/tests/baselines/reference/moduleExportAliasImported.types @@ -0,0 +1,23 @@ +=== tests/cases/conformance/salsa/bug28014.js === +exports.version = 1 +>exports.version = 1 : 1 +>exports.version : number +>exports : typeof alias +>version : number +>1 : 1 + +function alias() { } +>alias : typeof alias + +module.exports = alias +>module.exports = alias : typeof alias +>module.exports : typeof alias +>module : { "tests/cases/conformance/salsa/bug28014": typeof alias; } +>exports : typeof alias +>alias : typeof alias + +=== tests/cases/conformance/salsa/importer.js === +import('./bug28014') +>import('./bug28014') : Promise<() => void> +>'./bug28014' : "./bug28014" + diff --git a/tests/cases/conformance/salsa/moduleExportAliasImported.ts b/tests/cases/conformance/salsa/moduleExportAliasImported.ts new file mode 100644 index 00000000000..95c02981382 --- /dev/null +++ b/tests/cases/conformance/salsa/moduleExportAliasImported.ts @@ -0,0 +1,12 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @target: esnext +// @module: esnext +// @Filename: bug28014.js +exports.version = 1 +function alias() { } +module.exports = alias + +// @Filename: importer.js +import('./bug28014') From 1979570f73e4117035325405f8d4db290f4fb432 Mon Sep 17 00:00:00 2001 From: csigs Date: Thu, 25 Oct 2018 23:45:15 +0000 Subject: [PATCH 123/262] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index c735834474e..087c7c6a051 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -3784,7 +3784,7 @@ - + @@ -3793,7 +3793,7 @@ - + @@ -3802,7 +3802,7 @@ - + @@ -5437,7 +5437,7 @@ - + From 3fb8873bc21d5990325f7addc74d543e38c0e2af Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Fri, 26 Oct 2018 18:50:12 +0200 Subject: [PATCH 124/262] don't resolve import types in JSDoc of TS files (#28158) --- src/compiler/program.ts | 8 ++++---- tests/baselines/reference/jsdocInTypeScript.errors.txt | 4 ++++ tests/baselines/reference/jsdocInTypeScript.js | 7 +++++++ tests/baselines/reference/jsdocInTypeScript.symbols | 6 ++++++ tests/baselines/reference/jsdocInTypeScript.trace.json | 1 + tests/baselines/reference/jsdocInTypeScript.types | 8 ++++++++ tests/cases/compiler/jsdocInTypeScript.ts | 7 +++++++ 7 files changed, 37 insertions(+), 4 deletions(-) create mode 100644 tests/baselines/reference/jsdocInTypeScript.trace.json diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 8ed9f82af71..3e927c0b75f 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1946,7 +1946,7 @@ namespace ts { function collectDynamicImportOrRequireCalls(file: SourceFile) { const r = /import|require/g; while (r.exec(file.text) !== null) { - const node = getTokenAtPosition(file, r.lastIndex); + const node = getNodeAtPosition(file, r.lastIndex); if (isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { imports = append(imports, node.arguments[0]); } @@ -1960,8 +1960,8 @@ namespace ts { } } - /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile: SourceFile, position: number): Node { + /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */ + function getNodeAtPosition(sourceFile: SourceFile, position: number): Node { let current: Node = sourceFile; const getContainingChild = (child: Node) => { if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === SyntaxKind.EndOfFileToken)))) { @@ -1969,7 +1969,7 @@ namespace ts { } }; while (true) { - const child = hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + const child = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); if (!child) { return current; } diff --git a/tests/baselines/reference/jsdocInTypeScript.errors.txt b/tests/baselines/reference/jsdocInTypeScript.errors.txt index c8972bb0f0a..24f80e1c889 100644 --- a/tests/baselines/reference/jsdocInTypeScript.errors.txt +++ b/tests/baselines/reference/jsdocInTypeScript.errors.txt @@ -71,4 +71,8 @@ tests/cases/compiler/jsdocInTypeScript.ts(42,12): error TS2503: Cannot find name /** @enum {string} */ var E = {}; E[""]; + + // make sure import types in JSDoc are not resolved + /** @type {import("should-not-be-resolved").Type} */ + var v = import(String()); \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.js b/tests/baselines/reference/jsdocInTypeScript.js index ebff5629c37..037d655ccf0 100644 --- a/tests/baselines/reference/jsdocInTypeScript.js +++ b/tests/baselines/reference/jsdocInTypeScript.js @@ -51,6 +51,10 @@ const obj = { foo: (a, b) => a + b }; /** @enum {string} */ var E = {}; E[""]; + +// make sure import types in JSDoc are not resolved +/** @type {import("should-not-be-resolved").Type} */ +var v = import(String()); //// [jsdocInTypeScript.js] @@ -86,3 +90,6 @@ var obj = { foo: function (a, b) { return a + b; } }; /** @enum {string} */ var E = {}; E[""]; +// make sure import types in JSDoc are not resolved +/** @type {import("should-not-be-resolved").Type} */ +var v = Promise.resolve().then(function () { return require(String()); }); diff --git a/tests/baselines/reference/jsdocInTypeScript.symbols b/tests/baselines/reference/jsdocInTypeScript.symbols index c65d1215abe..3b56fe3b848 100644 --- a/tests/baselines/reference/jsdocInTypeScript.symbols +++ b/tests/baselines/reference/jsdocInTypeScript.symbols @@ -90,3 +90,9 @@ var E = {}; E[""]; >E : Symbol(E, Decl(jsdocInTypeScript.ts, 50, 3)) +// make sure import types in JSDoc are not resolved +/** @type {import("should-not-be-resolved").Type} */ +var v = import(String()); +>v : Symbol(v, Decl(jsdocInTypeScript.ts, 55, 3)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 1 more) + diff --git a/tests/baselines/reference/jsdocInTypeScript.trace.json b/tests/baselines/reference/jsdocInTypeScript.trace.json new file mode 100644 index 00000000000..0637a088a01 --- /dev/null +++ b/tests/baselines/reference/jsdocInTypeScript.trace.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.types b/tests/baselines/reference/jsdocInTypeScript.types index 010efb68b7a..0b4bb8192cb 100644 --- a/tests/baselines/reference/jsdocInTypeScript.types +++ b/tests/baselines/reference/jsdocInTypeScript.types @@ -103,3 +103,11 @@ E[""]; >E : {} >"" : "" +// make sure import types in JSDoc are not resolved +/** @type {import("should-not-be-resolved").Type} */ +var v = import(String()); +>v : Promise +>import(String()) : Promise +>String() : string +>String : StringConstructor + diff --git a/tests/cases/compiler/jsdocInTypeScript.ts b/tests/cases/compiler/jsdocInTypeScript.ts index 4d1f0fbbe42..be485f59c55 100644 --- a/tests/cases/compiler/jsdocInTypeScript.ts +++ b/tests/cases/compiler/jsdocInTypeScript.ts @@ -1,3 +1,6 @@ +// @lib: es2015 +// @traceResolution: true + // JSDoc typedef tags are not bound TypeScript files. /** @typedef {function} T */ declare const x: T; @@ -50,3 +53,7 @@ const obj = { foo: (a, b) => a + b }; /** @enum {string} */ var E = {}; E[""]; + +// make sure import types in JSDoc are not resolved +/** @type {import("should-not-be-resolved").Type} */ +var v = import(String()); From 14c328e706f37446306484cb5770fa2d06c6875c Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Fri, 26 Oct 2018 09:55:05 -0700 Subject: [PATCH 125/262] Update user baselines (#28157) --- .../user/chrome-devtools-frontend.log | 82 ------------------- 1 file changed, 82 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 9eeb095f316..7e4641c5f1e 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -768,7 +768,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21003,8): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21007,8): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21011,8): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21017,1): error TS2323: Cannot redeclare exported variable 'deflate'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21022,19): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21026,23): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21034,19): error TS2350: Only a void function can be called with the 'new' keyword. @@ -847,29 +846,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23247,18): error TS2339: Property 'length' does not exist on type 'Buffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23247,37): error TS2339: Property 'length' does not exist on type 'Buffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23256,26): error TS2339: Property 'length' does not exist on type 'Buffer'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23459,1): error TS2323: Cannot redeclare exported variable 'isArray'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23464,1): error TS2323: Cannot redeclare exported variable 'isBoolean'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23469,1): error TS2323: Cannot redeclare exported variable 'isNull'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23474,1): error TS2323: Cannot redeclare exported variable 'isNullOrUndefined'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23479,1): error TS2323: Cannot redeclare exported variable 'isNumber'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23484,1): error TS2323: Cannot redeclare exported variable 'isString'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23489,1): error TS2323: Cannot redeclare exported variable 'isSymbol'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23494,1): error TS2323: Cannot redeclare exported variable 'isUndefined'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23499,1): error TS2323: Cannot redeclare exported variable 'isRegExp'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23504,1): error TS2323: Cannot redeclare exported variable 'isObject'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23509,1): error TS2323: Cannot redeclare exported variable 'isDate'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23514,1): error TS2323: Cannot redeclare exported variable 'isError'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23519,1): error TS2323: Cannot redeclare exported variable 'isFunction'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23529,1): error TS2323: Cannot redeclare exported variable 'isPrimitive'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23531,1): error TS2323: Cannot redeclare exported variable 'isBuffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23601,5): error TS2339: Property 'context' does not exist on type 'Error'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24073,1): error TS2323: Cannot redeclare exported variable 'Buf8'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24074,1): error TS2323: Cannot redeclare exported variable 'Buf16'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24075,1): error TS2323: Cannot redeclare exported variable 'Buf32'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24078,1): error TS2323: Cannot redeclare exported variable 'Buf8'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24079,1): error TS2323: Cannot redeclare exported variable 'Buf16'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24080,1): error TS2323: Cannot redeclare exported variable 'Buf32'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(26059,1): error TS2323: Cannot redeclare exported variable 'deflate'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27915,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27918,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. @@ -880,7 +857,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27929,20): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27956,16): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28222,51): error TS2300: Duplicate identifier '_read'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28457,20): error TS2339: Property 'emit' does not exist on type 'Readable'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28533,20): error TS2300: Duplicate identifier '_read'. @@ -921,23 +897,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30311,40): error TS2345: Argument of type '(x: string) => string | number' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30729,1): error TS2323: Cannot redeclare exported variable 'isArray'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30734,1): error TS2323: Cannot redeclare exported variable 'isBoolean'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30739,1): error TS2323: Cannot redeclare exported variable 'isNull'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30744,1): error TS2323: Cannot redeclare exported variable 'isNullOrUndefined'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30749,1): error TS2323: Cannot redeclare exported variable 'isNumber'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30754,1): error TS2323: Cannot redeclare exported variable 'isString'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30759,1): error TS2323: Cannot redeclare exported variable 'isSymbol'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30764,1): error TS2323: Cannot redeclare exported variable 'isUndefined'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30769,1): error TS2323: Cannot redeclare exported variable 'isRegExp'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30774,1): error TS2323: Cannot redeclare exported variable 'isObject'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30779,1): error TS2323: Cannot redeclare exported variable 'isDate'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30785,1): error TS2323: Cannot redeclare exported variable 'isError'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30790,1): error TS2323: Cannot redeclare exported variable 'isFunction'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30800,1): error TS2323: Cannot redeclare exported variable 'isPrimitive'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30802,1): error TS2323: Cannot redeclare exported variable 'isBuffer'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30828,1): error TS2323: Cannot redeclare exported variable 'log'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31089,1): error TS2323: Cannot redeclare exported variable 'log'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31094,37): error TS2304: Cannot find name 'chrome'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31095,21): error TS2304: Cannot find name 'chrome'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31096,1): error TS2304: Cannot find name 'chrome'. @@ -945,14 +904,10 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31124,56): error TS2339: Property 'process' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31130,128): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31132,62): error TS2339: Property 'firebug' does not exist on type 'Console'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31289,1): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31290,1): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31343,6): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31344,6): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31345,6): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31382,17): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31410,1): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31411,1): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39766,1): error TS2304: Cannot find name 'axe'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39802,8): error TS2339: Property 'requestFileSystem' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39802,33): error TS2339: Property 'requestFileSystem' does not exist on type 'Window'. @@ -2830,14 +2785,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,11): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,32): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60268,1): error TS2304: Cannot find name 'define'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60346,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60397,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60430,8): error TS2339: Property 'errors' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60436,1): error TS2323: Cannot redeclare exported variable 'Syntax'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60446,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60601,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60602,1): error TS2323: Cannot redeclare exported variable 'Syntax'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60688,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60728,13): error TS2339: Property 'match' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,6): error TS2339: Property 'scanner' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,25): error TS2339: Property 'startMarker' does not exist on type 'JSXParser'. @@ -3000,11 +2948,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61200,9): error TS2339: Property 'config' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61201,6): error TS2339: Property 'tokens' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61209,62): error TS2339: Property 'match' does not exist on type 'JSXParser'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61221,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61281,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61386,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61407,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62087,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62832,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'id' must be of type 'string', but here has type 'any'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63482,12): error TS2339: Property 'message' does not exist on type '{ simple: boolean; paramSet: {}; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63483,39): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; paramSet: {}; }'. @@ -3016,19 +2959,12 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64518,9): error TS2551: Property 'paramSet' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. Did you mean 'params'? node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64534,18): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64536,17): error TS2339: Property 'message' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65232,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65248,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65283,7): error TS2339: Property 'index' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65284,7): error TS2339: Property 'lineNumber' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65285,7): error TS2339: Property 'description' does not exist on type 'Error'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65310,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65379,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65468,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65533,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66529,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66549,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66811,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67117,1): error TS2322: Type 'string[]' is not assignable to type 'RegExpExecArray'. Property 'index' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67300,14): error TS2339: Property 'Channels' does not exist on type '{}'. @@ -3058,7 +2994,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68209,38): error TS2339: Property 'componentsOrder' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68212,26): error TS2339: Property 'maxH' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68213,26): error TS2339: Property 'maxV' does not exist on type '{}'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(69799,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,4): error TS2531: Object is possibly 'null'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,26): error TS2531: Object is possibly 'null'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70753,6): error TS2531: Object is possibly 'null'. @@ -11599,30 +11534,16 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,482): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,502): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,564): error TS2339: Property 'code' does not exist on type 'Error'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(166,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(293,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(337,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(398,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1330,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1370,101): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1550,11): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1557,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2037,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2281,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2359,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2378,16): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2397,20): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2398,27): error TS2339: Property 'clipboardData' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2450,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2476,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2503,41): error TS2339: Property '_document' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2509,18): error TS2339: Property '_parentElement' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2524,18): error TS2339: Property 'emit' does not exist on type 'CharMeasure'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2535,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2612,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2615,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2674,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2690,63): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2694,68): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2697,70): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. @@ -11630,9 +11551,6 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2704,51): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2713,22): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2714,22): error TS2339: Property '_objectCount' does not exist on type 'typeof DomElementObjectPool'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2721,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2732,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2766,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2925,9): error TS2322: Type 'number' is not assignable to type 'number[]'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3087,14): error TS2339: Property 'browser' does not exist on type 'Terminal'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3151,54): error TS2339: Property 'theme' does not exist on type 'Terminal'. From 372c7d9b0c7e2fb3a9d027e2ab4c069e2fa30b9a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 26 Oct 2018 14:09:42 -0700 Subject: [PATCH 126/262] infer from usage JSDoc:Don't emit nested comments (#28161) * infer from usage JSDoc:Don't emit nested comments Previously, the trivia on a parameter name would show up inside the emitted JSDoc comment. If the trivia contained a C-style comment, the emitted JSDoc comment would be invalid. For example: ```js function call(callback /*oh no*/) { return callback(this) } ``` Emitted this comment: ```js /** * @param {(arg0: any) => void} callback /*oh no*/ */ ``` * Remove misleading comment used for debugging. --- src/services/codefixes/inferFromUsage.ts | 4 +++- ...eFixInferFromUsageCommentAfterParameter.ts | 24 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 2055bbf3b31..bc324ac9e24 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -219,7 +219,9 @@ namespace ts.codefix { if (param.initializer || getJSDocType(param) || !isIdentifier(param.name)) return; const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); - return typeNode && createJSDocParamTag(param.name, !!inference.isOptional, createJSDocTypeExpression(typeNode), ""); + const name = getSynthesizedClone(param.name); + setEmitFlags(name, EmitFlags.NoComments | EmitFlags.NoNestedComments); + return typeNode && createJSDocParamTag(name, !!inference.isOptional, createJSDocTypeExpression(typeNode), ""); }); addJSDocTags(changes, sourceFile, signature, paramTags); } diff --git a/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts b/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts new file mode 100644 index 00000000000..b46600d927f --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: true +// @Filename: important.js + + +////function coll(callback /*, name1, name2, ... */) { +//// return callback(this); +////} + +verify.codeFix({ + description: "Infer parameter types from usage", + index: 2, + newFileContent: +`/** + * @param {(arg0: any) => void} callback + */ +function coll(callback /*, name1, name2, ... */) { + return callback(this); +}`, +}); From 30d1ecd1bd022bd15390d6b102adc72954955279 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Oct 2018 14:14:53 -0700 Subject: [PATCH 127/262] Constraint for { [P in K]: XXX } should be empty type --- src/compiler/checker.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fd786799b8b..383566ab291 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6832,11 +6832,9 @@ namespace ts { } } else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - const keyType = constraintType.flags & TypeFlags.InstantiableNonPrimitive ? getApparentType(constraintType) : constraintType; - const iterationType = keyType.flags & TypeFlags.Index ? getIndexType(getApparentType((keyType).type)) : keyType; + // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Then iterate over the constituents of the key type. + const iterationType = constraintType.flags & TypeFlags.Index ? getIndexType(getApparentType((constraintType).type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); From 77d8e1590516c65c05be68ca8e09cc37978f8d84 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 26 Oct 2018 14:44:49 -0700 Subject: [PATCH 128/262] Remove unused property ParameterInference#typeNode (#28115) --- src/services/codefixes/inferFromUsage.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index bc324ac9e24..cef820bbf59 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -306,10 +306,9 @@ namespace ts.codefix { } interface ParameterInference { - declaration: ParameterDeclaration; - type?: Type; - typeNode?: TypeNode; - isOptional?: boolean; + readonly declaration: ParameterDeclaration; + readonly type?: Type; + readonly isOptional?: boolean; } namespace InferFromReference { @@ -355,7 +354,7 @@ namespace ts.codefix { } const isConstructor = declaration.kind === SyntaxKind.Constructor; const callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; - return callContexts && declaration.parameters.map((parameter, parameterIndex) => { + return callContexts && declaration.parameters.map((parameter, parameterIndex): ParameterInference => { const types: Type[] = []; const isRest = isRestParameter(parameter); let isOptional = false; From abce9ae0be0a3c13942f8532252952ecde850a10 Mon Sep 17 00:00:00 2001 From: Jack W Date: Fri, 26 Oct 2018 22:56:26 +0100 Subject: [PATCH 129/262] Bring typeof switch inline with if (#27680) - Narrow unknown - Narrow union members (in addition to filtering) --- src/compiler/checker.ts | 54 +- .../reference/narrowingByTypeofInSwitch.js | 119 +++- .../narrowingByTypeofInSwitch.symbols | 562 +++++++++++------- .../reference/narrowingByTypeofInSwitch.types | 177 +++++- .../compiler/narrowingByTypeofInSwitch.ts | 43 +- 5 files changed, 706 insertions(+), 249 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 49caad2116e..7531dd926ff 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15441,6 +15441,32 @@ namespace ts { return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } + function getImpliedTypeFromTypeofCase(type: Type, text: string) { + switch (text) { + case "function": + return type.flags & TypeFlags.Any ? type : globalFunctionType; + case "object": + return type.flags & TypeFlags.Unknown ? getUnionType([nonPrimitiveType, nullType]) : type; + default: + return typeofTypesByName.get(text) || type; + } + } + + function narrowTypeForTypeofSwitch(candidate: Type) { + return (type: Type) => { + if (isTypeSubtypeOf(candidate, type)) { + return candidate; + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(candidate, constraint)) { + return getIntersectionType([type, candidate]); + } + } + return type; + }; + } + function narrowBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type { const switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!switchWitnesses.length) { @@ -15458,7 +15484,7 @@ namespace ts { // that we don't have to worry about undefined // in the witness array. const witnesses = switchWitnesses.filter(witness => witness !== undefined); - // The adjust clause start and end after removing the `default` statement. + // The adjusted clause start and end after removing the `default` statement. const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; const fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); @@ -15468,6 +15494,9 @@ namespace ts { clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); } + if (hasDefaultClause) { + return filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts); + } /* The implied type is the raw type suggested by a value being caught in this clause. @@ -15496,26 +15525,11 @@ namespace ts { boolean. We know that number cannot be selected because it is caught in the first clause. */ - if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { - let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); - if (impliedType.flags & TypeFlags.Union) { - impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOfType(type) || type); - } - if (!(impliedType.flags & TypeFlags.Never)) { - if (isTypeSubtypeOf(impliedType, type)) { - return impliedType; - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(impliedType, constraint)) { - return getIntersectionType([type, impliedType]); - } - } - } + let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => getImpliedTypeFromTypeofCase(type, text))), switchFacts); + if (impliedType.flags & TypeFlags.Union) { + impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOrType(type)); } - return hasDefaultClause ? - filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts) : - getTypeWithFacts(type, switchFacts); + return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.js b/tests/baselines/reference/narrowingByTypeofInSwitch.js index 95ec120a85d..2b99da05e13 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.js +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.js @@ -27,6 +27,10 @@ function assertObject(x: object) { return x; } +function assertObjectOrNull(x: object | null) { + return x; +} + function assertUndefined(x: undefined) { return x; } @@ -35,11 +39,11 @@ function assertAll(x: Basic) { return x; } -function assertStringOrNumber(x: string | number) { +function assertStringOrNumber(x: string | number) { return x; } -function assertBooleanOrObject(x: boolean | object) { +function assertBooleanOrObject(x: boolean | object) { return x; } @@ -210,6 +214,41 @@ function fallThroughTest(x: string | number | boolean | object) { break; } } + +function unknownNarrowing(x: unknown) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObjectOrNull(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } +} + +function keyofNarrowing(k: keyof S) { + function assertKeyofS(k1: keyof S) { } + switch (typeof k) { + case 'number': assertNumber(k); assertKeyofS(k); return; + case 'symbol': assertSymbol(k); assertKeyofS(k); return; + case 'string': assertString(k); assertKeyofS(k); return; + } +} + +function narrowingNarrows(x: {} | undefined) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': const _: {} = x; return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + case 'number': assertNever(x); return; + default: const _y: {} = x; return; + } +} //// [narrowingByTypeofInSwitch.js] @@ -234,6 +273,9 @@ function assertFunction(x) { function assertObject(x) { return x; } +function assertObjectOrNull(x) { + return x; +} function assertUndefined(x) { return x; } @@ -470,3 +512,76 @@ function fallThroughTest(x) { break; } } +function unknownNarrowing(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + case 'object': + assertObjectOrNull(x); + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + } +} +function keyofNarrowing(k) { + function assertKeyofS(k1) { } + switch (typeof k) { + case 'number': + assertNumber(k); + assertKeyofS(k); + return; + case 'symbol': + assertSymbol(k); + assertKeyofS(k); + return; + case 'string': + assertString(k); + assertKeyofS(k); + return; + } +} +function narrowingNarrows(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + case 'object': + var _ = x; + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + case 'number': + assertNever(x); + return; + default: + var _y = x; + return; + } +} diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols index 80246251815..f1ff39725b3 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols @@ -56,536 +56,662 @@ function assertObject(x: object) { >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 24, 22)) } -function assertUndefined(x: undefined) { ->assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 25)) +function assertObjectOrNull(x: object | null) { +>assertObjectOrNull : Symbol(assertObjectOrNull, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 28)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 25)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 28)) +} + +function assertUndefined(x: undefined) { +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 25)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 25)) } function assertAll(x: Basic) { ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 19)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 19)) } -function assertStringOrNumber(x: string | number) { ->assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 30)) +function assertStringOrNumber(x: string | number) { +>assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 30)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 30)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 30)) } -function assertBooleanOrObject(x: boolean | object) { ->assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 31)) +function assertBooleanOrObject(x: boolean | object) { +>assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 44, 31)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 44, 31)) } type Basic = number | boolean | string | symbol | object | Function | undefined; ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) function testUnion(x: Basic) { ->testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 44, 80)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 48, 80)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'object': assertObject(x); return; >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) case 'undefined': assertUndefined(x); return; ->assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) } assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 50, 19)) } function testExtendsUnion(x: T) { ->testExtendsUnion : Symbol(testExtendsUnion, Decl(narrowingByTypeofInSwitch.ts, 57, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 59, 26)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 59, 26)) +>testExtendsUnion : Symbol(testExtendsUnion, Decl(narrowingByTypeofInSwitch.ts, 61, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 63, 26)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 63, 26)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'function': assertAll(x); return; ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'object': assertAll(x); return; ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) case 'undefined': assertUndefined(x); return; ->assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) } assertAll(x); ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 63, 43)) } function testAny(x: any) { ->testAny : Symbol(testAny, Decl(narrowingByTypeofInSwitch.ts, 70, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>testAny : Symbol(testAny, Decl(narrowingByTypeofInSwitch.ts, 74, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'object': assertObject(x); return; >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) case 'undefined': assertUndefined(x); return; ->assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) } assertAll(x); // is any ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 76, 17)) } function a1(x: string | object | undefined) { ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 85, 12)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 87, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 12)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 85, 12)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 12)) } function testUnionExplicitDefault(x: Basic) { ->testUnionExplicitDefault : Symbol(testUnionExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 87, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>testUnionExplicitDefault : Symbol(testUnionExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 91, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) default: a1(x); return; ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 87, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 93, 34)) } } function testUnionImplicitDefault(x: Basic) { ->testUnionImplicitDefault : Symbol(testUnionImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 97, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>testUnionImplicitDefault : Symbol(testUnionImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 101, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) } return a1(x); ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 87, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 103, 34)) } function testExtendsExplicitDefault(x: T) { ->testExtendsExplicitDefault : Symbol(testExtendsExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 107, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 109, 36)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 109, 36)) +>testExtendsExplicitDefault : Symbol(testExtendsExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 111, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 113, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 113, 36)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) case 'function': assertAll(x); return; ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) default: assertAll(x); return; ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 113, 53)) } } function testExtendsImplicitDefault(x: T) { ->testExtendsImplicitDefault : Symbol(testExtendsImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 118, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 120, 36)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 120, 36)) +>testExtendsImplicitDefault : Symbol(testExtendsImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 122, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 124, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 124, 36)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) case 'function': assertAll(x); return; ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) } return assertAll(x); ->assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 124, 53)) } type L = (x: number) => string; ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 130, 10)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 10)) type R = { x: string, y: number } ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 135, 10)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 135, 21)) function exhaustiveChecks(x: number | string | L | R): string { ->exhaustiveChecks : Symbol(exhaustiveChecks, Decl(narrowingByTypeofInSwitch.ts, 131, 33)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>exhaustiveChecks : Symbol(exhaustiveChecks, Decl(narrowingByTypeofInSwitch.ts, 135, 33)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) case 'number': return x.toString(2); >x.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) >toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) case 'string': return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) case 'function': return x(42); ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) case 'object': return x.x; ->x.x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) +>x.x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 135, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 137, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 135, 10)) } } function exhaustiveChecksGenerics(x: T): string { ->exhaustiveChecksGenerics : Symbol(exhaustiveChecksGenerics, Decl(narrowingByTypeofInSwitch.ts, 140, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 142, 34)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 142, 34)) +>exhaustiveChecksGenerics : Symbol(exhaustiveChecksGenerics, Decl(narrowingByTypeofInSwitch.ts, 144, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 146, 34)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 146, 34)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) case 'number': return x.toString(2); >x.toString : Symbol(toString, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --) ... and 2 more) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) >toString : Symbol(toString, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --) ... and 2 more) case 'string': return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) case 'function': return (x as L)(42); // Can't narrow generic ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) case 'object': return (x as R).x; // Can't narrow generic ->(x as R).x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) +>(x as R).x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 135, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 146, 69)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 135, 10)) } } function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { ->multipleGeneric : Symbol(multipleGeneric, Decl(narrowingByTypeofInSwitch.ts, 149, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) +>multipleGeneric : Symbol(multipleGeneric, Decl(narrowingByTypeofInSwitch.ts, 153, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 155, 25)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 155, 37)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 155, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 155, 37)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 155, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 155, 37)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) case 'function': return [xy, xy(42)]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) case 'object': return [xy, xy.y]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) ->xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 135, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 135, 21)) default: return assertNever(xy); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 155, 51)) } } function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { ->multipleGenericFuse : Symbol(multipleGenericFuse, Decl(narrowingByTypeofInSwitch.ts, 157, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) +>multipleGenericFuse : Symbol(multipleGenericFuse, Decl(narrowingByTypeofInSwitch.ts, 161, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 163, 29)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 163, 50)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 163, 73)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 163, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 163, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 163, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 163, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 163, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 163, 50)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 163, 73)) case 'function': return [xy, 1]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 163, 73)) case 'object': return [xy, 'two']; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 163, 73)) case 'number': return [xy] ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 163, 73)) } } function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { ->multipleGenericExhaustive : Symbol(multipleGenericExhaustive, Decl(narrowingByTypeofInSwitch.ts, 165, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) +>multipleGenericExhaustive : Symbol(multipleGenericExhaustive, Decl(narrowingByTypeofInSwitch.ts, 169, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 171, 35)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 171, 47)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 171, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 171, 47)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 171, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 171, 47)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) case 'object': return [xy, xy.y]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) ->xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 135, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 135, 21)) case 'function': return [xy, xy(42)]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 171, 61)) } } function switchOrdering(x: string | number | boolean) { ->switchOrdering : Symbol(switchOrdering, Decl(narrowingByTypeofInSwitch.ts, 172, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>switchOrdering : Symbol(switchOrdering, Decl(narrowingByTypeofInSwitch.ts, 176, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) case 'string': return assertString(x); >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) case 'number': return assertNumber(x); >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) case 'boolean': return assertBoolean(x); >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) case 'number': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 178, 24)) } } function switchOrderingWithDefault(x: string | number | boolean) { ->switchOrderingWithDefault : Symbol(switchOrderingWithDefault, Decl(narrowingByTypeofInSwitch.ts, 181, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>switchOrderingWithDefault : Symbol(switchOrderingWithDefault, Decl(narrowingByTypeofInSwitch.ts, 185, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) function local(y: string | number | boolean) { ->local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 183, 66)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 184, 19)) +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 187, 66)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 188, 19)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) } switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) case 'string': case 'number': default: return local(x) ->local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 183, 66)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 187, 66)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) case 'string': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) case 'number': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 187, 35)) } } function fallThroughTest(x: string | number | boolean | object) { ->fallThroughTest : Symbol(fallThroughTest, Decl(narrowingByTypeofInSwitch.ts, 194, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>fallThroughTest : Symbol(fallThroughTest, Decl(narrowingByTypeofInSwitch.ts, 198, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) case 'number': assertNumber(x) >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) case 'string': assertStringOrNumber(x) ->assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) break; default: assertObject(x); >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) case 'number': case 'boolean': assertBooleanOrObject(x); ->assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) +>assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 200, 25)) break; } } +function unknownNarrowing(x: unknown) { +>unknownNarrowing : Symbol(unknownNarrowing, Decl(narrowingByTypeofInSwitch.ts, 214, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'object': assertObjectOrNull(x); return; +>assertObjectOrNull : Symbol(assertObjectOrNull, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 216, 26)) + } +} + +function keyofNarrowing(k: keyof S) { +>keyofNarrowing : Symbol(keyofNarrowing, Decl(narrowingByTypeofInSwitch.ts, 226, 1)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 228, 24)) +>K : Symbol(K, Decl(narrowingByTypeofInSwitch.ts, 228, 37)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 228, 24)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 228, 24)) + + function assertKeyofS(k1: keyof S) { } +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 228, 75)) +>k1 : Symbol(k1, Decl(narrowingByTypeofInSwitch.ts, 229, 26)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 228, 24)) + + switch (typeof k) { +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) + + case 'number': assertNumber(k); assertKeyofS(k); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 228, 75)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) + + case 'symbol': assertSymbol(k); assertKeyofS(k); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 228, 75)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) + + case 'string': assertString(k); assertKeyofS(k); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 228, 75)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 228, 62)) + } +} + +function narrowingNarrows(x: {} | undefined) { +>narrowingNarrows : Symbol(narrowingNarrows, Decl(narrowingByTypeofInSwitch.ts, 235, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'object': const _: {} = x; return; +>_ : Symbol(_, Decl(narrowingByTypeofInSwitch.ts, 243, 28)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + case 'number': assertNever(x); return; +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + + default: const _y: {} = x; return; +>_y : Symbol(_y, Decl(narrowingByTypeofInSwitch.ts, 247, 22)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 237, 26)) + } +} + diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index 342aeb670ec..a0d1c272d02 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -55,6 +55,15 @@ function assertObject(x: object) { >x : object } +function assertObjectOrNull(x: object | null) { +>assertObjectOrNull : (x: object | null) => object | null +>x : object | null +>null : null + + return x; +>x : object | null +} + function assertUndefined(x: undefined) { >assertUndefined : (x: undefined) => undefined >x : undefined @@ -71,7 +80,7 @@ function assertAll(x: Basic) { >x : Basic } -function assertStringOrNumber(x: string | number) { +function assertStringOrNumber(x: string | number) { >assertStringOrNumber : (x: string | number) => string | number >x : string | number @@ -79,7 +88,7 @@ function assertStringOrNumber(x: string | number) { >x : string | number } -function assertBooleanOrObject(x: boolean | object) { +function assertBooleanOrObject(x: boolean | object) { >assertBooleanOrObject : (x: boolean | object) => boolean | object >x : boolean | object @@ -170,7 +179,7 @@ function testExtendsUnion(x: T) { >'function' : "function" >assertAll(x) : Basic >assertAll : (x: Basic) => Basic ->x : T +>x : T & Function case 'symbol': assertSymbol(x); return; >'symbol' : "symbol" @@ -367,7 +376,7 @@ function testExtendsExplicitDefault(x: T) { >'function' : "function" >assertAll(x) : Basic >assertAll : (x: Basic) => Basic ->x : T +>x : T & Function case 'symbol': assertSymbol(x); return; >'symbol' : "symbol" @@ -407,7 +416,7 @@ function testExtendsImplicitDefault(x: T) { >'function' : "function" >assertAll(x) : Basic >assertAll : (x: Basic) => Basic ->x : T +>x : T & Function case 'symbol': assertSymbol(x); return; >'symbol' : "symbol" @@ -555,8 +564,8 @@ function multipleGenericFuse(xy: X | case 'number': return [xy] >'number' : "number" ->[xy] : [X | Y] ->xy : X | Y +>[xy] : [(X & number) | (Y & number)] +>xy : (X & number) | (Y & number) } } @@ -706,3 +715,157 @@ function fallThroughTest(x: string | number | boolean | object) { } } +function unknownNarrowing(x: unknown) { +>unknownNarrowing : (x: unknown) => void +>x : unknown + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : unknown + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : Function + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + + case 'object': assertObjectOrNull(x); return; +>'object' : "object" +>assertObjectOrNull(x) : object | null +>assertObjectOrNull : (x: object | null) => object | null +>x : object | null + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : string + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : undefined + } +} + +function keyofNarrowing(k: keyof S) { +>keyofNarrowing : (k: keyof S) => void +>k : keyof S + + function assertKeyofS(k1: keyof S) { } +>assertKeyofS : (k1: keyof S) => void +>k1 : keyof S + + switch (typeof k) { +>typeof k : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>k : keyof S + + case 'number': assertNumber(k); assertKeyofS(k); return; +>'number' : "number" +>assertNumber(k) : number +>assertNumber : (x: number) => number +>k : keyof S & number +>assertKeyofS(k) : void +>assertKeyofS : (k1: keyof S) => void +>k : keyof S & number + + case 'symbol': assertSymbol(k); assertKeyofS(k); return; +>'symbol' : "symbol" +>assertSymbol(k) : symbol +>assertSymbol : (x: symbol) => symbol +>k : keyof S & symbol +>assertKeyofS(k) : void +>assertKeyofS : (k1: keyof S) => void +>k : keyof S & symbol + + case 'string': assertString(k); assertKeyofS(k); return; +>'string' : "string" +>assertString(k) : string +>assertString : (x: string) => string +>k : keyof S & string +>assertKeyofS(k) : void +>assertKeyofS : (k1: keyof S) => void +>k : keyof S & string + } +} + +function narrowingNarrows(x: {} | undefined) { +>narrowingNarrows : (x: {} | undefined) => void +>x : {} | undefined + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : {} | undefined + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : Function + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + + case 'object': const _: {} = x; return; +>'object' : "object" +>_ : {} +>x : {} + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : string + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : undefined + + case 'number': assertNever(x); return; +>'number' : "number" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + default: const _y: {} = x; return; +>_y : {} +>x : {} + } +} + diff --git a/tests/cases/compiler/narrowingByTypeofInSwitch.ts b/tests/cases/compiler/narrowingByTypeofInSwitch.ts index 252c1d9445a..39f04168684 100644 --- a/tests/cases/compiler/narrowingByTypeofInSwitch.ts +++ b/tests/cases/compiler/narrowingByTypeofInSwitch.ts @@ -29,6 +29,10 @@ function assertObject(x: object) { return x; } +function assertObjectOrNull(x: object | null) { + return x; +} + function assertUndefined(x: undefined) { return x; } @@ -37,11 +41,11 @@ function assertAll(x: Basic) { return x; } -function assertStringOrNumber(x: string | number) { +function assertStringOrNumber(x: string | number) { return x; } -function assertBooleanOrObject(x: boolean | object) { +function assertBooleanOrObject(x: boolean | object) { return x; } @@ -212,3 +216,38 @@ function fallThroughTest(x: string | number | boolean | object) { break; } } + +function unknownNarrowing(x: unknown) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObjectOrNull(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } +} + +function keyofNarrowing(k: keyof S) { + function assertKeyofS(k1: keyof S) { } + switch (typeof k) { + case 'number': assertNumber(k); assertKeyofS(k); return; + case 'symbol': assertSymbol(k); assertKeyofS(k); return; + case 'string': assertString(k); assertKeyofS(k); return; + } +} + +function narrowingNarrows(x: {} | undefined) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': const _: {} = x; return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + case 'number': assertNever(x); return; + default: const _y: {} = x; return; + } +} From 36dfd775b3ca55ccef5f7c6fa31cc7d9d8a20098 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 26 Oct 2018 15:00:31 -0700 Subject: [PATCH 130/262] Parse an object literal property as shorthand unless followed by '(' or ':' (#28121) --- src/compiler/parser.ts | 3 +-- .../convertCompilerOptionsFromJson.ts | 3 ++- src/testRunner/unittests/tsconfigParsing.ts | 2 +- .../incompleteObjectLiteral1.errors.txt | 9 ++++--- .../reference/incompleteObjectLiteral1.js | 2 +- .../reference/incompleteObjectLiteral1.types | 1 - ...tiesErrorFromNotUsingIdentifier.errors.txt | 25 +++++++++++++++---- ...ndPropertiesErrorFromNotUsingIdentifier.js | 14 +++++++---- ...pertiesErrorFromNotUsingIdentifier.symbols | 5 ++++ ...ropertiesErrorFromNotUsingIdentifier.types | 11 +++++--- ...rthandPropertiesErrorWithModule.errors.txt | 4 +-- ...teralShorthandPropertiesErrorWithModule.js | 2 +- ...ShorthandPropertiesErrorWithModule.symbols | 1 + ...alShorthandPropertiesErrorWithModule.types | 7 +++--- .../objectLiteralWithSemicolons1.errors.txt | 16 ++++++++---- .../reference/objectLiteralWithSemicolons1.js | 2 +- .../objectLiteralWithSemicolons1.types | 2 -- .../objectLiteralWithSemicolons2.errors.txt | 16 ++++++++---- .../reference/objectLiteralWithSemicolons2.js | 4 +-- .../objectLiteralWithSemicolons2.types | 2 -- .../objectLiteralWithSemicolons3.errors.txt | 23 +++++++++++------ .../reference/objectLiteralWithSemicolons3.js | 6 ++--- .../objectLiteralWithSemicolons3.types | 3 --- .../objectLiteralWithSemicolons4.errors.txt | 9 ++++--- .../reference/objectLiteralWithSemicolons4.js | 2 +- .../objectLiteralWithSemicolons4.types | 2 -- ...ors.objectLiteralMethods.esnext.errors.txt | 18 ++++++++----- ...nerators.objectLiteralMethods.esnext.types | 2 -- .../reference/parser512097.errors.txt | 11 +++++--- tests/baselines/reference/parser512097.js | 4 +-- .../baselines/reference/parser512097.symbols | 2 +- tests/baselines/reference/parser512097.types | 3 +-- ...serErrorRecovery_ObjectLiteral2.errors.txt | 9 ++++--- .../parserErrorRecovery_ObjectLiteral2.js | 2 +- .../parserErrorRecovery_ObjectLiteral2.types | 1 - .../reference/privateIndexer2.errors.txt | 9 ++++--- tests/baselines/reference/privateIndexer2.js | 2 +- .../baselines/reference/privateIndexer2.types | 1 - .../RegressionTests/parser512097.ts | 2 +- ...etionsAtIncompleteObjectLiteralProperty.ts | 14 +++++++++++ 40 files changed, 163 insertions(+), 93 deletions(-) create mode 100644 tests/cases/fourslash/completionsAtIncompleteObjectLiteralProperty.ts diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index edb4835ae5f..77bf0351242 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -4738,8 +4738,7 @@ namespace ts { // CoverInitializedName[Yield] : // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - const isShorthandPropertyAssignment = - tokenIsIdentifier && (token() === SyntaxKind.CommaToken || token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.EqualsToken); + const isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== SyntaxKind.ColonToken); if (isShorthandPropertyAssignment) { node.kind = SyntaxKind.ShorthandPropertyAssignment; const equalsToken = parseOptionalToken(SyntaxKind.EqualsToken); diff --git a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts index 327bf523160..4f6f479e2bd 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts @@ -596,7 +596,8 @@ namespace ts { { compilerOptions: { target: undefined, - module: ModuleKind.ESNext + module: ModuleKind.ESNext, + experimentalDecorators: true, }, hasParseErrors: true } diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/tsconfigParsing.ts index 6909e260d2a..255129d9fb6 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/tsconfigParsing.ts @@ -141,7 +141,7 @@ namespace ts { it("returns object with error when json is invalid", () => { const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid"); - assert.deepEqual(parsed.config, { invalid: undefined }); + assert.deepEqual(parsed.config, {}); const expected = createCompilerDiagnostic(Diagnostics._0_expected, "{"); const error = parsed.error!; assert.equal(error.messageText, expected.messageText); diff --git a/tests/baselines/reference/incompleteObjectLiteral1.errors.txt b/tests/baselines/reference/incompleteObjectLiteral1.errors.txt index 903f83b3229..9122063302e 100644 --- a/tests/baselines/reference/incompleteObjectLiteral1.errors.txt +++ b/tests/baselines/reference/incompleteObjectLiteral1.errors.txt @@ -1,8 +1,11 @@ -tests/cases/compiler/incompleteObjectLiteral1.ts(1,14): error TS1005: ':' expected. +tests/cases/compiler/incompleteObjectLiteral1.ts(1,12): error TS2304: Cannot find name 'aa'. +tests/cases/compiler/incompleteObjectLiteral1.ts(1,14): error TS1005: ',' expected. -==== tests/cases/compiler/incompleteObjectLiteral1.ts (1 errors) ==== +==== tests/cases/compiler/incompleteObjectLiteral1.ts (2 errors) ==== var tt = { aa; } + ~~ +!!! error TS2304: Cannot find name 'aa'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. var x = tt; \ No newline at end of file diff --git a/tests/baselines/reference/incompleteObjectLiteral1.js b/tests/baselines/reference/incompleteObjectLiteral1.js index ecdbe86604a..b64da995a5a 100644 --- a/tests/baselines/reference/incompleteObjectLiteral1.js +++ b/tests/baselines/reference/incompleteObjectLiteral1.js @@ -3,5 +3,5 @@ var tt = { aa; } var x = tt; //// [incompleteObjectLiteral1.js] -var tt = { aa: }; +var tt = { aa: aa }; var x = tt; diff --git a/tests/baselines/reference/incompleteObjectLiteral1.types b/tests/baselines/reference/incompleteObjectLiteral1.types index 322ad333f95..f7982f33ce2 100644 --- a/tests/baselines/reference/incompleteObjectLiteral1.types +++ b/tests/baselines/reference/incompleteObjectLiteral1.types @@ -3,7 +3,6 @@ var tt = { aa; } >tt : { aa: any; } >{ aa; } : { aa: any; } >aa : any -> : any var x = tt; >x : { aa: any; } diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt index 5fa8a12e875..17c7126ff33 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.errors.txt @@ -7,13 +7,18 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(9,8): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(10,10): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(12,1): error TS1005: ':' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,6): error TS1005: ':' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,6): error TS1005: ':' expected. -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,6): error TS1005: ':' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(15,6): error TS1005: ',' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,6): error TS1005: ',' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(16,12): error TS1005: ':' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,5): error TS2304: Cannot find name 'a'. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,6): error TS1005: ',' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(17,9): error TS1005: ':' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts(20,17): error TS1005: ':' expected. -==== tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts (13 errors) ==== +==== tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts (18 errors) ==== // errors var y = { "stringLiteral", @@ -47,13 +52,23 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr var x = { a.b, + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. a["ss"], + ~ +!!! error TS2304: Cannot find name 'a'. ~ +!!! error TS1005: ',' expected. + ~ !!! error TS1005: ':' expected. a[1], + ~ +!!! error TS2304: Cannot find name 'a'. ~ +!!! error TS1005: ',' expected. + ~ !!! error TS1005: ':' expected. }; diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js index 7b9c9f5d328..e0aecb5f188 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js @@ -21,6 +21,7 @@ var x = { var v = { class }; // error //// [objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js] +var _a; // errors var y = { "stringLiteral": , @@ -33,9 +34,12 @@ var y = { "class": , "typeof": }; -var x = { - a: .b, - a: ["ss"], - a: [1] -}; +var x = (_a = { + a: a, : .b, + a: a + }, + _a["ss"] = , + _a.a = a, + _a[1] = , + _a); var v = { "class": }; // error diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.symbols b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.symbols index 09f9d036285..2ce3f53d594 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.symbols +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.symbols @@ -37,12 +37,17 @@ var x = { a.b, >a : Symbol(a, Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 13, 9), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 14, 8), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 15, 12)) +> : Symbol((Missing), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 14, 5)) a["ss"], >a : Symbol(a, Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 13, 9), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 14, 8), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 15, 12)) +>["ss"] : Symbol(["ss"], Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 15, 5)) +>"ss" : Symbol(["ss"], Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 15, 5)) a[1], >a : Symbol(a, Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 13, 9), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 14, 8), Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 15, 12)) +>[1] : Symbol([1], Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 16, 5)) +>1 : Symbol([1], Decl(objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts, 16, 5)) }; diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.types b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.types index 6e255d871c0..3782c70fe97 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.types +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.types @@ -41,24 +41,27 @@ var y = { > : any var x = { ->x : { a: number[]; } ->{ a.b, a["ss"], a[1],} : { a: number[]; } +>x : { a: any; (Missing): any; ["ss"]: any; [1]: any; } +>{ a.b, a["ss"], a[1],} : { a: any; (Missing): any; ["ss"]: any; [1]: any; } a.b, >a : any +> : any >.b : any > : any >b : any a["ss"], >a : any ->["ss"] : string[] +>["ss"] : any >"ss" : "ss" +> : any a[1], >a : any ->[1] : number[] +>[1] : any >1 : 1 +> : any }; diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.errors.txt b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.errors.txt index 15bac99436f..f5fd8ed53f2 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.errors.txt +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorWithModule.ts(10,10): error TS1005: ':' expected. +tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorWithModule.ts(10,10): error TS1005: ',' expected. tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPropertiesErrorWithModule.ts(14,3): error TS2339: Property 'y' does not exist on type 'typeof m'. @@ -14,7 +14,7 @@ tests/cases/conformance/es6/shorthandPropertyAssignment/objectLiteralShorthandPr export var y = { m.x // error ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. }; } diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js index 65ba94f86a3..ee46d4741dd 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js @@ -25,7 +25,7 @@ var n; (function (n) { var z = 10000; n.y = { - m: .x // error + m: m, : .x // error }; })(n || (n = {})); m.y.x; diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.symbols b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.symbols index 3df77aee210..d33969190a9 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.symbols +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.symbols @@ -21,6 +21,7 @@ module n { m.x // error >m : Symbol(m, Decl(objectLiteralShorthandPropertiesErrorWithModule.ts, 8, 20)) +> : Symbol((Missing), Decl(objectLiteralShorthandPropertiesErrorWithModule.ts, 9, 9)) }; } diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.types b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.types index a496bf4b787..78da1fb83ea 100644 --- a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.types +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.types @@ -19,11 +19,12 @@ module n { >10000 : 10000 export var y = { ->y : { m: any; } ->{ m.x // error } : { m: any; } +>y : { m: typeof m; (Missing): any; } +>{ m.x // error } : { m: typeof m; (Missing): any; } m.x // error ->m : any +>m : typeof m +> : any >.x : any > : any >x : any diff --git a/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt index 077d807af2c..43a0927cc29 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons1.errors.txt @@ -1,13 +1,19 @@ -tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,12): error TS1005: ':' expected. -tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,15): error TS1005: ':' expected. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,11): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,12): error TS1005: ',' expected. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,14): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,15): error TS1005: ',' expected. tests/cases/compiler/objectLiteralWithSemicolons1.ts(1,17): error TS2304: Cannot find name 'c'. -==== tests/cases/compiler/objectLiteralWithSemicolons1.ts (3 errors) ==== +==== tests/cases/compiler/objectLiteralWithSemicolons1.ts (5 errors) ==== var v = { a; b; c } + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. + ~ +!!! error TS2304: Cannot find name 'b'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. ~ !!! error TS2304: Cannot find name 'c'. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons1.js b/tests/baselines/reference/objectLiteralWithSemicolons1.js index b820b14428c..6dce134df26 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons1.js +++ b/tests/baselines/reference/objectLiteralWithSemicolons1.js @@ -2,4 +2,4 @@ var v = { a; b; c } //// [objectLiteralWithSemicolons1.js] -var v = { a: , b: , c: c }; +var v = { a: a, b: b, c: c }; diff --git a/tests/baselines/reference/objectLiteralWithSemicolons1.types b/tests/baselines/reference/objectLiteralWithSemicolons1.types index cc7e6075fad..48445eee95d 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons1.types +++ b/tests/baselines/reference/objectLiteralWithSemicolons1.types @@ -3,8 +3,6 @@ var v = { a; b; c } >v : { a: any; b: any; c: any; } >{ a; b; c } : { a: any; b: any; c: any; } >a : any -> : any >b : any -> : any >c : any diff --git a/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt index d5594f66fb3..6fc0b5ff139 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons2.errors.txt @@ -1,16 +1,22 @@ -tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,4): error TS1005: ':' expected. -tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,4): error TS1005: ':' expected. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(2,4): error TS1005: ',' expected. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,3): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons2.ts(3,4): error TS1005: ',' expected. tests/cases/compiler/objectLiteralWithSemicolons2.ts(4,3): error TS2304: Cannot find name 'c'. -==== tests/cases/compiler/objectLiteralWithSemicolons2.ts (3 errors) ==== +==== tests/cases/compiler/objectLiteralWithSemicolons2.ts (5 errors) ==== var v = { a; + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. b; + ~ +!!! error TS2304: Cannot find name 'b'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. c ~ !!! error TS2304: Cannot find name 'c'. diff --git a/tests/baselines/reference/objectLiteralWithSemicolons2.js b/tests/baselines/reference/objectLiteralWithSemicolons2.js index 2b46267465d..7e43ab48edb 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons2.js +++ b/tests/baselines/reference/objectLiteralWithSemicolons2.js @@ -7,7 +7,7 @@ var v = { //// [objectLiteralWithSemicolons2.js] var v = { - a: , - b: , + a: a, + b: b, c: c }; diff --git a/tests/baselines/reference/objectLiteralWithSemicolons2.types b/tests/baselines/reference/objectLiteralWithSemicolons2.types index 8dfab7bfea4..bb5f5dc7a7f 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons2.types +++ b/tests/baselines/reference/objectLiteralWithSemicolons2.types @@ -5,11 +5,9 @@ var v = { a; >a : any -> : any b; >b : any -> : any c >c : any diff --git a/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt index dc638922e7b..dd5709b9822 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons3.errors.txt @@ -1,17 +1,26 @@ -tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,4): error TS1005: ':' expected. -tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,4): error TS1005: ':' expected. -tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,4): error TS1005: ':' expected. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(2,4): error TS1005: ',' expected. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,3): error TS2304: Cannot find name 'b'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(3,4): error TS1005: ',' expected. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,3): error TS2304: Cannot find name 'c'. +tests/cases/compiler/objectLiteralWithSemicolons3.ts(4,4): error TS1005: ',' expected. -==== tests/cases/compiler/objectLiteralWithSemicolons3.ts (3 errors) ==== +==== tests/cases/compiler/objectLiteralWithSemicolons3.ts (6 errors) ==== var v = { a; + ~ +!!! error TS2304: Cannot find name 'a'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. b; + ~ +!!! error TS2304: Cannot find name 'b'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. c; + ~ +!!! error TS2304: Cannot find name 'c'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons3.js b/tests/baselines/reference/objectLiteralWithSemicolons3.js index d9d6d9bc842..30fab228041 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons3.js +++ b/tests/baselines/reference/objectLiteralWithSemicolons3.js @@ -7,7 +7,7 @@ var v = { //// [objectLiteralWithSemicolons3.js] var v = { - a: , - b: , - c: + a: a, + b: b, + c: c }; diff --git a/tests/baselines/reference/objectLiteralWithSemicolons3.types b/tests/baselines/reference/objectLiteralWithSemicolons3.types index 5a5fb9e6b5b..7ac9b8002d2 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons3.types +++ b/tests/baselines/reference/objectLiteralWithSemicolons3.types @@ -5,13 +5,10 @@ var v = { a; >a : any -> : any b; >b : any -> : any c; >c : any -> : any } diff --git a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt index 9938f1629b8..e0ea42bb8c1 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt +++ b/tests/baselines/reference/objectLiteralWithSemicolons4.errors.txt @@ -1,9 +1,12 @@ -tests/cases/compiler/objectLiteralWithSemicolons4.ts(3,1): error TS1005: ':' expected. +tests/cases/compiler/objectLiteralWithSemicolons4.ts(2,3): error TS2304: Cannot find name 'a'. +tests/cases/compiler/objectLiteralWithSemicolons4.ts(3,1): error TS1005: ',' expected. -==== tests/cases/compiler/objectLiteralWithSemicolons4.ts (1 errors) ==== +==== tests/cases/compiler/objectLiteralWithSemicolons4.ts (2 errors) ==== var v = { a + ~ +!!! error TS2304: Cannot find name 'a'. ; ~ -!!! error TS1005: ':' expected. \ No newline at end of file +!!! error TS1005: ',' expected. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralWithSemicolons4.js b/tests/baselines/reference/objectLiteralWithSemicolons4.js index 9e1e3dea4b9..f4dd2c10790 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons4.js +++ b/tests/baselines/reference/objectLiteralWithSemicolons4.js @@ -5,5 +5,5 @@ var v = { //// [objectLiteralWithSemicolons4.js] var v = { - a: + a: a }; diff --git a/tests/baselines/reference/objectLiteralWithSemicolons4.types b/tests/baselines/reference/objectLiteralWithSemicolons4.types index ef6b32838b2..a1809f439f1 100644 --- a/tests/baselines/reference/objectLiteralWithSemicolons4.types +++ b/tests/baselines/reference/objectLiteralWithSemicolons4.types @@ -7,5 +7,3 @@ var v = { >a : any ; -> : any - diff --git a/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.errors.txt b/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.errors.txt index 8215f418cdc..4fe18485a2d 100644 --- a/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.errors.txt +++ b/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.errors.txt @@ -4,7 +4,8 @@ tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/asyncGeneratorSetA tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitInParameterInitializerIsError.ts(2,19): error TS2524: 'await' expressions cannot be used in a parameter initializer. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitMissingValueIsError.ts(3,14): error TS1109: Expression expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(2,15): error TS1138: Parameter declaration expected. -tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(2,20): error TS1005: ':' expected. +tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(2,15): error TS2693: 'await' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(2,20): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(2,22): error TS1136: Property assignment expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts(4,1): error TS1128: Declaration or statement expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/nestedFunctionDeclarationNamedAwaitIsError.ts(3,18): error TS1003: Identifier expected. @@ -19,7 +20,8 @@ tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/nestedFunctionExpr tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/nestedFunctionExpressionNamedYieldIsError.ts(3,36): error TS1005: '=>' expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldInParameterInitializerIsError.ts(2,19): error TS2523: 'yield' expressions cannot be used in a parameter initializer. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(2,15): error TS1138: Parameter declaration expected. -tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(2,20): error TS1005: ':' expected. +tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(2,15): error TS2693: 'yield' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(2,20): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(2,22): error TS1136: Property assignment expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts(4,1): error TS1128: Declaration or statement expected. tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldStarMissingValueIsError.ts(3,16): error TS1109: Expression expected. @@ -40,26 +42,30 @@ tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldStarMissingVa async * yield() { } }; -==== tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts (4 errors) ==== +==== tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitParameterIsError.ts (5 errors) ==== const o4 = { async * f(await) { ~~~~~ !!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2693: 'await' only refers to a type, but is being used as a value here. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. ~ !!! error TS1136: Property assignment expected. } }; ~ !!! error TS1128: Declaration or statement expected. -==== tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts (4 errors) ==== +==== tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts (5 errors) ==== const o5 = { async * f(yield) { ~~~~~ !!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2693: 'yield' only refers to a type, but is being used as a value here. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. ~ !!! error TS1136: Property assignment expected. } diff --git a/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.types b/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.types index 43a6dbfc878..4cdaa6c1813 100644 --- a/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.types +++ b/tests/baselines/reference/parser.asyncGenerators.objectLiteralMethods.esnext.types @@ -33,7 +33,6 @@ const o4 = { async * f(await) { >f : () => any >await : any -> : any } }; === tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/yieldParameterIsError.ts === @@ -44,7 +43,6 @@ const o5 = { async * f(yield) { >f : () => any >yield : any -> : any } }; === tests/cases/conformance/parser/ecmascriptnext/asyncGenerators/awaitInParameterInitializerIsError.ts === diff --git a/tests/baselines/reference/parser512097.errors.txt b/tests/baselines/reference/parser512097.errors.txt index 87f8a5af151..5a25284ba51 100644 --- a/tests/baselines/reference/parser512097.errors.txt +++ b/tests/baselines/reference/parser512097.errors.txt @@ -1,10 +1,13 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,14): error TS1005: ':' expected. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,12): error TS2304: Cannot find name 'aa'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts(1,14): error TS1005: ',' expected. -==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts (1 errors) ==== - var tt = { aa; } // After this point, no useful parsing occurs in the entire file +==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts (2 errors) ==== + var tt = { aa; } + ~~ +!!! error TS2304: Cannot find name 'aa'. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. if (true) { } \ No newline at end of file diff --git a/tests/baselines/reference/parser512097.js b/tests/baselines/reference/parser512097.js index ce73dadf3bc..3f1b5e4f18b 100644 --- a/tests/baselines/reference/parser512097.js +++ b/tests/baselines/reference/parser512097.js @@ -1,10 +1,10 @@ //// [parser512097.ts] -var tt = { aa; } // After this point, no useful parsing occurs in the entire file +var tt = { aa; } if (true) { } //// [parser512097.js] -var tt = { aa: }; // After this point, no useful parsing occurs in the entire file +var tt = { aa: aa }; if (true) { } diff --git a/tests/baselines/reference/parser512097.symbols b/tests/baselines/reference/parser512097.symbols index c8da7e09782..ffaa758f7d3 100644 --- a/tests/baselines/reference/parser512097.symbols +++ b/tests/baselines/reference/parser512097.symbols @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts === -var tt = { aa; } // After this point, no useful parsing occurs in the entire file +var tt = { aa; } >tt : Symbol(tt, Decl(parser512097.ts, 0, 3)) >aa : Symbol(aa, Decl(parser512097.ts, 0, 10)) diff --git a/tests/baselines/reference/parser512097.types b/tests/baselines/reference/parser512097.types index 8f41a4ff2ce..7cdf4ec6117 100644 --- a/tests/baselines/reference/parser512097.types +++ b/tests/baselines/reference/parser512097.types @@ -1,9 +1,8 @@ === tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts === -var tt = { aa; } // After this point, no useful parsing occurs in the entire file +var tt = { aa; } >tt : { aa: any; } >{ aa; } : { aa: any; } >aa : any -> : any if (true) { >true : true diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt index 770fee897d3..8be4448ae52 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.errors.txt @@ -1,13 +1,16 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,1): error TS1005: ':' expected. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(1,11): error TS2304: Cannot find name 'a'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,1): error TS1005: ',' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,7): error TS1005: ':' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts(2,8): error TS1005: '}' expected. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ObjectLiterals/parserErrorRecovery_ObjectLiteral2.ts (4 errors) ==== var v = { a + ~ +!!! error TS2304: Cannot find name 'a'. return; ~~~~~~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. ~ !!! error TS1005: ':' expected. diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js index c206a30237a..1cdf73ddadc 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js @@ -3,5 +3,5 @@ var v = { a return; //// [parserErrorRecovery_ObjectLiteral2.js] -var v = { a: , +var v = { a: a, "return": }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.types b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.types index 172444e5cf6..3ec1cd8a69f 100644 --- a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.types +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.types @@ -5,7 +5,6 @@ var v = { a >a : any return; -> : any >return : any > : any diff --git a/tests/baselines/reference/privateIndexer2.errors.txt b/tests/baselines/reference/privateIndexer2.errors.txt index 7e826dbc7a9..80ddea93148 100644 --- a/tests/baselines/reference/privateIndexer2.errors.txt +++ b/tests/baselines/reference/privateIndexer2.errors.txt @@ -2,10 +2,11 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15) tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,23): error TS1005: ',' expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1136: Property assignment expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ':' expected. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,26): error TS2693: 'string' only refers to a type, but is being used as a value here. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ',' expected. -==== tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts (5 errors) ==== +==== tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts (6 errors) ==== // private indexers not allowed var x = { @@ -18,8 +19,10 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32) !!! error TS1005: ',' expected. ~ !!! error TS1136: Property assignment expected. + ~~~~~~ +!!! error TS2693: 'string' only refers to a type, but is being used as a value here. ~ -!!! error TS1005: ':' expected. +!!! error TS1005: ',' expected. } var y: { diff --git a/tests/baselines/reference/privateIndexer2.js b/tests/baselines/reference/privateIndexer2.js index 3613d2715c2..18840d02d9d 100644 --- a/tests/baselines/reference/privateIndexer2.js +++ b/tests/baselines/reference/privateIndexer2.js @@ -14,6 +14,6 @@ var y: { var _a; var x = (_a = {}, _a[x] = string, - _a.string = , + _a.string = string, _a); var y; diff --git a/tests/baselines/reference/privateIndexer2.types b/tests/baselines/reference/privateIndexer2.types index fcfabc3f799..98ade7651ae 100644 --- a/tests/baselines/reference/privateIndexer2.types +++ b/tests/baselines/reference/privateIndexer2.types @@ -10,7 +10,6 @@ var x = { >x : any >string : any >string : any -> : any } var y: { diff --git a/tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts b/tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts index b9f4552ca7e..f94d41edcfd 100644 --- a/tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts +++ b/tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512097.ts @@ -1,4 +1,4 @@ -var tt = { aa; } // After this point, no useful parsing occurs in the entire file +var tt = { aa; } if (true) { } \ No newline at end of file diff --git a/tests/cases/fourslash/completionsAtIncompleteObjectLiteralProperty.ts b/tests/cases/fourslash/completionsAtIncompleteObjectLiteralProperty.ts new file mode 100644 index 00000000000..130b70de949 --- /dev/null +++ b/tests/cases/fourslash/completionsAtIncompleteObjectLiteralProperty.ts @@ -0,0 +1,14 @@ +/// + +// @noLib: true + +////f({ +//// a/**/ +//// xyz: ``, +////}); +////declare function f(options: { abc?: number, xyz?: string }): void; + +verify.completions({ + marker: "", + exact: ["abc"], +}); From 24e37452960358a592c8a7526fc3d2081f78f388 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Oct 2018 15:32:10 -0700 Subject: [PATCH 131/262] Add regression test --- .../cases/conformance/types/mapped/mappedTypeErrors.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/cases/conformance/types/mapped/mappedTypeErrors.ts b/tests/cases/conformance/types/mapped/mappedTypeErrors.ts index cec1fbf8395..a38979054ec 100644 --- a/tests/cases/conformance/types/mapped/mappedTypeErrors.ts +++ b/tests/cases/conformance/types/mapped/mappedTypeErrors.ts @@ -144,3 +144,13 @@ let f: Foo2 = { pf: {x: 7}, pt: {x: 7, y: false}, }; + +// Repro from #28170 + +function test1(obj: Pick) { + let x = obj.foo; // Error +} + +function test2(obj: Record) { + let x = obj.foo; // Error +} From 00fbdedbccdb2daf10ee56ed0793ecc1d7a1d727 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 26 Oct 2018 15:32:18 -0700 Subject: [PATCH 132/262] Accept new baselines --- .../reference/mappedTypeErrors.errors.txt | 18 ++++++++++- tests/baselines/reference/mappedTypeErrors.js | 19 ++++++++++++ .../reference/mappedTypeErrors.symbols | 31 +++++++++++++++++++ .../reference/mappedTypeErrors.types | 24 ++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) diff --git a/tests/baselines/reference/mappedTypeErrors.errors.txt b/tests/baselines/reference/mappedTypeErrors.errors.txt index 6d78b229fa4..a59859875bd 100644 --- a/tests/baselines/reference/mappedTypeErrors.errors.txt +++ b/tests/baselines/reference/mappedTypeErrors.errors.txt @@ -39,9 +39,11 @@ tests/cases/conformance/types/mapped/mappedTypeErrors.ts(130,39): error TS2322: tests/cases/conformance/types/mapped/mappedTypeErrors.ts(136,16): error TS2322: Type 'T' is not assignable to type 'string | number | symbol'. Type 'T' is not assignable to type 'symbol'. tests/cases/conformance/types/mapped/mappedTypeErrors.ts(136,21): error TS2536: Type 'P' cannot be used to index type 'T'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(148,17): error TS2339: Property 'foo' does not exist on type 'Pick'. +tests/cases/conformance/types/mapped/mappedTypeErrors.ts(152,17): error TS2339: Property 'foo' does not exist on type 'Record'. -==== tests/cases/conformance/types/mapped/mappedTypeErrors.ts (25 errors) ==== +==== tests/cases/conformance/types/mapped/mappedTypeErrors.ts (27 errors) ==== interface Shape { name: string; width: number; @@ -256,4 +258,18 @@ tests/cases/conformance/types/mapped/mappedTypeErrors.ts(136,21): error TS2536: pf: {x: 7}, pt: {x: 7, y: false}, }; + + // Repro from #28170 + + function test1(obj: Pick) { + let x = obj.foo; // Error + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Pick'. + } + + function test2(obj: Record) { + let x = obj.foo; // Error + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Record'. + } \ No newline at end of file diff --git a/tests/baselines/reference/mappedTypeErrors.js b/tests/baselines/reference/mappedTypeErrors.js index bc73780a478..276aeb76a1d 100644 --- a/tests/baselines/reference/mappedTypeErrors.js +++ b/tests/baselines/reference/mappedTypeErrors.js @@ -142,6 +142,16 @@ let f: Foo2 = { pf: {x: 7}, pt: {x: 7, y: false}, }; + +// Repro from #28170 + +function test1(obj: Pick) { + let x = obj.foo; // Error +} + +function test2(obj: Record) { + let x = obj.foo; // Error +} //// [mappedTypeErrors.js] @@ -222,6 +232,13 @@ var f = { pf: { x: 7 }, pt: { x: 7, y: false } }; +// Repro from #28170 +function test1(obj) { + var x = obj.foo; // Error +} +function test2(obj) { + var x = obj.foo; // Error +} //// [mappedTypeErrors.d.ts] @@ -300,3 +317,5 @@ declare type O = { }; declare let o: O; declare let f: Foo2; +declare function test1(obj: Pick): void; +declare function test2(obj: Record): void; diff --git a/tests/baselines/reference/mappedTypeErrors.symbols b/tests/baselines/reference/mappedTypeErrors.symbols index 80ce5d49845..e2f3b577506 100644 --- a/tests/baselines/reference/mappedTypeErrors.symbols +++ b/tests/baselines/reference/mappedTypeErrors.symbols @@ -540,3 +540,34 @@ let f: Foo2 = { }; +// Repro from #28170 + +function test1(obj: Pick) { +>test1 : Symbol(test1, Decl(mappedTypeErrors.ts, 142, 2)) +>T : Symbol(T, Decl(mappedTypeErrors.ts, 146, 15)) +>K : Symbol(K, Decl(mappedTypeErrors.ts, 146, 17)) +>T : Symbol(T, Decl(mappedTypeErrors.ts, 146, 15)) +>obj : Symbol(obj, Decl(mappedTypeErrors.ts, 146, 37)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypeErrors.ts, 146, 15)) +>K : Symbol(K, Decl(mappedTypeErrors.ts, 146, 17)) + + let x = obj.foo; // Error +>x : Symbol(x, Decl(mappedTypeErrors.ts, 147, 7)) +>obj : Symbol(obj, Decl(mappedTypeErrors.ts, 146, 37)) +} + +function test2(obj: Record) { +>test2 : Symbol(test2, Decl(mappedTypeErrors.ts, 148, 1)) +>T : Symbol(T, Decl(mappedTypeErrors.ts, 150, 15)) +>K : Symbol(K, Decl(mappedTypeErrors.ts, 150, 17)) +>T : Symbol(T, Decl(mappedTypeErrors.ts, 150, 15)) +>obj : Symbol(obj, Decl(mappedTypeErrors.ts, 150, 37)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>K : Symbol(K, Decl(mappedTypeErrors.ts, 150, 17)) + + let x = obj.foo; // Error +>x : Symbol(x, Decl(mappedTypeErrors.ts, 151, 7)) +>obj : Symbol(obj, Decl(mappedTypeErrors.ts, 150, 37)) +} + diff --git a/tests/baselines/reference/mappedTypeErrors.types b/tests/baselines/reference/mappedTypeErrors.types index c1ae7399137..cfa0df3cd58 100644 --- a/tests/baselines/reference/mappedTypeErrors.types +++ b/tests/baselines/reference/mappedTypeErrors.types @@ -501,3 +501,27 @@ let f: Foo2 = { }; +// Repro from #28170 + +function test1(obj: Pick) { +>test1 : (obj: Pick) => void +>obj : Pick + + let x = obj.foo; // Error +>x : any +>obj.foo : any +>obj : Pick +>foo : any +} + +function test2(obj: Record) { +>test2 : (obj: Record) => void +>obj : Record + + let x = obj.foo; // Error +>x : any +>obj.foo : any +>obj : Record +>foo : any +} + From 972c403cd84cf0327d9f87238c2feb03ad51442a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 26 Oct 2018 16:01:32 -0700 Subject: [PATCH 133/262] JSX uses mixed signatures and union sigs use subtype on partial match (#28141) * JSX uses mixed signatures and union sigs use subtype on partial match * Small improvement --- src/compiler/checker.ts | 60 ++++++++++++------- src/compiler/types.ts | 7 +++ .../tsxInvokeComponentType.errors.txt | 22 +++++++ .../reference/tsxInvokeComponentType.js | 25 ++++++++ .../reference/tsxInvokeComponentType.symbols | 30 ++++++++++ .../reference/tsxInvokeComponentType.types | 31 ++++++++++ .../tsxUnionTypeComponent1.errors.txt | 29 --------- .../cases/compiler/tsxInvokeComponentType.tsx | 14 +++++ 8 files changed, 169 insertions(+), 49 deletions(-) create mode 100644 tests/baselines/reference/tsxInvokeComponentType.errors.txt create mode 100644 tests/baselines/reference/tsxInvokeComponentType.js create mode 100644 tests/baselines/reference/tsxInvokeComponentType.symbols create mode 100644 tests/baselines/reference/tsxInvokeComponentType.types delete mode 100644 tests/baselines/reference/tsxUnionTypeComponent1.errors.txt create mode 100644 tests/cases/compiler/tsxInvokeComponentType.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7531dd926ff..0a7d7c19293 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6567,7 +6567,7 @@ namespace ts { function findMatchingSignature(signatureList: ReadonlyArray, signature: Signature, partialMatch: boolean, ignoreThisTypes: boolean, ignoreReturnTypes: boolean): Signature | undefined { for (const s of signatureList) { - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) { return s; } } @@ -6603,8 +6603,7 @@ namespace ts { // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. - function getUnionSignatures(types: ReadonlyArray, kind: SignatureKind): Signature[] { - const signatureLists = map(types, t => getSignaturesOfType(t, kind)); + function getUnionSignatures(signatureLists: ReadonlyArray>): Signature[] { let result: Signature[] | undefined; for (let i = 0; i < signatureLists.length; i++) { for (const signature of signatureLists[i]) { @@ -6650,8 +6649,8 @@ namespace ts { function resolveUnionTypeMembers(type: UnionType) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - const callSignatures = getUnionSignatures(type.types, SignatureKind.Call); - const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); + const callSignatures = getUnionSignatures(map(type.types, t => getSignaturesOfType(t, SignatureKind.Call))); + const constructSignatures = getUnionSignatures(map(type.types, t => getSignaturesOfType(t, SignatureKind.Construct))); const stringIndexInfo = getUnionIndexInfo(type.types, IndexKind.String); const numberIndexInfo = getUnionIndexInfo(type.types, IndexKind.Number); setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); @@ -10691,6 +10690,10 @@ namespace ts { return isTypeRelatedTo(source, target, assignableRelation) ? Ternary.True : Ternary.False; } + function compareTypesSubtypeOf(source: Type, target: Type): Ternary { + return isTypeRelatedTo(source, target, subtypeRelation) ? Ternary.True : Ternary.False; + } + function isTypeSubtypeOf(source: Type, target: Type): boolean { return isTypeRelatedTo(source, target, subtypeRelation); } @@ -12880,7 +12883,7 @@ namespace ts { for (let i = 0; i < targetLen; i++) { const s = getTypeAtPosition(source, i); const t = getTypeAtPosition(target, i); - const related = compareTypes(s, t); + const related = compareTypes(t, s); if (!related) { return Ternary.False; } @@ -17108,7 +17111,7 @@ namespace ts { } function getEffectiveFirstArgumentForJsxSignature(signature: Signature, node: JsxOpeningLikeElement) { - return isJsxStatelessFunctionReference(node) ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + return getJsxReferenceKind(node) !== JsxReferenceKind.Component ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig: Signature, context: JsxOpeningLikeElement) { @@ -18004,13 +18007,17 @@ namespace ts { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getUninstantiatedJsxSignaturesOfType(elementType: Type) { + function getUninstantiatedJsxSignaturesOfType(elementType: Type): ReadonlyArray { // Resolve the signatures, preferring constructor let signatures = getSignaturesOfType(elementType, SignatureKind.Construct); if (signatures.length === 0) { // No construct signatures, try call signatures signatures = getSignaturesOfType(elementType, SignatureKind.Call); } + if (signatures.length === 0 && elementType.flags & TypeFlags.Union) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(map((elementType as UnionType).types, getUninstantiatedJsxSignaturesOfType)); + } return signatures; } @@ -18036,20 +18043,29 @@ namespace ts { return anyType; } - function checkJsxReturnAssignableToAppropriateBound(isSFC: boolean, elemInstanceType: Type, openingLikeElement: Node) { - if (isSFC) { + function checkJsxReturnAssignableToAppropriateBound(refKind: JsxReferenceKind, elemInstanceType: Type, openingLikeElement: Node) { + if (refKind === JsxReferenceKind.Function) { const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } } - else { + else if (refKind === JsxReferenceKind.Component) { const classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } } + else { // Mixed + const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); + const classConstraint = getJsxElementClassTypeAt(openingLikeElement); + if (!sfcReturnConstraint || !classConstraint) { + return; + } + const combined = getUnionType([sfcReturnConstraint, classConstraint]); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } } /** @@ -18139,7 +18155,7 @@ namespace ts { if (isNodeOpeningLikeElement) { const sig = getResolvedSignature(node as JsxOpeningLikeElement); - checkJsxReturnAssignableToAppropriateBound(isJsxStatelessFunctionReference(node as JsxOpeningLikeElement), getReturnTypeOfSignature(sig), node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node as JsxOpeningLikeElement), getReturnTypeOfSignature(sig), node); } } @@ -19174,12 +19190,18 @@ namespace ts { return typeArgumentTypes; } - function isJsxStatelessFunctionReference(node: JsxOpeningLikeElement) { + function getJsxReferenceKind(node: JsxOpeningLikeElement): JsxReferenceKind { if (isJsxIntrinsicIdentifier(node.tagName)) { - return true; + return JsxReferenceKind.Mixed; } - const tagType = checkExpression(node.tagName); - return !length(getSignaturesOfType(getApparentType(tagType), SignatureKind.Construct)); + const tagType = getApparentType(checkExpression(node.tagName)); + if (length(getSignaturesOfType(tagType, SignatureKind.Construct))) { + return JsxReferenceKind.Component; + } + if (length(getSignaturesOfType(tagType, SignatureKind.Call))) { + return JsxReferenceKind.Function; + } + return JsxReferenceKind.Mixed; } /** @@ -20182,13 +20204,11 @@ namespace ts { } } - const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); - if (exprTypes.flags & TypeFlags.String || isUntypedFunctionCall(exprTypes, apparentType, callSignatures.length, constructSignatures.length)) { + const signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & TypeFlags.String || isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) { return resolveUntypedCall(node); } - const signatures = getUninstantiatedJsxSignaturesOfType(apparentType); if (signatures.length === 0) { // We found no signatures at all, which is an error error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index d382436ae42..d6ef05d7007 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4217,6 +4217,13 @@ namespace ts { substitute: Type; // Type to substitute for type parameter } + /* @internal */ + export const enum JsxReferenceKind { + Component, + Function, + Mixed + } + export const enum SignatureKind { Call, Construct, diff --git a/tests/baselines/reference/tsxInvokeComponentType.errors.txt b/tests/baselines/reference/tsxInvokeComponentType.errors.txt new file mode 100644 index 00000000000..75f9e4ad5d6 --- /dev/null +++ b/tests/baselines/reference/tsxInvokeComponentType.errors.txt @@ -0,0 +1,22 @@ +tests/cases/compiler/tsxInvokeComponentType.tsx(6,14): error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { someKey: string; } & { children?: ReactNode; }'. + Type '{}' is not assignable to type '{ someKey: string; }'. + Property 'someKey' is missing in type '{}'. + + +==== tests/cases/compiler/tsxInvokeComponentType.tsx (1 errors) ==== + /// + import React, { ComponentType } from "react"; + + declare const Elem: ComponentType<{ someKey: string }>; + + const bad = ; + ~~~~ +!!! error TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & { someKey: string; } & { children?: ReactNode; }'. +!!! error TS2322: Type '{}' is not assignable to type '{ someKey: string; }'. +!!! error TS2322: Property 'someKey' is missing in type '{}'. + + const good = ; + + declare const Elem2: ComponentType<{ opt?: number }>; + const alsoOk = text; + \ No newline at end of file diff --git a/tests/baselines/reference/tsxInvokeComponentType.js b/tests/baselines/reference/tsxInvokeComponentType.js new file mode 100644 index 00000000000..613ef8f26c5 --- /dev/null +++ b/tests/baselines/reference/tsxInvokeComponentType.js @@ -0,0 +1,25 @@ +//// [tsxInvokeComponentType.tsx] +/// +import React, { ComponentType } from "react"; + +declare const Elem: ComponentType<{ someKey: string }>; + +const bad = ; + +const good = ; + +declare const Elem2: ComponentType<{ opt?: number }>; +const alsoOk = text; + + +//// [tsxInvokeComponentType.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +/// +var react_1 = __importDefault(require("react")); +var bad = react_1["default"].createElement(Elem, null); +var good = react_1["default"].createElement(Elem, { someKey: "ok" }); +var alsoOk = react_1["default"].createElement(Elem2, null, "text"); diff --git a/tests/baselines/reference/tsxInvokeComponentType.symbols b/tests/baselines/reference/tsxInvokeComponentType.symbols new file mode 100644 index 00000000000..34501acc673 --- /dev/null +++ b/tests/baselines/reference/tsxInvokeComponentType.symbols @@ -0,0 +1,30 @@ +=== tests/cases/compiler/tsxInvokeComponentType.tsx === +/// +import React, { ComponentType } from "react"; +>React : Symbol(React, Decl(tsxInvokeComponentType.tsx, 1, 6)) +>ComponentType : Symbol(ComponentType, Decl(tsxInvokeComponentType.tsx, 1, 15)) + +declare const Elem: ComponentType<{ someKey: string }>; +>Elem : Symbol(Elem, Decl(tsxInvokeComponentType.tsx, 3, 13)) +>ComponentType : Symbol(ComponentType, Decl(tsxInvokeComponentType.tsx, 1, 15)) +>someKey : Symbol(someKey, Decl(tsxInvokeComponentType.tsx, 3, 35)) + +const bad = ; +>bad : Symbol(bad, Decl(tsxInvokeComponentType.tsx, 5, 5)) +>Elem : Symbol(Elem, Decl(tsxInvokeComponentType.tsx, 3, 13)) + +const good = ; +>good : Symbol(good, Decl(tsxInvokeComponentType.tsx, 7, 5)) +>Elem : Symbol(Elem, Decl(tsxInvokeComponentType.tsx, 3, 13)) +>someKey : Symbol(someKey, Decl(tsxInvokeComponentType.tsx, 7, 18)) + +declare const Elem2: ComponentType<{ opt?: number }>; +>Elem2 : Symbol(Elem2, Decl(tsxInvokeComponentType.tsx, 9, 13)) +>ComponentType : Symbol(ComponentType, Decl(tsxInvokeComponentType.tsx, 1, 15)) +>opt : Symbol(opt, Decl(tsxInvokeComponentType.tsx, 9, 36)) + +const alsoOk = text; +>alsoOk : Symbol(alsoOk, Decl(tsxInvokeComponentType.tsx, 10, 5)) +>Elem2 : Symbol(Elem2, Decl(tsxInvokeComponentType.tsx, 9, 13)) +>Elem2 : Symbol(Elem2, Decl(tsxInvokeComponentType.tsx, 9, 13)) + diff --git a/tests/baselines/reference/tsxInvokeComponentType.types b/tests/baselines/reference/tsxInvokeComponentType.types new file mode 100644 index 00000000000..a8cad986828 --- /dev/null +++ b/tests/baselines/reference/tsxInvokeComponentType.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/tsxInvokeComponentType.tsx === +/// +import React, { ComponentType } from "react"; +>React : typeof React +>ComponentType : any + +declare const Elem: ComponentType<{ someKey: string }>; +>Elem : React.ComponentType<{ someKey: string; }> +>someKey : string + +const bad = ; +>bad : JSX.Element +> : JSX.Element +>Elem : React.ComponentType<{ someKey: string; }> + +const good = ; +>good : JSX.Element +> : JSX.Element +>Elem : React.ComponentType<{ someKey: string; }> +>someKey : string + +declare const Elem2: ComponentType<{ opt?: number }>; +>Elem2 : React.ComponentType<{ opt?: number | undefined; }> +>opt : number | undefined + +const alsoOk = text; +>alsoOk : JSX.Element +>text : JSX.Element +>Elem2 : React.ComponentType<{ opt?: number | undefined; }> +>Elem2 : React.ComponentType<{ opt?: number | undefined; }> + diff --git a/tests/baselines/reference/tsxUnionTypeComponent1.errors.txt b/tests/baselines/reference/tsxUnionTypeComponent1.errors.txt deleted file mode 100644 index 564f7ec3d39..00000000000 --- a/tests/baselines/reference/tsxUnionTypeComponent1.errors.txt +++ /dev/null @@ -1,29 +0,0 @@ -tests/cases/conformance/jsx/file.tsx(10,18): error TS2604: JSX element type 'AnyComponent' does not have any construct or call signatures. - - -==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== - import React = require('react'); - - interface ComponentProps { - AnyComponent: React.StatelessComponent | React.ComponentClass; - } - - class MyComponent extends React.Component { - render() { - const { AnyComponent } = this.props; - return (); - ~~~~~~~~~~~~ -!!! error TS2604: JSX element type 'AnyComponent' does not have any construct or call signatures. - } - } - - // Stateless Component As Props - }/> - - // Component Class as Props - class MyButtonComponent extends React.Component<{},{}> { - } - - - - \ No newline at end of file diff --git a/tests/cases/compiler/tsxInvokeComponentType.tsx b/tests/cases/compiler/tsxInvokeComponentType.tsx new file mode 100644 index 00000000000..dcb4a30a002 --- /dev/null +++ b/tests/cases/compiler/tsxInvokeComponentType.tsx @@ -0,0 +1,14 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// +import React, { ComponentType } from "react"; + +declare const Elem: ComponentType<{ someKey: string }>; + +const bad = ; + +const good = ; + +declare const Elem2: ComponentType<{ opt?: number }>; +const alsoOk = text; From e2100cd2cc6ba488cdd2a4bf055d78e2af4f0b5f Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 26 Oct 2018 16:26:20 -0700 Subject: [PATCH 134/262] Measure variance of aliased conditional types using variance markers (#27804) * Measure variance of aliased conditional types using variance markers * Just do variance probing for all type aliases * Small limiter for predictability * Inline property set, remove unused functions --- src/compiler/checker.ts | 150 +++--- src/compiler/types.ts | 2 + .../conditionalTypeDoesntSpinForever.js | 152 ++++++ .../conditionalTypeDoesntSpinForever.symbols | 489 ++++++++++++++++++ .../conditionalTypeDoesntSpinForever.types | 487 +++++++++++++++++ .../reference/conditionalTypes1.errors.txt | 8 - .../strictFunctionTypesErrors.errors.txt | 4 - .../conditionalTypeDoesntSpinForever.ts | 119 +++++ 8 files changed, 1336 insertions(+), 75 deletions(-) create mode 100644 tests/baselines/reference/conditionalTypeDoesntSpinForever.js create mode 100644 tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols create mode 100644 tests/baselines/reference/conditionalTypeDoesntSpinForever.types create mode 100644 tests/cases/compiler/conditionalTypeDoesntSpinForever.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2cce7cd2727..e5a8d8ee460 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7636,35 +7636,35 @@ namespace ts { * @param typeParameters The requested type parameters. * @param minTypeArgumentCount The minimum number of required type arguments. */ - function fillMissingTypeArguments(typeArguments: Type[], typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; - function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; - function fillMissingTypeArguments(typeArguments: Type[] | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { + function fillMissingTypeArguments(typeArguments: ReadonlyArray, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[]; + function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean): Type[] | undefined; + function fillMissingTypeArguments(typeArguments: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, minTypeArgumentCount: number, isJavaScriptImplicitAny: boolean) { const numTypeParameters = length(typeParameters); - if (numTypeParameters) { - const numTypeArguments = length(typeArguments); - if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { - if (!typeArguments) { - typeArguments = []; - } - - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (let i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - for (let i = numTypeArguments; i < numTypeParameters; i++) { - const mapper = createTypeMapper(typeParameters!, typeArguments); - let defaultType = getDefaultFromTypeParameter(typeParameters![i]); - if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { - defaultType = anyType; - } - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); - } - typeArguments.length = typeParameters!.length; - } + if (!numTypeParameters) { + return []; } - return typeArguments; + const numTypeArguments = length(typeArguments); + if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { + const result = typeArguments ? typeArguments.slice() : []; + + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + for (let i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + } + for (let i = numTypeArguments; i < numTypeParameters; i++) { + const mapper = createTypeMapper(typeParameters!, result); + let defaultType = getDefaultFromTypeParameter(typeParameters![i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); + } + result.length = typeParameters!.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration: SignatureDeclaration | JSDocSignature): Signature { @@ -8262,7 +8262,7 @@ namespace ts { return checkNoTypeArguments(node, symbol) ? type : errorType; } - function getTypeAliasInstantiation(symbol: Symbol, typeArguments: Type[] | undefined): Type { + function getTypeAliasInstantiation(symbol: Symbol, typeArguments: ReadonlyArray | undefined): Type { const type = getDeclaredTypeOfSymbol(symbol); const links = getSymbolLinks(symbol); const typeParameters = links.typeParameters!; @@ -11783,9 +11783,7 @@ namespace ts { return result; } - function typeArgumentsRelatedTo(source: TypeReference, target: TypeReference, variances: Variance[], reportErrors: boolean): Ternary { - const sources = source.typeArguments || emptyArray; - const targets = target.typeArguments || emptyArray; + function typeArgumentsRelatedTo(sources: ReadonlyArray = emptyArray, targets: ReadonlyArray = emptyArray, variances: ReadonlyArray = emptyArray, reportErrors: boolean): Ternary { if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } @@ -11938,9 +11936,25 @@ namespace ts { } return Ternary.False; } + let result: Ternary; let originalErrorInfo: DiagnosticMessageChain | undefined; const saveErrorInfo = errorInfo; + + // We limit alias variance probing to only object and conditional types since their alias behavior + // is more predictable than other, interned types, which may or may not have an alias depending on + // the order in which things were checked. + if (source.flags & (TypeFlags.Object | TypeFlags.Conditional) && source.aliasSymbol && + source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && + !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { + const variances = getAliasVariances(source.aliasSymbol); + if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { + return result; + } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + if (target.flags & TypeFlags.TypeParameter) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. if (getObjectFlags(source) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(source) === getIndexType(target)) { @@ -12101,7 +12115,7 @@ namespace ts { // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. const variances = getVariances((source).target); - if (result = typeArgumentsRelatedTo(source, target, variances, reportErrors)) { + if (result = typeArgumentsRelatedTo((source).typeArguments, (target).typeArguments, variances, reportErrors)) { return result; } // The type arguments did not relate appropriately, but it may be because we have no variance @@ -12608,48 +12622,58 @@ namespace ts { return result; } + function getAliasVariances(symbol: Symbol) { + const links = getSymbolLinks(symbol); + return getVariancesWorker(links.typeParameters, links, (_links, param, marker) => { + const type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters!, makeUnaryTypeMapper(param, marker))); + type.aliasTypeArgumentsContainsMarker = true; + return type; + }); + } + // Return an array containing the variance of each type parameter. The variance is effectively // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function // has been invoked recursively for the given generic type. + function getVariancesWorker(typeParameters: ReadonlyArray = emptyArray, cache: TCache, createMarkerType: (input: TCache, param: TypeParameter, marker: Type) => Type): Variance[] { + let variances = cache.variances; + if (!variances) { + // The emptyArray singleton is used to signal a recursive invocation. + cache.variances = emptyArray; + variances = []; + for (const tp of typeParameters) { + // We first compare instantiations where the type parameter is replaced with + // marker types that have a known subtype relationship. From this we can infer + // invariance, covariance, contravariance or bivariance. + const typeWithSuper = createMarkerType(cache, tp, markerSuperType); + const typeWithSub = createMarkerType(cache, tp, markerSubType); + let variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? Variance.Covariant : 0) | + (isTypeAssignableTo(typeWithSuper, typeWithSub) ? Variance.Contravariant : 0); + // If the instantiations appear to be related bivariantly it may be because the + // type parameter is independent (i.e. it isn't witnessed anywhere in the generic + // type). To determine this we compare instantiations where the type parameter is + // replaced with marker types that are known to be unrelated. + if (variance === Variance.Bivariant && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) { + variance = Variance.Independent; + } + variances.push(variance); + } + cache.variances = variances; + } + return variances; + } + function getVariances(type: GenericType): Variance[] { if (!strictFunctionTypes) { return emptyArray; } - const typeParameters = type.typeParameters || emptyArray; - let variances = type.variances; - if (!variances) { - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this - variances = [Variance.Covariant]; - } - else { - // The emptyArray singleton is used to signal a recursive invocation. - type.variances = emptyArray; - variances = []; - for (const tp of typeParameters) { - // We first compare instantiations where the type parameter is replaced with - // marker types that have a known subtype relationship. From this we can infer - // invariance, covariance, contravariance or bivariance. - const typeWithSuper = getMarkerTypeReference(type, tp, markerSuperType); - const typeWithSub = getMarkerTypeReference(type, tp, markerSubType); - let variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? Variance.Covariant : 0) | - (isTypeAssignableTo(typeWithSuper, typeWithSub) ? Variance.Contravariant : 0); - // If the instantiations appear to be related bivariantly it may be because the - // type parameter is independent (i.e. it isn't witnessed anywhere in the generic - // type). To determine this we compare instantiations where the type parameter is - // replaced with marker types that are known to be unrelated. - if (variance === Variance.Bivariant && isTypeAssignableTo(getMarkerTypeReference(type, tp, markerOtherType), typeWithSuper)) { - variance = Variance.Independent; - } - variances.push(variance); - } - } - type.variances = variances; + if (type === globalArrayType || type === globalReadonlyArrayType) { + // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + return emptyArray; } - return variances; + return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. diff --git a/src/compiler/types.ts b/src/compiler/types.ts index d6ef05d7007..e7d20bfc249 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3647,6 +3647,7 @@ namespace ts { originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol` lateSymbol?: Symbol; // Late-bound symbol for a computed property specifierCache?: Map; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings + variances?: Variance[]; // Alias symbol type argument variance cache } /* @internal */ @@ -3899,6 +3900,7 @@ namespace ts { pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) aliasSymbol?: Symbol; // Alias associated with type aliasTypeArguments?: ReadonlyArray; // Alias type arguments (if any) + /* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any) /* @internal */ wildcardInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type /* @internal */ diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.js b/tests/baselines/reference/conditionalTypeDoesntSpinForever.js new file mode 100644 index 00000000000..144503ac94b --- /dev/null +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.js @@ -0,0 +1,152 @@ +//// [conditionalTypeDoesntSpinForever.ts] +// A *self-contained* demonstration of the problem follows... +// Test this by running `tsc --target es6` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. + +export enum PubSubRecordIsStoredInRedisAsA { + redisHash = "redisHash", + jsonEncodedRedisString = "jsonEncodedRedisString" + } + + export interface PubSubRecord> { + name: NAME; + record: RECORD; + identifier: IDENTIFIER; + storedAs: PubSubRecordIsStoredInRedisAsA; + maxMsToWaitBeforePublishing: number; + } + + type NameFieldConstructor = + SO_FAR extends {name: any} ? {} : { + name: (t?: TYPE) => BuildPubSubRecordType + } + + const buildNameFieldConstructor = (soFar: SO_FAR) => ( + "name" in soFar ? {} : { + name: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType + } + ); + + type StoredAsConstructor = + SO_FAR extends {storedAs: any} ? {} : { + storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; + storedRedisHash: () => BuildPubSubRecordType; + } + + const buildStoredAsConstructor = (soFar: SO_FAR) => ( + "storedAs" in soFar ? {} : { + storedAsJsonEncodedRedisString: () => + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as + BuildPubSubRecordType, + storedAsRedisHash: () => + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as + BuildPubSubRecordType, + } + ); + + type IdentifierFieldConstructor = + SO_FAR extends {identifier: any} ? {} : + SO_FAR extends {record: any} ? { + identifier: >(t?: TYPE) => BuildPubSubRecordType + } : {} + + const buildIdentifierFieldConstructor = (soFar: SO_FAR) => ( + "identifier" in soFar || (!("record" in soFar)) ? {} : { + identifier: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType + } + ); + + type RecordFieldConstructor = + SO_FAR extends {record: any} ? {} : { + record: (t?: TYPE) => BuildPubSubRecordType + } + + const buildRecordFieldConstructor = (soFar: SO_FAR) => ( + "record" in soFar ? {} : { + record: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType + } + ); + + type MaxMsToWaitBeforePublishingFieldConstructor = + SO_FAR extends {maxMsToWaitBeforePublishing: any} ? {} : { + maxMsToWaitBeforePublishing: (t: number) => BuildPubSubRecordType, + neverDelayPublishing: () => BuildPubSubRecordType, + } + + const buildMaxMsToWaitBeforePublishingFieldConstructor = (soFar: SO_FAR): MaxMsToWaitBeforePublishingFieldConstructor => ( + "maxMsToWaitBeforePublishing" in soFar ? {} : { + maxMsToWaitBeforePublishing: (instance: number = 0) => + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, + neverDelayPublishing: () => + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, + } + ) as MaxMsToWaitBeforePublishingFieldConstructor; + + type TypeConstructor = + SO_FAR extends {identifier: any, record: any, maxMsToWaitBeforePublishing: number, storedAs: PubSubRecordIsStoredInRedisAsA} ? { + type: SO_FAR, + fields: Set, + hasField: (fieldName: string | number | symbol) => fieldName is keyof SO_FAR + } : {} + + const buildType = (soFar: SO_FAR) => ( + "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { + type: soFar, + fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), + hasField: (fieldName: string | number | symbol) => fieldName in soFar + } + ); + + type BuildPubSubRecordType = + NameFieldConstructor & + IdentifierFieldConstructor & + RecordFieldConstructor & + StoredAsConstructor & // infinite loop goes away when you comment out this line + MaxMsToWaitBeforePublishingFieldConstructor & + TypeConstructor + + const buildPubSubRecordType = (soFar: SO_FAR) => Object.assign( + {}, + buildNameFieldConstructor(soFar), + buildIdentifierFieldConstructor(soFar), + buildRecordFieldConstructor(soFar), + buildStoredAsConstructor(soFar), + buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), + buildType(soFar) + ) as BuildPubSubRecordType; + const PubSubRecordType = buildPubSubRecordType({}); + +//// [conditionalTypeDoesntSpinForever.js] +// A *self-contained* demonstration of the problem follows... +// Test this by running `tsc --target es6` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. +export var PubSubRecordIsStoredInRedisAsA; +(function (PubSubRecordIsStoredInRedisAsA) { + PubSubRecordIsStoredInRedisAsA["redisHash"] = "redisHash"; + PubSubRecordIsStoredInRedisAsA["jsonEncodedRedisString"] = "jsonEncodedRedisString"; +})(PubSubRecordIsStoredInRedisAsA || (PubSubRecordIsStoredInRedisAsA = {})); +const buildNameFieldConstructor = (soFar) => ("name" in soFar ? {} : { + name: (instance = undefined) => buildPubSubRecordType(Object.assign({}, soFar, { name: instance })) +}); +const buildStoredAsConstructor = (soFar) => ("storedAs" in soFar ? {} : { + storedAsJsonEncodedRedisString: () => buildPubSubRecordType(Object.assign({}, soFar, { storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString })), + storedAsRedisHash: () => buildPubSubRecordType(Object.assign({}, soFar, { storedAs: PubSubRecordIsStoredInRedisAsA.redisHash })), +}); +const buildIdentifierFieldConstructor = (soFar) => ("identifier" in soFar || (!("record" in soFar)) ? {} : { + identifier: (instance = undefined) => buildPubSubRecordType(Object.assign({}, soFar, { identifier: instance })) +}); +const buildRecordFieldConstructor = (soFar) => ("record" in soFar ? {} : { + record: (instance = undefined) => buildPubSubRecordType(Object.assign({}, soFar, { record: instance })) +}); +const buildMaxMsToWaitBeforePublishingFieldConstructor = (soFar) => ("maxMsToWaitBeforePublishing" in soFar ? {} : { + maxMsToWaitBeforePublishing: (instance = 0) => buildPubSubRecordType(Object.assign({}, soFar, { maxMsToWaitBeforePublishing: instance })), + neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, { maxMsToWaitBeforePublishing: 0 })), +}); +const buildType = (soFar) => ("identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { + type: soFar, + fields: () => new Set(Object.keys(soFar)), + hasField: (fieldName) => fieldName in soFar +}); +const buildPubSubRecordType = (soFar) => Object.assign({}, buildNameFieldConstructor(soFar), buildIdentifierFieldConstructor(soFar), buildRecordFieldConstructor(soFar), buildStoredAsConstructor(soFar), buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), buildType(soFar)); +const PubSubRecordType = buildPubSubRecordType({}); diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols b/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols new file mode 100644 index 00000000000..d21db8eb90d --- /dev/null +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.symbols @@ -0,0 +1,489 @@ +=== tests/cases/compiler/conditionalTypeDoesntSpinForever.ts === +// A *self-contained* demonstration of the problem follows... +// Test this by running `tsc --target es6` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. + +export enum PubSubRecordIsStoredInRedisAsA { +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) + + redisHash = "redisHash", +>redisHash : Symbol(PubSubRecordIsStoredInRedisAsA.redisHash, Decl(conditionalTypeDoesntSpinForever.ts, 3, 44)) + + jsonEncodedRedisString = "jsonEncodedRedisString" +>jsonEncodedRedisString : Symbol(PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 4, 28)) + } + + export interface PubSubRecord> { +>PubSubRecord : Symbol(PubSubRecord, Decl(conditionalTypeDoesntSpinForever.ts, 6, 3)) +>NAME : Symbol(NAME, Decl(conditionalTypeDoesntSpinForever.ts, 8, 32)) +>RECORD : Symbol(RECORD, Decl(conditionalTypeDoesntSpinForever.ts, 8, 52)) +>IDENTIFIER : Symbol(IDENTIFIER, Decl(conditionalTypeDoesntSpinForever.ts, 8, 60)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>RECORD : Symbol(RECORD, Decl(conditionalTypeDoesntSpinForever.ts, 8, 52)) + + name: NAME; +>name : Symbol(PubSubRecord.name, Decl(conditionalTypeDoesntSpinForever.ts, 8, 98)) +>NAME : Symbol(NAME, Decl(conditionalTypeDoesntSpinForever.ts, 8, 32)) + + record: RECORD; +>record : Symbol(PubSubRecord.record, Decl(conditionalTypeDoesntSpinForever.ts, 9, 15)) +>RECORD : Symbol(RECORD, Decl(conditionalTypeDoesntSpinForever.ts, 8, 52)) + + identifier: IDENTIFIER; +>identifier : Symbol(PubSubRecord.identifier, Decl(conditionalTypeDoesntSpinForever.ts, 10, 19)) +>IDENTIFIER : Symbol(IDENTIFIER, Decl(conditionalTypeDoesntSpinForever.ts, 8, 60)) + + storedAs: PubSubRecordIsStoredInRedisAsA; +>storedAs : Symbol(PubSubRecord.storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 11, 27)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) + + maxMsToWaitBeforePublishing: number; +>maxMsToWaitBeforePublishing : Symbol(PubSubRecord.maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 12, 45)) + } + + type NameFieldConstructor = +>NameFieldConstructor : Symbol(NameFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 14, 3)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 16, 28)) + + SO_FAR extends {name: any} ? {} : { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 16, 28)) +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 17, 20)) + + name: (t?: TYPE) => BuildPubSubRecordType +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 17, 39)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 18, 13)) +>t : Symbol(t, Decl(conditionalTypeDoesntSpinForever.ts, 18, 19)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 18, 13)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 16, 28)) +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 18, 64)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 18, 13)) + } + + const buildNameFieldConstructor = (soFar: SO_FAR) => ( +>buildNameFieldConstructor : Symbol(buildNameFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 21, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 21, 37)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 21, 45)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 21, 37)) + + "name" in soFar ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 21, 45)) + + name: (instance: TYPE = undefined) => +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 22, 28)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 23, 13)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 23, 19)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 23, 13)) +>undefined : Symbol(undefined) + + buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 21, 45)) +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 24, 56)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 23, 19)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 23, 13)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 21, 37)) +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 24, 94)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 23, 13)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 21, 37)) +>name : Symbol(name, Decl(conditionalTypeDoesntSpinForever.ts, 24, 142)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 23, 13)) + } + ); + + type StoredAsConstructor = +>StoredAsConstructor : Symbol(StoredAsConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 26, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 28, 27)) + + SO_FAR extends {storedAs: any} ? {} : { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 28, 27)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 29, 20)) + + storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; +>storedAsJsonEncodedRedisString : Symbol(storedAsJsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 29, 43)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 28, 27)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 30, 76)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>jsonEncodedRedisString : Symbol(PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 4, 28)) + + storedRedisHash: () => BuildPubSubRecordType; +>storedRedisHash : Symbol(storedRedisHash, Decl(conditionalTypeDoesntSpinForever.ts, 30, 142)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 28, 27)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 31, 61)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>redisHash : Symbol(PubSubRecordIsStoredInRedisAsA.redisHash, Decl(conditionalTypeDoesntSpinForever.ts, 3, 44)) + } + + const buildStoredAsConstructor = (soFar: SO_FAR) => ( +>buildStoredAsConstructor : Symbol(buildStoredAsConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 34, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 34, 36)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 34, 44)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 34, 36)) + + "storedAs" in soFar ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 34, 44)) + + storedAsJsonEncodedRedisString: () => +>storedAsJsonEncodedRedisString : Symbol(storedAsJsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 35, 32)) + + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 34, 44)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 37, 56)) +>PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString : Symbol(PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 4, 28)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>jsonEncodedRedisString : Symbol(PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 4, 28)) + + BuildPubSubRecordType, +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 34, 36)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 38, 42)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>jsonEncodedRedisString : Symbol(PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString, Decl(conditionalTypeDoesntSpinForever.ts, 4, 28)) + + storedAsRedisHash: () => +>storedAsRedisHash : Symbol(storedAsRedisHash, Decl(conditionalTypeDoesntSpinForever.ts, 38, 108)) + + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 34, 44)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 40, 56)) +>PubSubRecordIsStoredInRedisAsA.redisHash : Symbol(PubSubRecordIsStoredInRedisAsA.redisHash, Decl(conditionalTypeDoesntSpinForever.ts, 3, 44)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>redisHash : Symbol(PubSubRecordIsStoredInRedisAsA.redisHash, Decl(conditionalTypeDoesntSpinForever.ts, 3, 44)) + + BuildPubSubRecordType, +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 34, 36)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 41, 42)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) +>redisHash : Symbol(PubSubRecordIsStoredInRedisAsA.redisHash, Decl(conditionalTypeDoesntSpinForever.ts, 3, 44)) + } + ); + + type IdentifierFieldConstructor = +>IdentifierFieldConstructor : Symbol(IdentifierFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 43, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 45, 34)) + + SO_FAR extends {identifier: any} ? {} : +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 45, 34)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 46, 20)) + + SO_FAR extends {record: any} ? { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 45, 34)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 47, 20)) + + identifier: >(t?: TYPE) => BuildPubSubRecordType +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 47, 36)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 48, 19)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 45, 34)) +>t : Symbol(t, Decl(conditionalTypeDoesntSpinForever.ts, 48, 59)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 48, 19)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 45, 34)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 48, 104)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 48, 19)) + + } : {} + + const buildIdentifierFieldConstructor = (soFar: SO_FAR) => ( +>buildIdentifierFieldConstructor : Symbol(buildIdentifierFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 51, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 51, 43)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 51, 51)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 51, 43)) + + "identifier" in soFar || (!("record" in soFar)) ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 51, 51)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 51, 51)) + + identifier: (instance: TYPE = undefined) => +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 52, 60)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 53, 19)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 53, 25)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 53, 19)) +>undefined : Symbol(undefined) + + buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 51, 51)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 54, 56)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 53, 25)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 53, 19)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 51, 43)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 54, 100)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 53, 19)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 51, 43)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 54, 154)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 53, 19)) + } + ); + + type RecordFieldConstructor = +>RecordFieldConstructor : Symbol(RecordFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 56, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 58, 30)) + + SO_FAR extends {record: any} ? {} : { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 58, 30)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 59, 20)) + + record: (t?: TYPE) => BuildPubSubRecordType +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 59, 41)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 60, 15)) +>t : Symbol(t, Decl(conditionalTypeDoesntSpinForever.ts, 60, 21)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 60, 15)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 58, 30)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 60, 66)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 60, 15)) + } + + const buildRecordFieldConstructor = (soFar: SO_FAR) => ( +>buildRecordFieldConstructor : Symbol(buildRecordFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 63, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 63, 39)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 63, 47)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 63, 39)) + + "record" in soFar ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 63, 47)) + + record: (instance: TYPE = undefined) => +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 64, 30)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 65, 15)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 65, 21)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 65, 15)) +>undefined : Symbol(undefined) + + buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 63, 47)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 66, 56)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 65, 21)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 65, 15)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 63, 39)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 66, 96)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 65, 15)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 63, 39)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 66, 146)) +>TYPE : Symbol(TYPE, Decl(conditionalTypeDoesntSpinForever.ts, 65, 15)) + } + ); + + type MaxMsToWaitBeforePublishingFieldConstructor = +>MaxMsToWaitBeforePublishingFieldConstructor : Symbol(MaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 68, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 70, 51)) + + SO_FAR extends {maxMsToWaitBeforePublishing: any} ? {} : { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 70, 51)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 71, 20)) + + maxMsToWaitBeforePublishing: (t: number) => BuildPubSubRecordType, +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 71, 62)) +>t : Symbol(t, Decl(conditionalTypeDoesntSpinForever.ts, 72, 36)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 70, 51)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 72, 82)) + + neverDelayPublishing: () => BuildPubSubRecordType, +>neverDelayPublishing : Symbol(neverDelayPublishing, Decl(conditionalTypeDoesntSpinForever.ts, 72, 120)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 70, 51)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 73, 66)) + } + + const buildMaxMsToWaitBeforePublishingFieldConstructor = (soFar: SO_FAR): MaxMsToWaitBeforePublishingFieldConstructor => ( +>buildMaxMsToWaitBeforePublishingFieldConstructor : Symbol(buildMaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 76, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 76, 68)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) +>MaxMsToWaitBeforePublishingFieldConstructor : Symbol(MaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 68, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) + + "maxMsToWaitBeforePublishing" in soFar ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 76, 68)) + + maxMsToWaitBeforePublishing: (instance: number = 0) => +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 77, 51)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 78, 36)) + + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 76, 68)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 79, 56)) +>instance : Symbol(instance, Decl(conditionalTypeDoesntSpinForever.ts, 78, 36)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 79, 132)) + + neverDelayPublishing: () => +>neverDelayPublishing : Symbol(neverDelayPublishing, Decl(conditionalTypeDoesntSpinForever.ts, 79, 170)) + + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 76, 68)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 81, 56)) +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 81, 125)) + } + ) as MaxMsToWaitBeforePublishingFieldConstructor; +>MaxMsToWaitBeforePublishingFieldConstructor : Symbol(MaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 68, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 76, 60)) + + type TypeConstructor = +>TypeConstructor : Symbol(TypeConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 83, 59)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 85, 23)) + + SO_FAR extends {identifier: any, record: any, maxMsToWaitBeforePublishing: number, storedAs: PubSubRecordIsStoredInRedisAsA} ? { +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 85, 23)) +>identifier : Symbol(identifier, Decl(conditionalTypeDoesntSpinForever.ts, 86, 20)) +>record : Symbol(record, Decl(conditionalTypeDoesntSpinForever.ts, 86, 36)) +>maxMsToWaitBeforePublishing : Symbol(maxMsToWaitBeforePublishing, Decl(conditionalTypeDoesntSpinForever.ts, 86, 49)) +>storedAs : Symbol(storedAs, Decl(conditionalTypeDoesntSpinForever.ts, 86, 86)) +>PubSubRecordIsStoredInRedisAsA : Symbol(PubSubRecordIsStoredInRedisAsA, Decl(conditionalTypeDoesntSpinForever.ts, 0, 0)) + + type: SO_FAR, +>type : Symbol(type, Decl(conditionalTypeDoesntSpinForever.ts, 86, 132)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 85, 23)) + + fields: Set, +>fields : Symbol(fields, Decl(conditionalTypeDoesntSpinForever.ts, 87, 19)) +>Set : Symbol(Set, Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 85, 23)) + + hasField: (fieldName: string | number | symbol) => fieldName is keyof SO_FAR +>hasField : Symbol(hasField, Decl(conditionalTypeDoesntSpinForever.ts, 88, 32)) +>fieldName : Symbol(fieldName, Decl(conditionalTypeDoesntSpinForever.ts, 89, 17)) +>fieldName : Symbol(fieldName, Decl(conditionalTypeDoesntSpinForever.ts, 89, 17)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 85, 23)) + + } : {} + + const buildType = (soFar: SO_FAR) => ( +>buildType : Symbol(buildType, Decl(conditionalTypeDoesntSpinForever.ts, 92, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 92, 21)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 92, 21)) + + "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) + + type: soFar, +>type : Symbol(type, Decl(conditionalTypeDoesntSpinForever.ts, 93, 142)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) + + fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), +>fields : Symbol(fields, Decl(conditionalTypeDoesntSpinForever.ts, 94, 18)) +>Set : Symbol(Set, Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.collection.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>Object.keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>keys : Symbol(ObjectConstructor.keys, Decl(lib.es5.d.ts, --, --)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 92, 21)) + + hasField: (fieldName: string | number | symbol) => fieldName in soFar +>hasField : Symbol(hasField, Decl(conditionalTypeDoesntSpinForever.ts, 95, 68)) +>fieldName : Symbol(fieldName, Decl(conditionalTypeDoesntSpinForever.ts, 96, 17)) +>fieldName : Symbol(fieldName, Decl(conditionalTypeDoesntSpinForever.ts, 96, 17)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 92, 29)) + } + ); + + type BuildPubSubRecordType = +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + NameFieldConstructor & +>NameFieldConstructor : Symbol(NameFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 14, 3)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + IdentifierFieldConstructor & +>IdentifierFieldConstructor : Symbol(IdentifierFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 43, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + RecordFieldConstructor & +>RecordFieldConstructor : Symbol(RecordFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 56, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + StoredAsConstructor & // infinite loop goes away when you comment out this line +>StoredAsConstructor : Symbol(StoredAsConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 26, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + MaxMsToWaitBeforePublishingFieldConstructor & +>MaxMsToWaitBeforePublishingFieldConstructor : Symbol(MaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 68, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + TypeConstructor +>TypeConstructor : Symbol(TypeConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 83, 59)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 100, 29)) + + const buildPubSubRecordType = (soFar: SO_FAR) => Object.assign( +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 108, 33)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 108, 33)) +>Object.assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>assign : Symbol(ObjectConstructor.assign, Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) + + {}, + buildNameFieldConstructor(soFar), +>buildNameFieldConstructor : Symbol(buildNameFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 21, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + buildIdentifierFieldConstructor(soFar), +>buildIdentifierFieldConstructor : Symbol(buildIdentifierFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 51, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + buildRecordFieldConstructor(soFar), +>buildRecordFieldConstructor : Symbol(buildRecordFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 63, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + buildStoredAsConstructor(soFar), +>buildStoredAsConstructor : Symbol(buildStoredAsConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 34, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), +>buildMaxMsToWaitBeforePublishingFieldConstructor : Symbol(buildMaxMsToWaitBeforePublishingFieldConstructor, Decl(conditionalTypeDoesntSpinForever.ts, 76, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + buildType(soFar) +>buildType : Symbol(buildType, Decl(conditionalTypeDoesntSpinForever.ts, 92, 7)) +>soFar : Symbol(soFar, Decl(conditionalTypeDoesntSpinForever.ts, 108, 41)) + + ) as BuildPubSubRecordType; +>BuildPubSubRecordType : Symbol(BuildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 98, 4)) +>SO_FAR : Symbol(SO_FAR, Decl(conditionalTypeDoesntSpinForever.ts, 108, 33)) + + const PubSubRecordType = buildPubSubRecordType({}); +>PubSubRecordType : Symbol(PubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 117, 7)) +>buildPubSubRecordType : Symbol(buildPubSubRecordType, Decl(conditionalTypeDoesntSpinForever.ts, 108, 7)) + diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.types b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types new file mode 100644 index 00000000000..d4fe4bf4826 --- /dev/null +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types @@ -0,0 +1,487 @@ +=== tests/cases/compiler/conditionalTypeDoesntSpinForever.ts === +// A *self-contained* demonstration of the problem follows... +// Test this by running `tsc --target es6` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. + +export enum PubSubRecordIsStoredInRedisAsA { +>PubSubRecordIsStoredInRedisAsA : PubSubRecordIsStoredInRedisAsA + + redisHash = "redisHash", +>redisHash : PubSubRecordIsStoredInRedisAsA.redisHash +>"redisHash" : "redisHash" + + jsonEncodedRedisString = "jsonEncodedRedisString" +>jsonEncodedRedisString : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString +>"jsonEncodedRedisString" : "jsonEncodedRedisString" + } + + export interface PubSubRecord> { + name: NAME; +>name : NAME + + record: RECORD; +>record : RECORD + + identifier: IDENTIFIER; +>identifier : IDENTIFIER + + storedAs: PubSubRecordIsStoredInRedisAsA; +>storedAs : PubSubRecordIsStoredInRedisAsA + + maxMsToWaitBeforePublishing: number; +>maxMsToWaitBeforePublishing : number + } + + type NameFieldConstructor = +>NameFieldConstructor : NameFieldConstructor + + SO_FAR extends {name: any} ? {} : { +>name : any + + name: (t?: TYPE) => BuildPubSubRecordType +>name : (t?: TYPE) => BuildPubSubRecordType +>t : TYPE +>name : TYPE + } + + const buildNameFieldConstructor = (soFar: SO_FAR) => ( +>buildNameFieldConstructor : (soFar: SO_FAR) => { name?: undefined; } | { name: (instance?: TYPE) => BuildPubSubRecordType; } +>(soFar: SO_FAR) => ( "name" in soFar ? {} : { name: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType } ) : (soFar: SO_FAR) => { name?: undefined; } | { name: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR +>( "name" in soFar ? {} : { name: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType } ) : {} | { name: (instance?: TYPE) => BuildPubSubRecordType; } + + "name" in soFar ? {} : { +>"name" in soFar ? {} : { name: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType } : {} | { name: (instance?: TYPE) => BuildPubSubRecordType; } +>"name" in soFar : boolean +>"name" : "name" +>soFar : SO_FAR +>{} : {} +>{ name: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType } : { name: (instance?: TYPE) => BuildPubSubRecordType; } + + name: (instance: TYPE = undefined) => +>name : (instance?: TYPE) => BuildPubSubRecordType +>(instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType : (instance?: TYPE) => BuildPubSubRecordType +>instance : TYPE +>undefined : undefined + + buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE} : SO_FAR & { name: TYPE; } +>Object.assign({}, soFar, {name: instance as TYPE}) : SO_FAR & { name: TYPE; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{name: instance as TYPE} : { name: TYPE; } +>name : TYPE +>instance as TYPE : TYPE +>instance : TYPE +>name : TYPE +>name : TYPE + } + ); + + type StoredAsConstructor = +>StoredAsConstructor : StoredAsConstructor + + SO_FAR extends {storedAs: any} ? {} : { +>storedAs : any + + storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; +>storedAsJsonEncodedRedisString : () => BuildPubSubRecordType +>storedAs : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString +>PubSubRecordIsStoredInRedisAsA : any + + storedRedisHash: () => BuildPubSubRecordType; +>storedRedisHash : () => BuildPubSubRecordType +>storedAs : PubSubRecordIsStoredInRedisAsA.redisHash +>PubSubRecordIsStoredInRedisAsA : any + } + + const buildStoredAsConstructor = (soFar: SO_FAR) => ( +>buildStoredAsConstructor : (soFar: SO_FAR) => { storedAsJsonEncodedRedisString?: undefined; storedAsRedisHash?: undefined; } | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } +>(soFar: SO_FAR) => ( "storedAs" in soFar ? {} : { storedAsJsonEncodedRedisString: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType, storedAsRedisHash: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType, } ) : (soFar: SO_FAR) => { storedAsJsonEncodedRedisString?: undefined; storedAsRedisHash?: undefined; } | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } +>soFar : SO_FAR +>( "storedAs" in soFar ? {} : { storedAsJsonEncodedRedisString: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType, storedAsRedisHash: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType, } ) : {} | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } + + "storedAs" in soFar ? {} : { +>"storedAs" in soFar ? {} : { storedAsJsonEncodedRedisString: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType, storedAsRedisHash: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType, } : {} | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } +>"storedAs" in soFar : boolean +>"storedAs" : "storedAs" +>soFar : SO_FAR +>{} : {} +>{ storedAsJsonEncodedRedisString: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType, storedAsRedisHash: () => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType, } : { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } + + storedAsJsonEncodedRedisString: () => +>storedAsJsonEncodedRedisString : () => BuildPubSubRecordType +>() => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType : () => BuildPubSubRecordType + + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString} : { storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString; } +>storedAs : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString +>PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString +>PubSubRecordIsStoredInRedisAsA : typeof PubSubRecordIsStoredInRedisAsA +>jsonEncodedRedisString : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString + + BuildPubSubRecordType, +>storedAs : PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString +>PubSubRecordIsStoredInRedisAsA : any + + storedAsRedisHash: () => +>storedAsRedisHash : () => BuildPubSubRecordType +>() => buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType : () => BuildPubSubRecordType + + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{storedAs: PubSubRecordIsStoredInRedisAsA.redisHash} : { storedAs: PubSubRecordIsStoredInRedisAsA.redisHash; } +>storedAs : PubSubRecordIsStoredInRedisAsA.redisHash +>PubSubRecordIsStoredInRedisAsA.redisHash : PubSubRecordIsStoredInRedisAsA.redisHash +>PubSubRecordIsStoredInRedisAsA : typeof PubSubRecordIsStoredInRedisAsA +>redisHash : PubSubRecordIsStoredInRedisAsA.redisHash + + BuildPubSubRecordType, +>storedAs : PubSubRecordIsStoredInRedisAsA.redisHash +>PubSubRecordIsStoredInRedisAsA : any + } + ); + + type IdentifierFieldConstructor = +>IdentifierFieldConstructor : IdentifierFieldConstructor + + SO_FAR extends {identifier: any} ? {} : +>identifier : any + + SO_FAR extends {record: any} ? { +>record : any + + identifier: >(t?: TYPE) => BuildPubSubRecordType +>identifier : >(t?: TYPE) => BuildPubSubRecordType +>t : TYPE +>identifier : TYPE + + } : {} + + const buildIdentifierFieldConstructor = (soFar: SO_FAR) => ( +>buildIdentifierFieldConstructor : (soFar: SO_FAR) => { identifier?: undefined; } | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } +>(soFar: SO_FAR) => ( "identifier" in soFar || (!("record" in soFar)) ? {} : { identifier: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType } ) : (soFar: SO_FAR) => { identifier?: undefined; } | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR +>( "identifier" in soFar || (!("record" in soFar)) ? {} : { identifier: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType } ) : {} | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } + + "identifier" in soFar || (!("record" in soFar)) ? {} : { +>"identifier" in soFar || (!("record" in soFar)) ? {} : { identifier: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType } : {} | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } +>"identifier" in soFar || (!("record" in soFar)) : boolean +>"identifier" in soFar : boolean +>"identifier" : "identifier" +>soFar : SO_FAR +>(!("record" in soFar)) : boolean +>!("record" in soFar) : boolean +>("record" in soFar) : boolean +>"record" in soFar : boolean +>"record" : "record" +>soFar : SO_FAR +>{} : {} +>{ identifier: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType } : { identifier: (instance?: TYPE) => BuildPubSubRecordType; } + + identifier: (instance: TYPE = undefined) => +>identifier : (instance?: TYPE) => BuildPubSubRecordType +>(instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType : (instance?: TYPE) => BuildPubSubRecordType +>instance : TYPE +>undefined : undefined + + buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE} : SO_FAR & { identifier: TYPE; } +>Object.assign({}, soFar, {identifier: instance as TYPE}) : SO_FAR & { identifier: TYPE; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{identifier: instance as TYPE} : { identifier: TYPE; } +>identifier : TYPE +>instance as TYPE : TYPE +>instance : TYPE +>identifier : TYPE +>identifier : TYPE + } + ); + + type RecordFieldConstructor = +>RecordFieldConstructor : RecordFieldConstructor + + SO_FAR extends {record: any} ? {} : { +>record : any + + record: (t?: TYPE) => BuildPubSubRecordType +>record : (t?: TYPE) => BuildPubSubRecordType +>t : TYPE +>record : TYPE + } + + const buildRecordFieldConstructor = (soFar: SO_FAR) => ( +>buildRecordFieldConstructor : (soFar: SO_FAR) => { record?: undefined; } | { record: (instance?: TYPE) => BuildPubSubRecordType; } +>(soFar: SO_FAR) => ( "record" in soFar ? {} : { record: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType } ) : (soFar: SO_FAR) => { record?: undefined; } | { record: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR +>( "record" in soFar ? {} : { record: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType } ) : {} | { record: (instance?: TYPE) => BuildPubSubRecordType; } + + "record" in soFar ? {} : { +>"record" in soFar ? {} : { record: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType } : {} | { record: (instance?: TYPE) => BuildPubSubRecordType; } +>"record" in soFar : boolean +>"record" : "record" +>soFar : SO_FAR +>{} : {} +>{ record: (instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType } : { record: (instance?: TYPE) => BuildPubSubRecordType; } + + record: (instance: TYPE = undefined) => +>record : (instance?: TYPE) => BuildPubSubRecordType +>(instance: TYPE = undefined) => buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType : (instance?: TYPE) => BuildPubSubRecordType +>instance : TYPE +>undefined : undefined + + buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE} : SO_FAR & { record: TYPE; } +>Object.assign({}, soFar, {record: instance as TYPE}) : SO_FAR & { record: TYPE; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{record: instance as TYPE} : { record: TYPE; } +>record : TYPE +>instance as TYPE : TYPE +>instance : TYPE +>record : TYPE +>record : TYPE + } + ); + + type MaxMsToWaitBeforePublishingFieldConstructor = +>MaxMsToWaitBeforePublishingFieldConstructor : MaxMsToWaitBeforePublishingFieldConstructor + + SO_FAR extends {maxMsToWaitBeforePublishing: any} ? {} : { +>maxMsToWaitBeforePublishing : any + + maxMsToWaitBeforePublishing: (t: number) => BuildPubSubRecordType, +>maxMsToWaitBeforePublishing : (t: number) => BuildPubSubRecordType +>t : number +>maxMsToWaitBeforePublishing : number + + neverDelayPublishing: () => BuildPubSubRecordType, +>neverDelayPublishing : () => BuildPubSubRecordType +>maxMsToWaitBeforePublishing : 0 + } + + const buildMaxMsToWaitBeforePublishingFieldConstructor = (soFar: SO_FAR): MaxMsToWaitBeforePublishingFieldConstructor => ( +>buildMaxMsToWaitBeforePublishingFieldConstructor : (soFar: SO_FAR) => MaxMsToWaitBeforePublishingFieldConstructor +>(soFar: SO_FAR): MaxMsToWaitBeforePublishingFieldConstructor => ( "maxMsToWaitBeforePublishing" in soFar ? {} : { maxMsToWaitBeforePublishing: (instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, } ) as MaxMsToWaitBeforePublishingFieldConstructor : (soFar: SO_FAR) => MaxMsToWaitBeforePublishingFieldConstructor +>soFar : SO_FAR +>( "maxMsToWaitBeforePublishing" in soFar ? {} : { maxMsToWaitBeforePublishing: (instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, } ) as MaxMsToWaitBeforePublishingFieldConstructor : MaxMsToWaitBeforePublishingFieldConstructor +>( "maxMsToWaitBeforePublishing" in soFar ? {} : { maxMsToWaitBeforePublishing: (instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, } ) : {} | { maxMsToWaitBeforePublishing: (instance?: number) => BuildPubSubRecordType; neverDelayPublishing: () => BuildPubSubRecordType; } + + "maxMsToWaitBeforePublishing" in soFar ? {} : { +>"maxMsToWaitBeforePublishing" in soFar ? {} : { maxMsToWaitBeforePublishing: (instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, } : {} | { maxMsToWaitBeforePublishing: (instance?: number) => BuildPubSubRecordType; neverDelayPublishing: () => BuildPubSubRecordType; } +>"maxMsToWaitBeforePublishing" in soFar : boolean +>"maxMsToWaitBeforePublishing" : "maxMsToWaitBeforePublishing" +>soFar : SO_FAR +>{} : {} +>{ maxMsToWaitBeforePublishing: (instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, neverDelayPublishing: () => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, } : { maxMsToWaitBeforePublishing: (instance?: number) => BuildPubSubRecordType; neverDelayPublishing: () => BuildPubSubRecordType; } + + maxMsToWaitBeforePublishing: (instance: number = 0) => +>maxMsToWaitBeforePublishing : (instance?: number) => BuildPubSubRecordType +>(instance: number = 0) => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType : (instance?: number) => BuildPubSubRecordType +>instance : number +>0 : 0 + + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, +>buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance}) : SO_FAR & { maxMsToWaitBeforePublishing: number; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{maxMsToWaitBeforePublishing: instance} : { maxMsToWaitBeforePublishing: number; } +>maxMsToWaitBeforePublishing : number +>instance : number +>maxMsToWaitBeforePublishing : number + + neverDelayPublishing: () => +>neverDelayPublishing : () => BuildPubSubRecordType +>() => buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType : () => BuildPubSubRecordType + + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, +>buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) : BuildPubSubRecordType +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0}) : SO_FAR & { maxMsToWaitBeforePublishing: number; } +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>{} : {} +>soFar : SO_FAR +>{maxMsToWaitBeforePublishing: 0} : { maxMsToWaitBeforePublishing: number; } +>maxMsToWaitBeforePublishing : number +>0 : 0 +>maxMsToWaitBeforePublishing : 0 + } + ) as MaxMsToWaitBeforePublishingFieldConstructor; + + type TypeConstructor = +>TypeConstructor : TypeConstructor + + SO_FAR extends {identifier: any, record: any, maxMsToWaitBeforePublishing: number, storedAs: PubSubRecordIsStoredInRedisAsA} ? { +>identifier : any +>record : any +>maxMsToWaitBeforePublishing : number +>storedAs : PubSubRecordIsStoredInRedisAsA + + type: SO_FAR, +>type : SO_FAR + + fields: Set, +>fields : Set + + hasField: (fieldName: string | number | symbol) => fieldName is keyof SO_FAR +>hasField : (fieldName: string | number | symbol) => fieldName is keyof SO_FAR +>fieldName : string | number | symbol + + } : {} + + const buildType = (soFar: SO_FAR) => ( +>buildType : (soFar: SO_FAR) => { type?: undefined; fields?: undefined; hasField?: undefined; } | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } +>(soFar: SO_FAR) => ( "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { type: soFar, fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), hasField: (fieldName: string | number | symbol) => fieldName in soFar } ) : (soFar: SO_FAR) => { type?: undefined; fields?: undefined; hasField?: undefined; } | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } +>soFar : SO_FAR +>( "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { type: soFar, fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), hasField: (fieldName: string | number | symbol) => fieldName in soFar } ) : {} | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } + + "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { +>"identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { type: soFar, fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), hasField: (fieldName: string | number | symbol) => fieldName in soFar } : {} | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } +>"identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar : boolean +>"identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar : boolean +>"identifier" in soFar && "object" in soFar : boolean +>"identifier" in soFar : boolean +>"identifier" : "identifier" +>soFar : SO_FAR +>"object" in soFar : boolean +>"object" : "object" +>soFar : SO_FAR +>"maxMsToWaitBeforePublishing" in soFar : boolean +>"maxMsToWaitBeforePublishing" : "maxMsToWaitBeforePublishing" +>soFar : SO_FAR +>"PubSubRecordIsStoredInRedisAsA" in soFar : boolean +>"PubSubRecordIsStoredInRedisAsA" : "PubSubRecordIsStoredInRedisAsA" +>soFar : SO_FAR +>{} : {} +>{ type: soFar, fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), hasField: (fieldName: string | number | symbol) => fieldName in soFar } : { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } + + type: soFar, +>type : SO_FAR +>soFar : SO_FAR + + fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), +>fields : () => Set +>() => new Set(Object.keys(soFar) as (keyof SO_FAR)[]) : () => Set +>new Set(Object.keys(soFar) as (keyof SO_FAR)[]) : Set +>Set : SetConstructor +>Object.keys(soFar) as (keyof SO_FAR)[] : (keyof SO_FAR)[] +>Object.keys(soFar) : string[] +>Object.keys : (o: {}) => string[] +>Object : ObjectConstructor +>keys : (o: {}) => string[] +>soFar : SO_FAR + + hasField: (fieldName: string | number | symbol) => fieldName in soFar +>hasField : (fieldName: string | number | symbol) => boolean +>(fieldName: string | number | symbol) => fieldName in soFar : (fieldName: string | number | symbol) => boolean +>fieldName : string | number | symbol +>fieldName in soFar : boolean +>fieldName : string | number | symbol +>soFar : SO_FAR + } + ); + + type BuildPubSubRecordType = +>BuildPubSubRecordType : BuildPubSubRecordType + + NameFieldConstructor & + IdentifierFieldConstructor & + RecordFieldConstructor & + StoredAsConstructor & // infinite loop goes away when you comment out this line + MaxMsToWaitBeforePublishingFieldConstructor & + TypeConstructor + + const buildPubSubRecordType = (soFar: SO_FAR) => Object.assign( +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>(soFar: SO_FAR) => Object.assign( {}, buildNameFieldConstructor(soFar), buildIdentifierFieldConstructor(soFar), buildRecordFieldConstructor(soFar), buildStoredAsConstructor(soFar), buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), buildType(soFar) ) as BuildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>soFar : SO_FAR +>Object.assign( {}, buildNameFieldConstructor(soFar), buildIdentifierFieldConstructor(soFar), buildRecordFieldConstructor(soFar), buildStoredAsConstructor(soFar), buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), buildType(soFar) ) as BuildPubSubRecordType : BuildPubSubRecordType +>Object.assign( {}, buildNameFieldConstructor(soFar), buildIdentifierFieldConstructor(soFar), buildRecordFieldConstructor(soFar), buildStoredAsConstructor(soFar), buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), buildType(soFar) ) : any +>Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } +>Object : ObjectConstructor +>assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } + + {}, +>{} : {} + + buildNameFieldConstructor(soFar), +>buildNameFieldConstructor(soFar) : { name?: undefined; } | { name: (instance?: TYPE) => BuildPubSubRecordType; } +>buildNameFieldConstructor : (soFar: SO_FAR) => { name?: undefined; } | { name: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR + + buildIdentifierFieldConstructor(soFar), +>buildIdentifierFieldConstructor(soFar) : { identifier?: undefined; } | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } +>buildIdentifierFieldConstructor : (soFar: SO_FAR) => { identifier?: undefined; } | { identifier: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR + + buildRecordFieldConstructor(soFar), +>buildRecordFieldConstructor(soFar) : { record?: undefined; } | { record: (instance?: TYPE) => BuildPubSubRecordType; } +>buildRecordFieldConstructor : (soFar: SO_FAR) => { record?: undefined; } | { record: (instance?: TYPE) => BuildPubSubRecordType; } +>soFar : SO_FAR + + buildStoredAsConstructor(soFar), +>buildStoredAsConstructor(soFar) : { storedAsJsonEncodedRedisString?: undefined; storedAsRedisHash?: undefined; } | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } +>buildStoredAsConstructor : (soFar: SO_FAR) => { storedAsJsonEncodedRedisString?: undefined; storedAsRedisHash?: undefined; } | { storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; storedAsRedisHash: () => BuildPubSubRecordType; } +>soFar : SO_FAR + + buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), +>buildMaxMsToWaitBeforePublishingFieldConstructor(soFar) : MaxMsToWaitBeforePublishingFieldConstructor +>buildMaxMsToWaitBeforePublishingFieldConstructor : (soFar: SO_FAR) => MaxMsToWaitBeforePublishingFieldConstructor +>soFar : SO_FAR + + buildType(soFar) +>buildType(soFar) : { type?: undefined; fields?: undefined; hasField?: undefined; } | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } +>buildType : (soFar: SO_FAR) => { type?: undefined; fields?: undefined; hasField?: undefined; } | { type: SO_FAR; fields: () => Set; hasField: (fieldName: string | number | symbol) => boolean; } +>soFar : SO_FAR + + ) as BuildPubSubRecordType; + const PubSubRecordType = buildPubSubRecordType({}); +>PubSubRecordType : BuildPubSubRecordType<{}> +>buildPubSubRecordType({}) : BuildPubSubRecordType<{}> +>buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType +>{} : {} + diff --git a/tests/baselines/reference/conditionalTypes1.errors.txt b/tests/baselines/reference/conditionalTypes1.errors.txt index 7ba3a2aa934..4018e0866d6 100644 --- a/tests/baselines/reference/conditionalTypes1.errors.txt +++ b/tests/baselines/reference/conditionalTypes1.errors.txt @@ -17,12 +17,8 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(103,5): error TS2 tests/cases/conformance/types/conditional/conditionalTypes1.ts(104,5): error TS2322: Type 'Pick' is not assignable to type 'T'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(106,5): error TS2322: Type 'Pick' is not assignable to type 'Pick'. Type 'T[keyof T] extends Function ? keyof T : never' is not assignable to type 'T[keyof T] extends Function ? never : keyof T'. - Type 'keyof T' is not assignable to type 'never'. - Type 'string | number | symbol' is not assignable to type 'never'. - Type 'string' is not assignable to type 'never'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(108,5): error TS2322: Type 'Pick' is not assignable to type 'Pick'. Type 'T[keyof T] extends Function ? never : keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. - Type 'keyof T' is not assignable to type 'never'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(114,5): error TS2322: Type 'keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. Type 'string | number | symbol' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. Type 'string' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. @@ -187,15 +183,11 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(288,43): error TS ~ !!! error TS2322: Type 'Pick' is not assignable to type 'Pick'. !!! error TS2322: Type 'T[keyof T] extends Function ? keyof T : never' is not assignable to type 'T[keyof T] extends Function ? never : keyof T'. -!!! error TS2322: Type 'keyof T' is not assignable to type 'never'. -!!! error TS2322: Type 'string | number | symbol' is not assignable to type 'never'. -!!! error TS2322: Type 'string' is not assignable to type 'never'. z = x; z = y; // Error ~ !!! error TS2322: Type 'Pick' is not assignable to type 'Pick'. !!! error TS2322: Type 'T[keyof T] extends Function ? never : keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. -!!! error TS2322: Type 'keyof T' is not assignable to type 'never'. } function f8(x: keyof T, y: FunctionPropertyNames, z: NonFunctionPropertyNames) { diff --git a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt index d8e36e43060..965bbee0ea1 100644 --- a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt +++ b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt @@ -58,8 +58,6 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(67,1): error TS2322: Type 'Fun Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(74,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. Type 'Func' is not assignable to type 'Func'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(75,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. Types of parameters 'x' and 'x' are incompatible. Type 'Object' is not assignable to type 'string'. @@ -261,8 +259,6 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. !!! error TS2322: Type 'Func' is not assignable to type 'Func'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. i1 = i3; // Error ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. diff --git a/tests/cases/compiler/conditionalTypeDoesntSpinForever.ts b/tests/cases/compiler/conditionalTypeDoesntSpinForever.ts new file mode 100644 index 00000000000..9ffbd57ffa1 --- /dev/null +++ b/tests/cases/compiler/conditionalTypeDoesntSpinForever.ts @@ -0,0 +1,119 @@ +// @target: es6 +// A *self-contained* demonstration of the problem follows... +// Test this by running `tsc --target es6` on the command-line, rather than through another build tool such as Gulp, Webpack, etc. + +export enum PubSubRecordIsStoredInRedisAsA { + redisHash = "redisHash", + jsonEncodedRedisString = "jsonEncodedRedisString" + } + + export interface PubSubRecord> { + name: NAME; + record: RECORD; + identifier: IDENTIFIER; + storedAs: PubSubRecordIsStoredInRedisAsA; + maxMsToWaitBeforePublishing: number; + } + + type NameFieldConstructor = + SO_FAR extends {name: any} ? {} : { + name: (t?: TYPE) => BuildPubSubRecordType + } + + const buildNameFieldConstructor = (soFar: SO_FAR) => ( + "name" in soFar ? {} : { + name: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {name: instance as TYPE}) as SO_FAR & {name: TYPE}) as BuildPubSubRecordType + } + ); + + type StoredAsConstructor = + SO_FAR extends {storedAs: any} ? {} : { + storedAsJsonEncodedRedisString: () => BuildPubSubRecordType; + storedRedisHash: () => BuildPubSubRecordType; + } + + const buildStoredAsConstructor = (soFar: SO_FAR) => ( + "storedAs" in soFar ? {} : { + storedAsJsonEncodedRedisString: () => + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as + BuildPubSubRecordType, + storedAsRedisHash: () => + buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as + BuildPubSubRecordType, + } + ); + + type IdentifierFieldConstructor = + SO_FAR extends {identifier: any} ? {} : + SO_FAR extends {record: any} ? { + identifier: >(t?: TYPE) => BuildPubSubRecordType + } : {} + + const buildIdentifierFieldConstructor = (soFar: SO_FAR) => ( + "identifier" in soFar || (!("record" in soFar)) ? {} : { + identifier: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {identifier: instance as TYPE}) as SO_FAR & {identifier: TYPE}) as BuildPubSubRecordType + } + ); + + type RecordFieldConstructor = + SO_FAR extends {record: any} ? {} : { + record: (t?: TYPE) => BuildPubSubRecordType + } + + const buildRecordFieldConstructor = (soFar: SO_FAR) => ( + "record" in soFar ? {} : { + record: (instance: TYPE = undefined) => + buildPubSubRecordType(Object.assign({}, soFar, {record: instance as TYPE}) as SO_FAR & {record: TYPE}) as BuildPubSubRecordType + } + ); + + type MaxMsToWaitBeforePublishingFieldConstructor = + SO_FAR extends {maxMsToWaitBeforePublishing: any} ? {} : { + maxMsToWaitBeforePublishing: (t: number) => BuildPubSubRecordType, + neverDelayPublishing: () => BuildPubSubRecordType, + } + + const buildMaxMsToWaitBeforePublishingFieldConstructor = (soFar: SO_FAR): MaxMsToWaitBeforePublishingFieldConstructor => ( + "maxMsToWaitBeforePublishing" in soFar ? {} : { + maxMsToWaitBeforePublishing: (instance: number = 0) => + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: instance})) as BuildPubSubRecordType, + neverDelayPublishing: () => + buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, + } + ) as MaxMsToWaitBeforePublishingFieldConstructor; + + type TypeConstructor = + SO_FAR extends {identifier: any, record: any, maxMsToWaitBeforePublishing: number, storedAs: PubSubRecordIsStoredInRedisAsA} ? { + type: SO_FAR, + fields: Set, + hasField: (fieldName: string | number | symbol) => fieldName is keyof SO_FAR + } : {} + + const buildType = (soFar: SO_FAR) => ( + "identifier" in soFar && "object" in soFar && "maxMsToWaitBeforePublishing" in soFar && "PubSubRecordIsStoredInRedisAsA" in soFar ? {} : { + type: soFar, + fields: () => new Set(Object.keys(soFar) as (keyof SO_FAR)[]), + hasField: (fieldName: string | number | symbol) => fieldName in soFar + } + ); + + type BuildPubSubRecordType = + NameFieldConstructor & + IdentifierFieldConstructor & + RecordFieldConstructor & + StoredAsConstructor & // infinite loop goes away when you comment out this line + MaxMsToWaitBeforePublishingFieldConstructor & + TypeConstructor + + const buildPubSubRecordType = (soFar: SO_FAR) => Object.assign( + {}, + buildNameFieldConstructor(soFar), + buildIdentifierFieldConstructor(soFar), + buildRecordFieldConstructor(soFar), + buildStoredAsConstructor(soFar), + buildMaxMsToWaitBeforePublishingFieldConstructor(soFar), + buildType(soFar) + ) as BuildPubSubRecordType; + const PubSubRecordType = buildPubSubRecordType({}); \ No newline at end of file From a6952887e9215ab1601aabfc1eca29322f84273a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 29 Oct 2018 09:38:10 -0700 Subject: [PATCH 135/262] Use same condition in isReferencedAliasDeclaration as isAliasResolvedToValue (#28171) --- src/compiler/checker.ts | 3 +- ...ortImportCanSubstituteConstEnumForValue.js | 128 +++++++++++++++++ ...portCanSubstituteConstEnumForValue.symbols | 130 ++++++++++++++++++ ...ImportCanSubstituteConstEnumForValue.types | 129 +++++++++++++++++ ...ortImportCanSubstituteConstEnumForValue.ts | 60 ++++++++ 5 files changed, 449 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.js create mode 100644 tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.symbols create mode 100644 tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.types create mode 100644 tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e5a8d8ee460..e209041f9fb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28341,7 +28341,8 @@ namespace ts { return true; } const target = getSymbolLinks(symbol!).target; // TODO: GH#18217 - if (target && getModifierFlags(node) & ModifierFlags.Export && target.flags & SymbolFlags.Value) { + if (target && getModifierFlags(node) & ModifierFlags.Export && + target.flags & SymbolFlags.Value && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; } diff --git a/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.js b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.js new file mode 100644 index 00000000000..961d3ccd500 --- /dev/null +++ b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.js @@ -0,0 +1,128 @@ +//// [exportImportCanSubstituteConstEnumForValue.ts] +module MsPortalFx.ViewModels.Dialogs { + + export const enum DialogResult { + Abort, + Cancel, + Ignore, + No, + Ok, + Retry, + Yes, + } + + export interface DialogResultCallback { + (result: MsPortalFx.ViewModels.Dialogs.DialogResult): void; + } + + export function someExportedFunction() { + } + + export const enum MessageBoxButtons { + AbortRetryIgnore, + OK, + OKCancel, + RetryCancel, + YesNo, + YesNoCancel, + } +} + + +module MsPortalFx.ViewModels { + + /** + * For some reason javascript code is emitted for this re-exported const enum. + */ + export import ReExportedEnum = Dialogs.DialogResult; + + /** + * Not exported to show difference. No javascript is emmitted (as expected) + */ + import DialogButtons = Dialogs.MessageBoxButtons; + + /** + * Re-exporting a function type to show difference. No javascript is emmitted (as expected) + */ + export import Callback = Dialogs.DialogResultCallback; + + export class SomeUsagesOfTheseConsts { + constructor() { + // these do get replaced by the const value + const value1 = ReExportedEnum.Cancel; + console.log(value1); + const value2 = DialogButtons.OKCancel; + console.log(value2); + } + } +} + + +//// [exportImportCanSubstituteConstEnumForValue.js] +var MsPortalFx; +(function (MsPortalFx) { + var ViewModels; + (function (ViewModels) { + var Dialogs; + (function (Dialogs) { + function someExportedFunction() { + } + Dialogs.someExportedFunction = someExportedFunction; + })(Dialogs = ViewModels.Dialogs || (ViewModels.Dialogs = {})); + })(ViewModels = MsPortalFx.ViewModels || (MsPortalFx.ViewModels = {})); +})(MsPortalFx || (MsPortalFx = {})); +(function (MsPortalFx) { + var ViewModels; + (function (ViewModels) { + var SomeUsagesOfTheseConsts = /** @class */ (function () { + function SomeUsagesOfTheseConsts() { + // these do get replaced by the const value + var value1 = 1 /* Cancel */; + console.log(value1); + var value2 = 2 /* OKCancel */; + console.log(value2); + } + return SomeUsagesOfTheseConsts; + }()); + ViewModels.SomeUsagesOfTheseConsts = SomeUsagesOfTheseConsts; + })(ViewModels = MsPortalFx.ViewModels || (MsPortalFx.ViewModels = {})); +})(MsPortalFx || (MsPortalFx = {})); + + +//// [exportImportCanSubstituteConstEnumForValue.d.ts] +declare module MsPortalFx.ViewModels.Dialogs { + const enum DialogResult { + Abort = 0, + Cancel = 1, + Ignore = 2, + No = 3, + Ok = 4, + Retry = 5, + Yes = 6 + } + interface DialogResultCallback { + (result: MsPortalFx.ViewModels.Dialogs.DialogResult): void; + } + function someExportedFunction(): void; + const enum MessageBoxButtons { + AbortRetryIgnore = 0, + OK = 1, + OKCancel = 2, + RetryCancel = 3, + YesNo = 4, + YesNoCancel = 5 + } +} +declare module MsPortalFx.ViewModels { + /** + * For some reason javascript code is emitted for this re-exported const enum. + */ + export import ReExportedEnum = Dialogs.DialogResult; + /** + * Re-exporting a function type to show difference. No javascript is emmitted (as expected) + */ + export import Callback = Dialogs.DialogResultCallback; + class SomeUsagesOfTheseConsts { + constructor(); + } +} diff --git a/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.symbols b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.symbols new file mode 100644 index 00000000000..ee21ab5b3b1 --- /dev/null +++ b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.symbols @@ -0,0 +1,130 @@ +=== tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts === +module MsPortalFx.ViewModels.Dialogs { +>MsPortalFx : Symbol(MsPortalFx, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 0), Decl(exportImportCanSubstituteConstEnumForValue.ts, 27, 1)) +>ViewModels : Symbol(ViewModels, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 18), Decl(exportImportCanSubstituteConstEnumForValue.ts, 30, 18)) +>Dialogs : Symbol(Dialogs, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 29)) + + export const enum DialogResult { +>DialogResult : Symbol(DialogResult, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 38)) + + Abort, +>Abort : Symbol(ReExportedEnum.Abort, Decl(exportImportCanSubstituteConstEnumForValue.ts, 2, 36)) + + Cancel, +>Cancel : Symbol(ReExportedEnum.Cancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 3, 14)) + + Ignore, +>Ignore : Symbol(ReExportedEnum.Ignore, Decl(exportImportCanSubstituteConstEnumForValue.ts, 4, 15)) + + No, +>No : Symbol(ReExportedEnum.No, Decl(exportImportCanSubstituteConstEnumForValue.ts, 5, 15)) + + Ok, +>Ok : Symbol(ReExportedEnum.Ok, Decl(exportImportCanSubstituteConstEnumForValue.ts, 6, 11)) + + Retry, +>Retry : Symbol(ReExportedEnum.Retry, Decl(exportImportCanSubstituteConstEnumForValue.ts, 7, 11)) + + Yes, +>Yes : Symbol(ReExportedEnum.Yes, Decl(exportImportCanSubstituteConstEnumForValue.ts, 8, 14)) + } + + export interface DialogResultCallback { +>DialogResultCallback : Symbol(DialogResultCallback, Decl(exportImportCanSubstituteConstEnumForValue.ts, 10, 5)) + + (result: MsPortalFx.ViewModels.Dialogs.DialogResult): void; +>result : Symbol(result, Decl(exportImportCanSubstituteConstEnumForValue.ts, 13, 9)) +>MsPortalFx : Symbol(MsPortalFx, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 0), Decl(exportImportCanSubstituteConstEnumForValue.ts, 27, 1)) +>ViewModels : Symbol(ViewModels, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 18), Decl(exportImportCanSubstituteConstEnumForValue.ts, 30, 18)) +>Dialogs : Symbol(Dialogs, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 29)) +>DialogResult : Symbol(DialogResult, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 38)) + } + + export function someExportedFunction() { +>someExportedFunction : Symbol(someExportedFunction, Decl(exportImportCanSubstituteConstEnumForValue.ts, 14, 5)) + } + + export const enum MessageBoxButtons { +>MessageBoxButtons : Symbol(MessageBoxButtons, Decl(exportImportCanSubstituteConstEnumForValue.ts, 17, 5)) + + AbortRetryIgnore, +>AbortRetryIgnore : Symbol(MessageBoxButtons.AbortRetryIgnore, Decl(exportImportCanSubstituteConstEnumForValue.ts, 19, 41)) + + OK, +>OK : Symbol(MessageBoxButtons.OK, Decl(exportImportCanSubstituteConstEnumForValue.ts, 20, 25)) + + OKCancel, +>OKCancel : Symbol(MessageBoxButtons.OKCancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 21, 11)) + + RetryCancel, +>RetryCancel : Symbol(MessageBoxButtons.RetryCancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 22, 17)) + + YesNo, +>YesNo : Symbol(MessageBoxButtons.YesNo, Decl(exportImportCanSubstituteConstEnumForValue.ts, 23, 20)) + + YesNoCancel, +>YesNoCancel : Symbol(MessageBoxButtons.YesNoCancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 24, 14)) + } +} + + +module MsPortalFx.ViewModels { +>MsPortalFx : Symbol(MsPortalFx, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 0), Decl(exportImportCanSubstituteConstEnumForValue.ts, 27, 1)) +>ViewModels : Symbol(ViewModels, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 18), Decl(exportImportCanSubstituteConstEnumForValue.ts, 30, 18)) + + /** + * For some reason javascript code is emitted for this re-exported const enum. + */ + export import ReExportedEnum = Dialogs.DialogResult; +>ReExportedEnum : Symbol(ReExportedEnum, Decl(exportImportCanSubstituteConstEnumForValue.ts, 30, 30)) +>Dialogs : Symbol(Dialogs, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 29)) +>DialogResult : Symbol(ReExportedEnum, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 38)) + + /** + * Not exported to show difference. No javascript is emmitted (as expected) + */ + import DialogButtons = Dialogs.MessageBoxButtons; +>DialogButtons : Symbol(DialogButtons, Decl(exportImportCanSubstituteConstEnumForValue.ts, 35, 56)) +>Dialogs : Symbol(Dialogs, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 29)) +>MessageBoxButtons : Symbol(DialogButtons, Decl(exportImportCanSubstituteConstEnumForValue.ts, 17, 5)) + + /** + * Re-exporting a function type to show difference. No javascript is emmitted (as expected) + */ + export import Callback = Dialogs.DialogResultCallback; +>Callback : Symbol(Callback, Decl(exportImportCanSubstituteConstEnumForValue.ts, 40, 53)) +>Dialogs : Symbol(Dialogs, Decl(exportImportCanSubstituteConstEnumForValue.ts, 0, 29)) +>DialogResultCallback : Symbol(Callback, Decl(exportImportCanSubstituteConstEnumForValue.ts, 10, 5)) + + export class SomeUsagesOfTheseConsts { +>SomeUsagesOfTheseConsts : Symbol(SomeUsagesOfTheseConsts, Decl(exportImportCanSubstituteConstEnumForValue.ts, 45, 58)) + + constructor() { + // these do get replaced by the const value + const value1 = ReExportedEnum.Cancel; +>value1 : Symbol(value1, Decl(exportImportCanSubstituteConstEnumForValue.ts, 50, 17)) +>ReExportedEnum.Cancel : Symbol(ReExportedEnum.Cancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 3, 14)) +>ReExportedEnum : Symbol(ReExportedEnum, Decl(exportImportCanSubstituteConstEnumForValue.ts, 30, 30)) +>Cancel : Symbol(ReExportedEnum.Cancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 3, 14)) + + console.log(value1); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>value1 : Symbol(value1, Decl(exportImportCanSubstituteConstEnumForValue.ts, 50, 17)) + + const value2 = DialogButtons.OKCancel; +>value2 : Symbol(value2, Decl(exportImportCanSubstituteConstEnumForValue.ts, 52, 17)) +>DialogButtons.OKCancel : Symbol(DialogButtons.OKCancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 21, 11)) +>DialogButtons : Symbol(DialogButtons, Decl(exportImportCanSubstituteConstEnumForValue.ts, 35, 56)) +>OKCancel : Symbol(DialogButtons.OKCancel, Decl(exportImportCanSubstituteConstEnumForValue.ts, 21, 11)) + + console.log(value2); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>value2 : Symbol(value2, Decl(exportImportCanSubstituteConstEnumForValue.ts, 52, 17)) + } + } +} + diff --git a/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.types b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.types new file mode 100644 index 00000000000..b35ca9384f7 --- /dev/null +++ b/tests/baselines/reference/exportImportCanSubstituteConstEnumForValue.types @@ -0,0 +1,129 @@ +=== tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts === +module MsPortalFx.ViewModels.Dialogs { +>MsPortalFx : typeof MsPortalFx +>ViewModels : typeof ViewModels +>Dialogs : typeof Dialogs + + export const enum DialogResult { +>DialogResult : DialogResult + + Abort, +>Abort : DialogResult.Abort + + Cancel, +>Cancel : DialogResult.Cancel + + Ignore, +>Ignore : DialogResult.Ignore + + No, +>No : DialogResult.No + + Ok, +>Ok : DialogResult.Ok + + Retry, +>Retry : DialogResult.Retry + + Yes, +>Yes : DialogResult.Yes + } + + export interface DialogResultCallback { + (result: MsPortalFx.ViewModels.Dialogs.DialogResult): void; +>result : DialogResult +>MsPortalFx : any +>ViewModels : any +>Dialogs : any + } + + export function someExportedFunction() { +>someExportedFunction : () => void + } + + export const enum MessageBoxButtons { +>MessageBoxButtons : MessageBoxButtons + + AbortRetryIgnore, +>AbortRetryIgnore : MessageBoxButtons.AbortRetryIgnore + + OK, +>OK : MessageBoxButtons.OK + + OKCancel, +>OKCancel : MessageBoxButtons.OKCancel + + RetryCancel, +>RetryCancel : MessageBoxButtons.RetryCancel + + YesNo, +>YesNo : MessageBoxButtons.YesNo + + YesNoCancel, +>YesNoCancel : MessageBoxButtons.YesNoCancel + } +} + + +module MsPortalFx.ViewModels { +>MsPortalFx : typeof MsPortalFx +>ViewModels : typeof ViewModels + + /** + * For some reason javascript code is emitted for this re-exported const enum. + */ + export import ReExportedEnum = Dialogs.DialogResult; +>ReExportedEnum : typeof ReExportedEnum +>Dialogs : typeof Dialogs +>DialogResult : ReExportedEnum + + /** + * Not exported to show difference. No javascript is emmitted (as expected) + */ + import DialogButtons = Dialogs.MessageBoxButtons; +>DialogButtons : typeof DialogButtons +>Dialogs : typeof Dialogs +>MessageBoxButtons : DialogButtons + + /** + * Re-exporting a function type to show difference. No javascript is emmitted (as expected) + */ + export import Callback = Dialogs.DialogResultCallback; +>Callback : any +>Dialogs : typeof Dialogs +>DialogResultCallback : Callback + + export class SomeUsagesOfTheseConsts { +>SomeUsagesOfTheseConsts : SomeUsagesOfTheseConsts + + constructor() { + // these do get replaced by the const value + const value1 = ReExportedEnum.Cancel; +>value1 : ReExportedEnum.Cancel +>ReExportedEnum.Cancel : ReExportedEnum.Cancel +>ReExportedEnum : typeof ReExportedEnum +>Cancel : ReExportedEnum.Cancel + + console.log(value1); +>console.log(value1) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>value1 : ReExportedEnum.Cancel + + const value2 = DialogButtons.OKCancel; +>value2 : DialogButtons.OKCancel +>DialogButtons.OKCancel : DialogButtons.OKCancel +>DialogButtons : typeof DialogButtons +>OKCancel : DialogButtons.OKCancel + + console.log(value2); +>console.log(value2) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>value2 : DialogButtons.OKCancel + } + } +} + diff --git a/tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts b/tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts new file mode 100644 index 00000000000..71c8a29df26 --- /dev/null +++ b/tests/cases/compiler/exportImportCanSubstituteConstEnumForValue.ts @@ -0,0 +1,60 @@ +// @module: amd +// @declaration: true +// @target: es5 +module MsPortalFx.ViewModels.Dialogs { + + export const enum DialogResult { + Abort, + Cancel, + Ignore, + No, + Ok, + Retry, + Yes, + } + + export interface DialogResultCallback { + (result: MsPortalFx.ViewModels.Dialogs.DialogResult): void; + } + + export function someExportedFunction() { + } + + export const enum MessageBoxButtons { + AbortRetryIgnore, + OK, + OKCancel, + RetryCancel, + YesNo, + YesNoCancel, + } +} + + +module MsPortalFx.ViewModels { + + /** + * For some reason javascript code is emitted for this re-exported const enum. + */ + export import ReExportedEnum = Dialogs.DialogResult; + + /** + * Not exported to show difference. No javascript is emmitted (as expected) + */ + import DialogButtons = Dialogs.MessageBoxButtons; + + /** + * Re-exporting a function type to show difference. No javascript is emmitted (as expected) + */ + export import Callback = Dialogs.DialogResultCallback; + + export class SomeUsagesOfTheseConsts { + constructor() { + // these do get replaced by the const value + const value1 = ReExportedEnum.Cancel; + console.log(value1); + const value2 = DialogButtons.OKCancel; + console.log(value2); + } + } +} From c97fc64972d8d41f61ab32c8e9b0a7de88bd5892 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 29 Oct 2018 10:03:25 -0700 Subject: [PATCH 136/262] Always use `verify.completions` when testing completions (#28137) --- src/harness/fourslash.ts | 882 ++++++++++-------- ...tsAreAvailableAfterEditsAtEndOfFunction.ts | 2 +- tests/cases/fourslash/asOperatorCompletion.ts | 4 +- tests/cases/fourslash/augmentedTypesClass2.ts | 6 +- tests/cases/fourslash/augmentedTypesClass3.ts | 4 +- .../cases/fourslash/augmentedTypesModule1.ts | 5 +- .../cases/fourslash/augmentedTypesModule2.ts | 5 +- .../cases/fourslash/augmentedTypesModule3.ts | 5 +- .../cases/fourslash/augmentedTypesModule4.ts | 8 +- .../cases/fourslash/augmentedTypesModule5.ts | 8 +- tests/cases/fourslash/basicClassMembers.ts | 4 +- tests/cases/fourslash/cloduleAsBaseClass.ts | 21 +- .../fourslash/closedCommentsInConstructor.ts | 3 +- .../cases/fourslash/codeCompletionEscaping.ts | 10 +- tests/cases/fourslash/commentsClass.ts | 36 +- tests/cases/fourslash/commentsClassMembers.ts | 542 +++-------- .../cases/fourslash/commentsCommentParsing.ts | 99 +- tests/cases/fourslash/commentsEnums.ts | 35 +- .../fourslash/commentsExternalModules.ts | 76 +- .../fourslash/commentsFunctionDeclaration.ts | 19 +- .../fourslash/commentsFunctionExpression.ts | 50 +- tests/cases/fourslash/commentsInheritance.ts | 323 ++++--- tests/cases/fourslash/commentsInterface.ts | 112 ++- tests/cases/fourslash/commentsModules.ts | 176 ++-- .../fourslash/commentsMultiModuleMultiFile.ts | 9 +- .../commentsMultiModuleSingleFile.ts | 3 +- tests/cases/fourslash/commentsOverloads.ts | 110 ++- .../cases/fourslash/completionAfterAtChar.ts | 3 +- ...completionAfterBackslashFollowingString.ts | 3 +- tests/cases/fourslash/completionAfterBrace.ts | 8 +- .../fourslash/completionAfterDotDotDot.ts | 3 +- .../cases/fourslash/completionAwaitKeyword.ts | 4 - ...foreSemanticDiagnosticsInArrowFunction1.ts | 3 +- .../completionEntryForClassMembers.ts | 248 +++-- .../completionEntryForClassMembers2.ts | 434 ++++----- .../completionEntryForClassMembers3.ts | 12 +- .../fourslash/completionEntryForConst.ts | 3 +- ...letionEntryForDeferredMappedTypeMembers.ts | 7 +- .../fourslash/completionEntryForImportName.ts | 8 +- ...onEntryForPropertyFromUnionOfModuleType.ts | 3 +- ...tionEntryForShorthandPropertyAssignment.ts | 3 +- .../completionEntryForUnionMethod.ts | 20 +- .../completionEntryForUnionProperty.ts | 11 +- .../completionEntryForUnionProperty2.ts | 11 +- .../completionEntryOnNarrowedType.ts | 13 +- ...nForQuotedPropertyInPropertyAssignment1.ts | 8 +- ...nForQuotedPropertyInPropertyAssignment2.ts | 8 +- ...nForQuotedPropertyInPropertyAssignment3.ts | 6 +- ...nForQuotedPropertyInPropertyAssignment4.ts | 14 +- .../fourslash/completionForStringLiteral.ts | 8 +- .../fourslash/completionForStringLiteral10.ts | 7 +- .../fourslash/completionForStringLiteral11.ts | 7 +- .../fourslash/completionForStringLiteral12.ts | 4 +- .../fourslash/completionForStringLiteral13.ts | 3 +- .../fourslash/completionForStringLiteral2.ts | 6 +- .../fourslash/completionForStringLiteral3.ts | 2 +- .../fourslash/completionForStringLiteral4.ts | 5 +- .../fourslash/completionForStringLiteral5.ts | 6 +- .../fourslash/completionForStringLiteral6.ts | 5 +- .../fourslash/completionForStringLiteral7.ts | 6 +- .../fourslash/completionForStringLiteral8.ts | 7 +- .../completionForStringLiteralExport.ts | 10 +- ...completionForStringLiteralFromSignature.ts | 2 +- ...ompletionForStringLiteralFromSignature2.ts | 2 +- .../completionForStringLiteralImport1.ts | 10 +- .../completionForStringLiteralImport2.ts | 10 +- ...letionForStringLiteralInIndexedAccess01.ts | 5 +- ...etionForStringLiteralNonrelativeImport1.ts | 8 +- ...tionForStringLiteralNonrelativeImport10.ts | 2 +- ...tionForStringLiteralNonrelativeImport12.ts | 2 +- ...etionForStringLiteralNonrelativeImport2.ts | 2 +- ...etionForStringLiteralNonrelativeImport3.ts | 6 +- ...etionForStringLiteralNonrelativeImport4.ts | 2 +- ...etionForStringLiteralNonrelativeImport7.ts | 2 +- ...etionForStringLiteralNonrelativeImport8.ts | 2 +- ...etionForStringLiteralNonrelativeImport9.ts | 2 +- ...rStringLiteralNonrelativeImportTypings1.ts | 11 +- ...rStringLiteralNonrelativeImportTypings2.ts | 10 +- ...rStringLiteralNonrelativeImportTypings3.ts | 6 +- ...mpletionForStringLiteralRelativeImport4.ts | 2 +- ...StringLiteralRelativeImportAllowJSFalse.ts | 53 +- ...rStringLiteralRelativeImportAllowJSTrue.ts | 36 +- ...letionForStringLiteralWithDynamicImport.ts | 10 +- .../completionForStringLiteral_details.ts | 20 +- tests/cases/fourslash/completionImportMeta.ts | 3 +- .../completionInAugmentedClassModule.ts | 3 +- .../fourslash/completionInFunctionLikeBody.ts | 39 +- .../completionInIncompleteCallExpression.ts | 4 +- .../fourslash/completionInJSDocFunctionNew.ts | 3 +- .../completionInJSDocFunctionThis.ts | 3 +- tests/cases/fourslash/completionInJsDoc.ts | 60 +- .../completionInJsDocQualifiedNames.ts | 3 +- .../completionInNamedImportLocation.ts | 13 +- tests/cases/fourslash/completionInTypeOf1.ts | 5 +- tests/cases/fourslash/completionInTypeOf2.ts | 4 +- ...completionInfoWithExplicitTypeArguments.ts | 10 +- ...mpletionInsideFunctionContainsArguments.ts | 14 +- .../fourslash/completionListAfterAnyType.ts | 6 +- .../completionListAfterClassExtends.ts | 5 +- .../fourslash/completionListAfterFunction.ts | 17 +- .../fourslash/completionListAfterFunction2.ts | 11 +- .../fourslash/completionListAfterFunction3.ts | 9 +- .../completionListAfterInvalidCharacter.ts | 5 +- .../completionListAfterNumericLiteral.ts | 41 +- .../completionListAfterNumericLiteral1.ts | 3 +- .../completionListAfterObjectLiteral1.ts | 4 +- .../completionListAfterPropertyName.ts | 42 +- ...tionListAfterRegularExpressionLiteral01.ts | 4 +- ...tionListAfterRegularExpressionLiteral02.ts | 4 +- ...tionListAfterRegularExpressionLiteral03.ts | 3 +- ...tionListAfterRegularExpressionLiteral04.ts | 3 +- ...tionListAfterRegularExpressionLiteral05.ts | 4 +- ...etionListAfterRegularExpressionLiteral1.ts | 4 +- .../fourslash/completionListAfterSlash.ts | 3 +- .../completionListAfterSpreadOperator01.ts | 3 +- ...alTypeWithNoSubstitutionTemplateLiteral.ts | 4 +- ...mpletionListAndMemberListOnCommentedDot.ts | 3 +- ...pletionListAndMemberListOnCommentedLine.ts | 3 +- ...nListAndMemberListOnCommentedWhiteSpace.ts | 4 +- .../completionListAtBeginningOfFile01.ts | 6 +- ...tBeginningOfIdentifierInArrowFunction01.ts | 3 +- ...pletionListAtDeclarationOfParameterType.ts | 3 +- tests/cases/fourslash/completionListAtEOF.ts | 6 +- tests/cases/fourslash/completionListAtEOF1.ts | 2 +- tests/cases/fourslash/completionListAtEOF2.ts | 2 +- ...pletionListAtEndOfWordInArrowFunction01.ts | 3 +- ...pletionListAtEndOfWordInArrowFunction02.ts | 11 +- ...pletionListAtEndOfWordInArrowFunction03.ts | 13 +- ...tIdentifierDefinitionLocations_Generics.ts | 2 +- ...stAtIdentifierDefinitionLocations_catch.ts | 2 +- ...AtIdentifierDefinitionLocations_classes.ts | 2 +- ...tifierDefinitionLocations_destructuring.ts | 2 +- ...entifierDefinitionLocations_enumMembers.ts | 2 +- ...ntifierDefinitionLocations_enumMembers2.ts | 2 +- ...stAtIdentifierDefinitionLocations_enums.ts | 2 +- ...IdentifierDefinitionLocations_functions.ts | 2 +- ...dentifierDefinitionLocations_interfaces.ts | 2 +- ...dentifierDefinitionLocations_parameters.ts | 43 +- ...dentifierDefinitionLocations_properties.ts | 5 +- ...fierDefinitionLocations_varDeclarations.ts | 2 +- .../completionListAtInvalidLocations.ts | 5 +- ...dry.ts => completionListAtNodeBoundary.ts} | 4 +- .../fourslash/completionListBeforeKeyword.ts | 9 +- .../completionListBeforeNewScope01.ts | 4 +- .../completionListBeforeNewScope02.ts | 3 +- .../completionListBuilderLocations_Modules.ts | 9 +- ...stBuilderLocations_VariableDeclarations.ts | 8 +- ...mpletionListBuilderLocations_parameters.ts | 21 +- ...mpletionListBuilderLocations_properties.ts | 2 +- .../cases/fourslash/completionListCladule.ts | 9 +- .../fourslash/completionListClassMembers.ts | 63 +- ...mbersWithSuperClassFromUnknownNamespace.ts | 4 +- .../fourslash/completionListEnumMembers.ts | 17 +- .../fourslash/completionListEnumValues.ts | 23 +- .../fourslash/completionListErrorRecovery.ts | 5 +- .../completionListForDerivedType1.ts | 17 +- .../completionListForExportEquals.ts | 2 +- .../completionListForExportEquals2.ts | 2 +- .../completionListForGenericInstance1.ts | 3 +- ...berInAmbientModuleWithExportAssignment1.ts | 3 +- .../completionListForObjectSpread.ts | 28 +- .../cases/fourslash/completionListForRest.ts | 9 +- ...etionListForShorthandPropertyAssignment.ts | 4 +- ...tionListForShorthandPropertyAssignment2.ts | 4 +- ...ionListForTransitivelyExportedMembers01.ts | 7 +- ...ionListForTransitivelyExportedMembers02.ts | 6 +- ...ionListForTransitivelyExportedMembers03.ts | 7 +- ...ionListForTransitivelyExportedMembers04.ts | 4 +- .../completionListForUnicodeEscapeName.ts | 26 +- .../completionListFunctionExpression.ts | 8 +- .../completionListFunctionMembers.ts | 3 +- .../completionListGenericConstraints.ts | 34 +- ...etionListImplementingInterfaceFunctions.ts | 5 +- ...ListInArrowFunctionInUnclosedCallSite01.ts | 10 +- ...nListInClassExpressionWithTypeParameter.ts | 11 +- .../completionListInClosedFunction01.ts | 7 +- .../completionListInClosedFunction02.ts | 16 +- .../completionListInClosedFunction03.ts | 18 +- .../completionListInClosedFunction04.ts | 18 +- .../completionListInClosedFunction05.ts | 19 +- .../completionListInClosedFunction06.ts | 4 +- .../completionListInClosedFunction07.ts | 19 +- ...tInClosedObjectTypeLiteralInSignature01.ts | 14 +- ...tInClosedObjectTypeLiteralInSignature02.ts | 10 +- ...tInClosedObjectTypeLiteralInSignature03.ts | 14 +- ...tInClosedObjectTypeLiteralInSignature04.ts | 2 +- .../fourslash/completionListInComments.ts | 3 +- .../fourslash/completionListInComments2.ts | 3 +- .../fourslash/completionListInComments3.ts | 21 +- ...mpletionListInContextuallyTypedArgument.ts | 9 +- .../fourslash/completionListInEmptyFile.ts | 3 +- .../completionListInExportClause01.ts | 33 +- .../completionListInExportClause02.ts | 5 +- .../completionListInExportClause03.ts | 5 +- .../completionListInExtendsClause.ts | 14 +- .../completionListInExtendsClauseAtEOF.ts | 4 +- .../fourslash/completionListInFatArrow.ts | 2 +- .../completionListInFunctionDeclaration.ts | 13 +- .../completionListInFunctionExpression.ts | 17 +- .../completionListInImportClause01.ts | 33 +- .../completionListInImportClause02.ts | 4 +- .../completionListInImportClause03.ts | 5 +- .../completionListInImportClause04.ts | 2 +- .../completionListInImportClause05.ts | 2 +- .../completionListInImportClause06.ts | 2 +- .../completionListInIndexSignature01.ts | 7 +- .../completionListInIndexSignature02.ts | 6 +- ...stInMiddleOfIdentifierInArrowFunction01.ts | 3 +- .../completionListInNamedClassExpression.ts | 13 +- ...ListInNamedClassExpressionWithShadowing.ts | 29 +- ...completionListInNamedFunctionExpression.ts | 9 +- ...ompletionListInNamedFunctionExpression1.ts | 3 +- ...tInNamedFunctionExpressionWithShadowing.ts | 15 +- .../completionListInNamespaceImportName01.ts | 4 +- .../completionListInObjectBindingPattern01.ts | 5 +- .../completionListInObjectBindingPattern02.ts | 5 +- .../completionListInObjectBindingPattern03.ts | 4 +- .../completionListInObjectBindingPattern04.ts | 5 +- .../completionListInObjectBindingPattern05.ts | 4 +- .../completionListInObjectBindingPattern06.ts | 3 +- .../completionListInObjectBindingPattern07.ts | 6 +- .../completionListInObjectBindingPattern08.ts | 6 +- .../completionListInObjectBindingPattern09.ts | 7 +- .../completionListInObjectBindingPattern10.ts | 15 +- .../completionListInObjectBindingPattern11.ts | 6 +- .../completionListInObjectBindingPattern12.ts | 5 +- .../completionListInObjectBindingPattern13.ts | 6 +- .../completionListInObjectBindingPattern14.ts | 3 +- .../completionListInObjectLiteral.ts | 4 +- .../completionListInObjectLiteral2.ts | 12 +- .../completionListInObjectLiteral3.ts | 6 +- .../completionListInObjectLiteral4.ts | 5 +- ...onListInObjectLiteralPropertyAssignment.ts | 5 +- ...ectLiteralThatIsParameterOfFunctionCall.ts | 5 +- .../cases/fourslash/completionListInScope.ts | 97 +- ...ListInScope_doesNotIncludeAugmentations.ts | 3 +- .../completionListInStringLiterals1.ts | 2 +- .../completionListInStringLiterals2.ts | 2 +- .../completionListInTemplateLiteralParts1.ts | 5 +- ...ionListInTemplateLiteralPartsNegatives1.ts | 2 +- ...onListInTypeParameterOfClassExpression1.ts | 18 +- ...mpletionListInTypeParameterOfTypeAlias1.ts | 15 +- ...mpletionListInTypeParameterOfTypeAlias2.ts | 17 +- ...mpletionListInTypeParameterOfTypeAlias3.ts | 10 +- .../completionListInTypedObjectLiterals2.ts | 5 +- .../completionListInTypedObjectLiterals3.ts | 6 +- .../completionListInTypedObjectLiterals4.ts | 6 +- ...dObjectLiteralsWithPartialPropertyNames.ts | 17 +- ...ObjectLiteralsWithPartialPropertyNames2.ts | 5 +- ...mpletionListInUnclosedCommaExpression01.ts | 4 +- ...mpletionListInUnclosedCommaExpression02.ts | 4 +- ...pletionListInUnclosedDeleteExpression01.ts | 3 +- ...pletionListInUnclosedDeleteExpression02.ts | 4 +- ...ListInUnclosedElementAccessExpression01.ts | 3 +- ...ListInUnclosedElementAccessExpression02.ts | 4 +- .../completionListInUnclosedForLoop01.ts | 3 +- .../completionListInUnclosedForLoop02.ts | 3 +- ...ompletionListInUnclosedIndexSignature01.ts | 4 +- ...ompletionListInUnclosedIndexSignature02.ts | 7 +- ...ompletionListInUnclosedIndexSignature03.ts | 4 +- ...nUnclosedObjectTypeLiteralInSignature01.ts | 14 +- ...nUnclosedObjectTypeLiteralInSignature03.ts | 14 +- ...nUnclosedObjectTypeLiteralInSignature04.ts | 2 +- ...pletionListInUnclosedSpreadExpression01.ts | 3 +- ...pletionListInUnclosedSpreadExpression02.ts | 4 +- ...ompletionListInUnclosedTaggedTemplate01.ts | 4 +- ...ompletionListInUnclosedTaggedTemplate02.ts | 4 +- .../completionListInUnclosedTemplate01.ts | 4 +- .../completionListInUnclosedTemplate02.ts | 4 +- .../completionListInUnclosedTypeArguments.ts | 40 +- ...pletionListInUnclosedTypeOfExpression01.ts | 3 +- ...pletionListInUnclosedTypeOfExpression02.ts | 4 +- ...ompletionListInUnclosedVoidExpression01.ts | 4 +- ...mpletionListInUnclosedYieldExpression01.ts | 5 +- ...completionListInsideTargetTypedFunction.ts | 3 +- .../completionListInstanceProtectedMembers.ts | 43 +- ...completionListInstanceProtectedMembers2.ts | 70 +- ...completionListInstanceProtectedMembers3.ts | 20 +- ...completionListInstanceProtectedMembers4.ts | 11 +- .../completionListInvalidMemberNames.ts | 31 +- .../completionListInvalidMemberNames2.ts | 3 +- ...etionListInvalidMemberNames_escapeQuote.ts | 18 +- ...onListInvalidMemberNames_startWithSpace.ts | 6 +- ...validMemberNames_withExistingIdentifier.ts | 14 +- .../completionListIsGlobalCompletion.ts | 54 +- .../cases/fourslash/completionListKeywords.ts | 43 +- .../fourslash/completionListModuleMembers.ts | 47 +- ...mpletionListNewIdentifierBindingElement.ts | 3 +- ...ionListNewIdentifierFunctionDeclaration.ts | 9 +- ...ionListNewIdentifierVariableDeclaration.ts | 5 +- .../fourslash/completionListObjectMembers.ts | 7 +- .../completionListOfGenericSymbol.ts | 24 + .../fourslash/completionListOfGnericSymbol.ts | 11 - .../completionListOfSplitInterface.ts | 20 +- .../cases/fourslash/completionListOfUnion.ts | 20 +- .../completionListOnAliasedModule.ts | 4 +- .../fourslash/completionListOnAliases.ts | 9 +- .../fourslash/completionListOnAliases2.ts | 68 +- .../fourslash/completionListOnAliases3.ts | 6 +- ...nListOnFunctionCallWithOptionalArgument.ts | 3 +- .../completionListOnMethodParameterName.ts | 3 +- .../cases/fourslash/completionListOnParam.ts | 3 +- .../fourslash/completionListOnParamInClass.ts | 4 +- .../completionListOnParamOfGenericType1.ts | 14 +- ...completionListOnPrivateVariableInModule.ts | 3 +- .../cases/fourslash/completionListOnSuper.ts | 5 +- .../completionListOnVarBetweenModules.ts | 4 +- ...etionListOutsideOfClosedArrowFunction01.ts | 4 +- ...etionListOutsideOfClosedArrowFunction02.ts | 4 +- ...istOutsideOfClosedFunctionDeclaration01.ts | 4 +- .../completionListOutsideOfForLoop01.ts | 3 +- .../completionListOutsideOfForLoop02.ts | 3 +- .../fourslash/completionListPrivateMembers.ts | 5 +- .../completionListPrivateMembers2.ts | 11 +- .../completionListPrivateMembers3.ts | 12 +- .../completionListStaticProtectedMembers2.ts | 85 +- .../completionListStaticProtectedMembers3.ts | 24 +- .../completionListStaticProtectedMembers4.ts | 45 +- .../fourslash/completionListWithLabel.ts | 34 +- .../fourslash/completionListWithMeanings.ts | 75 +- .../completionListWithModulesFromModule.ts | 165 ++-- ...pletionListWithModulesInsideModuleScope.ts | 329 ++++--- ...letionListWithModulesOutsideModuleScope.ts | 111 +-- ...etionListWithModulesOutsideModuleScope2.ts | 122 +-- .../completionListWithUnresolvedModule.ts | 4 +- .../completionList_getExportsOfModule.ts | 3 +- .../fourslash/completionOfInterfaceAndVar.ts | 24 +- ...tionWithConditionalOperatorMissingColon.ts | 11 +- ...letionWithDotFollowedByNamespaceKeyword.ts | 3 +- .../completionWithNamespaceInsideFunction.ts | 47 +- .../fourslash/completionsDefaultExport.ts | 3 +- .../fourslash/completionsDestructuring.ts | 6 +- ...mpletionsForRecursiveGenericTypesMember.ts | 8 +- .../fourslash/completionsImportBaseUrl.ts | 15 +- ...letionsImport_default_addToNamedImports.ts | 15 +- ...ionsImport_default_addToNamespaceImport.ts | 9 +- ...Import_default_alreadyExistedWithRename.ts | 9 +- .../completionsImport_default_anonymous.ts | 12 +- ...letionsImport_default_didNotExistBefore.ts | 9 +- ...sImport_default_exportDefaultIdentifier.ts | 8 +- ...nsImport_default_fromMergedDeclarations.ts | 9 +- .../completionsImport_multipleWithSameName.ts | 17 +- ...mpletionsImport_named_addToNamedImports.ts | 9 +- ...mpletionsImport_named_didNotExistBefore.ts | 8 +- ...tionsImport_named_exportEqualsNamespace.ts | 9 +- ...port_named_exportEqualsNamespace_merged.ts | 8 +- ...tionsImport_named_namespaceImportExists.ts | 9 +- .../completionsImport_notFromIndex.ts | 7 +- .../fourslash/completionsImport_ofAlias.ts | 7 +- ...mpletionsImport_ofAlias_preferShortPath.ts | 8 +- ...pletionsImport_previousTokenIsSemicolon.ts | 8 +- .../completionsImport_reExportDefault.ts | 14 +- .../completionsImport_reExport_wrongName.ts | 1 - .../fourslash/completionsImport_require.ts | 9 +- .../completionsImport_shadowedByLocal.ts | 7 +- tests/cases/fourslash/completionsInJsxTag.ts | 7 +- .../fourslash/completionsInterfaceElement.ts | 4 +- .../completionsJsPropertyAssignment.ts | 2 +- tests/cases/fourslash/completionsJsdocTag.ts | 3 +- .../fourslash/completionsJsdocTypeTagCast.ts | 2 +- .../completionsJsxAttributeInitializer.ts | 25 +- .../completionsJsxAttributeInitializer2.ts | 17 +- tests/cases/fourslash/completionsKeyof.ts | 12 +- .../fourslash/completionsKeywordsExtends.ts | 12 +- .../completionsMethodWithThisParameter.ts | 6 +- .../completionsNamespaceMergedWithClass.ts | 11 +- .../completionsNamespaceMergedWithObject.ts | 11 +- tests/cases/fourslash/completionsNewTarget.ts | 3 +- .../completionsOptionalKindModifier.ts | 10 +- .../fourslash/completionsOptionalMethod.ts | 2 +- .../fourslash/completionsPathsJsonModule.ts | 2 +- .../completionsPathsJsonModuleWithAmd.ts | 2 +- ...PathsJsonModuleWithoutResolveJsonModule.ts | 2 +- .../completionsPathsRelativeJsonModule.ts | 2 +- .../fourslash/completionsPaths_pathMapping.ts | 6 +- ...etionsPaths_pathMapping_parentDirectory.ts | 2 +- ...mpletionsPaths_pathMapping_relativePath.ts | 2 +- .../completionsPaths_pathMapping_topLevel.ts | 2 +- .../completionsRecommended_contextualTypes.ts | 26 +- .../completionsRecommended_equals.ts | 5 +- .../completionsRecommended_import.ts | 40 +- .../fourslash/completionsRecommended_local.ts | 37 +- .../completionsRecommended_namespace.ts | 24 +- ...pletionsRecommended_nonAccessibleSymbol.ts | 3 +- .../completionsRecommended_switch.ts | 5 +- ...letionsStringLiteral_fromTypeConstraint.ts | 2 +- .../fourslash/completionsSymbolMembers.ts | 14 +- tests/cases/fourslash/completionsUnion.ts | 2 +- .../constEnumQuickInfoAndCompletionList.ts | 8 +- .../constQuickInfoAndCompletionList.ts | 39 +- .../fourslash/doubleUnderscoreCompletions.ts | 10 +- tests/cases/fourslash/exportDefaultClass.ts | 6 +- .../cases/fourslash/exportDefaultFunction.ts | 9 +- .../fourslash/exportEqualCallableInterface.ts | 8 +- tests/cases/fourslash/exportEqualTypes.ts | 3 +- tests/cases/fourslash/extendArrayInterface.ts | 3 +- .../fourslash/externalModuleIntellisense.ts | 4 +- ...ernceResolutionOrderInImportDeclaration.ts | 3 +- .../externalModuleWithExportAssignment.ts | 29 +- tests/cases/fourslash/forwardReference.ts | 3 +- tests/cases/fourslash/fourslash.ts | 92 +- tests/cases/fourslash/functionProperty.ts | 20 +- tests/cases/fourslash/functionTypes.ts | 11 +- .../fourslash/genericCloduleCompletionList.ts | 4 +- ...genericTypeAliasIntersectionCompletions.ts | 4 +- .../genericTypeWithMultipleBases1.ts | 12 +- .../genericTypeWithMultipleBases1MultiFile.ts | 12 +- .../fourslash/getCompletionEntryDetails.ts | 23 +- .../fourslash/getCompletionEntryDetails2.ts | 10 +- .../fourslash/getJavaScriptCompletions1.ts | 3 +- .../fourslash/getJavaScriptCompletions10.ts | 3 +- .../fourslash/getJavaScriptCompletions11.ts | 10 +- .../fourslash/getJavaScriptCompletions14.ts | 3 +- .../fourslash/getJavaScriptCompletions15.ts | 14 +- .../fourslash/getJavaScriptCompletions16.ts | 4 +- .../fourslash/getJavaScriptCompletions18.ts | 5 +- .../fourslash/getJavaScriptCompletions19.ts | 4 +- .../fourslash/getJavaScriptCompletions2.ts | 3 +- .../fourslash/getJavaScriptCompletions20.ts | 10 +- .../fourslash/getJavaScriptCompletions3.ts | 3 +- .../fourslash/getJavaScriptCompletions4.ts | 3 +- .../fourslash/getJavaScriptCompletions5.ts | 6 +- .../fourslash/getJavaScriptCompletions8.ts | 3 +- .../fourslash/getJavaScriptCompletions9.ts | 3 +- .../getJavaScriptGlobalCompletions1.ts | 4 +- .../fourslash/getJavaScriptQuickInfo8.ts | 4 +- ...lobalCompletionListInsideObjectLiterals.ts | 33 +- .../fourslash/identifierErrorRecovery.ts | 3 +- tests/cases/fourslash/importJsNodeModule1.ts | 6 +- tests/cases/fourslash/importJsNodeModule2.ts | 11 +- tests/cases/fourslash/importJsNodeModule3.ts | 8 +- tests/cases/fourslash/importJsNodeModule4.ts | 6 +- .../fourslash/importTypeMemberCompletions.ts | 20 +- .../fourslash/indirectClassInstantiation.ts | 2 +- tests/cases/fourslash/javaScriptClass4.ts | 3 +- tests/cases/fourslash/javaScriptModules13.ts | 7 +- tests/cases/fourslash/javaScriptModules14.ts | 6 +- tests/cases/fourslash/javaScriptModules15.ts | 6 +- tests/cases/fourslash/javaScriptModules16.ts | 11 +- tests/cases/fourslash/javaScriptModules17.ts | 6 +- tests/cases/fourslash/javaScriptModules18.ts | 4 +- tests/cases/fourslash/javaScriptModules19.ts | 7 +- .../javaScriptModulesWithBackticks.ts | 3 +- tests/cases/fourslash/javaScriptPrototype1.ts | 13 +- tests/cases/fourslash/javaScriptPrototype3.ts | 17 +- tests/cases/fourslash/javaScriptPrototype4.ts | 6 +- tests/cases/fourslash/javaScriptPrototype5.ts | 3 +- tests/cases/fourslash/javascriptModules20.ts | 3 +- tests/cases/fourslash/javascriptModules21.ts | 3 +- tests/cases/fourslash/javascriptModules22.ts | 7 +- tests/cases/fourslash/javascriptModules23.ts | 3 +- tests/cases/fourslash/javascriptModules25.ts | 3 +- .../fourslash/jsDocFunctionSignatures3.ts | 6 +- tests/cases/fourslash/jsDocGenerics1.ts | 10 +- tests/cases/fourslash/jsDocTags.ts | 17 +- ...JsdocTypedefTagTypeExpressionCompletion.ts | 96 +- ...sdocTypedefTagTypeExpressionCompletion2.ts | 58 +- ...sdocTypedefTagTypeExpressionCompletion3.ts | 155 ++- tests/cases/fourslash/jsdocNullableUnion.ts | 22 +- .../fourslash/jsdocParameterNameCompletion.ts | 10 +- ...jsdocTypedefTagTypeExpressionCompletion.ts | 158 +--- tests/cases/fourslash/lambdaThisMembers.ts | 6 +- .../letQuickInfoAndCompletionList.ts | 31 +- .../memberCompletionFromFunctionCall.ts | 3 +- .../fourslash/memberCompletionInForEach1.ts | 6 +- .../memberCompletionOnRightSideOfImport.ts | 3 +- .../memberCompletionOnTypeParameters2.ts | 5 +- .../fourslash/memberListAfterDoubleDot.ts | 3 +- .../fourslash/memberListAfterSingleDot.ts | 3 +- .../fourslash/memberListErrorRecovery.ts | 4 +- .../fourslash/memberListInFunctionCall.ts | 3 +- .../fourslash/memberListInReopenedEnum.ts | 15 +- .../cases/fourslash/memberListInWithBlock.ts | 16 +- .../cases/fourslash/memberListInWithBlock2.ts | 5 +- .../cases/fourslash/memberListInWithBlock3.ts | 3 +- tests/cases/fourslash/memberListOfClass.ts | 11 +- .../memberListOfEnumFromExternalModule.ts | 4 +- .../fourslash/memberListOfEnumInModule.ts | 4 +- .../fourslash/memberListOfExportedClass.ts | 4 +- tests/cases/fourslash/memberListOfModule.ts | 5 +- .../memberListOfModuleAfterInvalidCharater.ts | 3 +- .../memberListOfModuleBeforeKeyword.ts | 12 +- .../memberListOfModuleInAnotherModule.ts | 26 +- .../memberListOfVarInArrowExpression.ts | 5 +- .../fourslash/memberListOnConstructorType.ts | 4 +- .../fourslash/memberListOnContextualThis.ts | 7 +- .../fourslash/memberListOnExplicitThis.ts | 31 +- .../memberListOnFunctionParameter.ts | 11 +- .../memberListOnThisInClassWithPrivates.ts | 13 +- tests/cases/fourslash/memberlistOnDDot.ts | 2 +- tests/cases/fourslash/mergedDeclarations1.ts | 12 +- tests/cases/fourslash/mergedDeclarations2.ts | 9 +- ...mergedDeclarationsWithExportAssignment1.ts | 28 +- .../fourslash/moduleMembersOfGenericType.ts | 3 +- tests/cases/fourslash/multiModuleClodule1.ts | 29 +- tests/cases/fourslash/multiModuleFundule1.ts | 10 +- ...etionListOnCommentsInsideObjectLiterals.ts | 6 +- ...oImportCompletionsInOtherJavaScriptFile.ts | 28 +- tests/cases/fourslash/nonExistingImport.ts | 3 +- .../objectLiteralBindingInParameter.ts | 16 +- .../fourslash/paramHelpOnCommaInString.ts | 2 +- .../fourslash/parameterInfoOnParameterType.ts | 2 +- tests/cases/fourslash/proto.ts | 3 +- .../fourslash/protoPropertyInObjectLiteral.ts | 6 +- .../protoVarInContextualObjectLiteral.ts | 61 +- ...VarVisibleWithOuterScopeUnderscoreProto.ts | 10 +- tests/cases/fourslash/prototypeProperty.ts | 3 +- ...-declaration-with-variable-entity-names.ts | 2 +- .../fourslash/quickInfoOnNarrowedType.ts | 39 +- .../quickInfoOnNarrowedTypeInModule.ts | 68 +- .../quickInfoOnObjectLiteralWithAccessors.ts | 19 +- .../quickInfoOnObjectLiteralWithOnlyGetter.ts | 10 +- .../quickInfoOnObjectLiteralWithOnlySetter.ts | 21 +- ...lsaMethodsOnAssignedFunctionExpressions.ts | 11 +- .../fourslash/selfReferencedExternalModule.ts | 10 +- .../completionEntryDetailAcrossFiles01.ts | 9 +- tests/cases/fourslash/server/completions01.ts | 6 +- tests/cases/fourslash/server/completions02.ts | 8 +- tests/cases/fourslash/server/completions03.ts | 5 +- .../server/jsdocParamTagSpecialKeywords.ts | 4 +- .../cases/fourslash/server/jsdocTypedefTag.ts | 49 +- .../fourslash/server/jsdocTypedefTag1.ts | 5 +- .../fourslash/server/jsdocTypedefTag2.ts | 13 +- .../server/jsdocTypedefTagNamespace.ts | 14 +- tests/cases/fourslash/server/openFile.ts | 2 +- .../server/openFileWithSyntaxKind.ts | 2 +- .../fourslash/server/typeReferenceOnServer.ts | 3 +- .../shims-pp/getCompletionsAtPosition.ts | 15 +- .../shims/getCompletionsAtPosition.ts | 13 +- .../signatureHelpTaggedTemplates1.ts | 2 +- .../signatureHelpTaggedTemplates2.ts | 2 +- .../signatureHelpTaggedTemplates3.ts | 2 +- .../signatureHelpTaggedTemplates4.ts | 2 +- .../signatureHelpTaggedTemplates5.ts | 2 +- .../signatureHelpTaggedTemplates6.ts | 2 +- .../signatureHelpTaggedTemplates7.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete1.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete2.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete3.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete4.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete5.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete6.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete7.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete8.ts | 2 +- ...signatureHelpTaggedTemplatesIncomplete9.ts | 2 +- .../signatureHelpTaggedTemplatesNested1.ts | 2 +- .../signatureHelpTaggedTemplatesNested2.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags1.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags2.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags3.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags4.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags5.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags6.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags7.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags8.ts | 2 +- ...eHelpTaggedTemplatesWithOverloadedTags9.ts | 2 +- ...lCompletionsForStringEnumContextualType.ts | 3 +- .../thisPredicateFunctionCompletions01.ts | 18 +- .../thisPredicateFunctionCompletions02.ts | 15 +- .../thisPredicateFunctionCompletions03.ts | 14 +- ...ipleSlashRefPathCompletionAbsolutePaths.ts | 19 +- ...ashRefPathCompletionBackandForwardSlash.ts | 15 +- .../tripleSlashRefPathCompletionContext.ts | 14 +- ...RefPathCompletionExtensionsAllowJSFalse.ts | 26 +- ...hRefPathCompletionExtensionsAllowJSTrue.ts | 2 +- .../tripleSlashRefPathCompletionHiddenFile.ts | 6 +- .../tripleSlashRefPathCompletionNarrowing.ts | 19 +- ...ipleSlashRefPathCompletionRelativePaths.ts | 22 +- .../tripleSlashRefPathCompletionRootdirs.ts | 7 +- tests/cases/fourslash/tsxCompletion1.ts | 4 +- tests/cases/fourslash/tsxCompletion11.ts | 3 +- tests/cases/fourslash/tsxCompletion12.ts | 28 +- tests/cases/fourslash/tsxCompletion13.ts | 35 +- tests/cases/fourslash/tsxCompletion2.ts | 4 +- tests/cases/fourslash/tsxCompletion3.ts | 4 +- tests/cases/fourslash/tsxCompletion4.ts | 3 +- tests/cases/fourslash/tsxCompletion5.ts | 5 +- tests/cases/fourslash/tsxCompletion6.ts | 5 +- tests/cases/fourslash/tsxCompletion7.ts | 6 +- tests/cases/fourslash/tsxCompletion9.ts | 9 +- ...nInFunctionExpressionOfChildrenCallback.ts | 5 +- ...InFunctionExpressionOfChildrenCallback1.ts | 5 +- .../fourslash/tsxCompletionNonTagLessThan.ts | 13 +- .../tsxCompletionOnOpeningTagWithoutJSX1.ts | 3 +- .../tsxCompletionUnionElementType.ts | 3 +- tests/cases/fourslash/typeArgCompletion.ts | 3 +- .../unclosedCommentsInConstructor.ts | 5 +- .../unclosedStringLiteralErrorRecovery.ts | 3 +- tests/cases/fourslash/underscoreTypings01.ts | 4 +- 589 files changed, 4240 insertions(+), 5731 deletions(-) delete mode 100644 tests/cases/fourslash/completionAwaitKeyword.ts rename tests/cases/fourslash/{completionListAtNodeBoundry.ts => completionListAtNodeBoundary.ts} (85%) create mode 100644 tests/cases/fourslash/completionListOfGenericSymbol.ts delete mode 100644 tests/cases/fourslash/completionListOfGnericSymbol.ts diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 406985f1efa..82ef60e7fbc 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -729,97 +729,6 @@ namespace FourSlash { }); } - public verifyCompletionListCount(expectedCount: number, negative: boolean) { - if (expectedCount === 0 && negative) { - this.verifyCompletionListIsEmpty(/*negative*/ false); - return; - } - - const members = this.getCompletionListAtCaret(); - - if (members) { - const match = members.entries.length === expectedCount; - - if ((!match && !negative) || (match && negative)) { - this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount); - } - } - else if (expectedCount) { - this.raiseError("Member list count was 0. Expected " + expectedCount); - } - } - - public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) { - const completions = this.getCompletionListAtCaret(); - const itemsCount = completions ? completions.entries.length : 0; - - if (negative) { - if (itemsCount > count) { - this.raiseError(`Expected completion list items count to not be greater than ${count}, but is actually ${itemsCount}`); - } - } - else { - if (itemsCount <= count) { - this.raiseError(`Expected completion list items count to be greater than ${count}, but is actually ${itemsCount}`); - } - } - } - - public verifyCompletionListStartsWithItemsInOrder(items: string[]): void { - if (items.length === 0) { - return; - } - - const entries = this.getCompletionListAtCaret()!.entries; - assert.isTrue(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`); - ts.zipWith(entries, items, (entry, item) => { - assert.equal(entry.name, item, `Unexpected item in completion list`); - }); - } - - public noItemsWithSameNameButDifferentKind(): void { - const completions = this.getCompletionListAtCaret()!; - const uniqueItems = ts.createMap(); - for (const item of completions.entries) { - const uniqueItem = uniqueItems.get(item.name); - if (!uniqueItem) { - uniqueItems.set(item.name, item.kind); - } - else { - assert.equal(item.kind, uniqueItem, `Items should have the same kind, got ${item.kind} and ${uniqueItem}`); - } - } - } - - public verifyCompletionListIsEmpty(negative: boolean) { - const completions = this.getCompletionListAtCaret(); - if ((!completions || completions.entries.length === 0) && negative) { - this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); - } - else if (completions && completions.entries.length !== 0 && !negative) { - this.raiseError(`Completion list is not empty at caret at position ${this.activeFile.fileName} ${this.currentCaretPosition}\n` + - `Completion List contains: ${stringify(completions.entries.map(e => e.name))}`); - } - } - - public verifyCompletionListAllowsNewIdentifier(negative: boolean) { - const completions = this.getCompletionListAtCaret(); - - if ((completions && !completions.isNewIdentifierLocation) && !negative) { - this.raiseError("Expected builder completion entry"); - } - else if ((completions && completions.isNewIdentifierLocation) && negative) { - this.raiseError("Un-expected builder completion entry"); - } - } - - public verifyCompletionListIsGlobal(expected: boolean) { - const completions = this.getCompletionListAtCaret(); - if (completions && completions.isGlobalCompletion !== expected) { - this.raiseError(`verifyCompletionListIsGlobal failed - expected result to be ${completions.isGlobalCompletion}`); - } - } - public verifyCompletions(options: FourSlashInterface.VerifyCompletionsOptions) { if (options.marker === undefined) { this.verifyCompletionsWorker(options); @@ -843,13 +752,21 @@ namespace FourSlash { this.raiseError(`Expected 'isNewIdentifierLocation' to be ${options.isNewIdentifierLocation || false}, got ${actualCompletions.isNewIdentifierLocation}`); } - const actualByName = ts.createMap(); + if ("isGlobalCompletion" in options && actualCompletions.isGlobalCompletion !== options.isGlobalCompletion) { + this.raiseError(`Expected 'isGlobalCompletion to be ${options.isGlobalCompletion}, got ${actualCompletions.isGlobalCompletion}`); + } + + const nameToEntries = ts.createMap(); for (const entry of actualCompletions.entries) { - if (actualByName.has(entry.name)) { - this.raiseError(`Duplicate (${actualCompletions.entries.filter(a => a.name === entry.name).length}) completions for ${entry.name}`); + const entries = nameToEntries.get(entry.name); + if (!entries) { + nameToEntries.set(entry.name, [entry]); } else { - actualByName.set(entry.name, entry); + if (entries.some(e => e.source === entry.source)) { + this.raiseError(`Duplicate completions for ${entry.name}`); + } + entries.push(entry); } } @@ -862,23 +779,16 @@ namespace FourSlash { if (options.includes) { for (const include of toArray(options.includes)) { const name = typeof include === "string" ? include : include.name; - const found = actualByName.get(name); + const found = nameToEntries.get(name); if (!found) throw this.raiseError(`No completion ${name} found`); - this.verifyCompletionEntry(found, include); + assert(found.length === 1); // Must use 'exact' for multiple completions with same name + this.verifyCompletionEntry(ts.first(found), include); } } if (options.excludes) { for (const exclude of toArray(options.excludes)) { - if (typeof exclude === "string") { - if (actualByName.has(exclude)) { - this.raiseError(`Did not expect to get a completion named ${exclude}`); - } - } - else { - const found = actualByName.get(exclude.name); - if (found && found.source === exclude.source) { - this.raiseError(`Did not expect to get a completion named ${exclude.name} with source ${exclude.source}`); - } + if (nameToEntries.has(exclude)) { + this.raiseError(`Did not expect to get a completion named ${exclude}`); } } } @@ -902,6 +812,7 @@ namespace FourSlash { } if (kind !== undefined) assert.equal(actual.kind, kind); + if (typeof expected !== "string" && "kindModifiers" in expected) assert.equal(actual.kindModifiers, expected.kindModifiers); assert.equal(actual.hasAction, hasAction); assert.equal(actual.isRecommended, isRecommended); @@ -923,9 +834,8 @@ namespace FourSlash { } private verifyCompletionsAreExactly(actual: ReadonlyArray, expected: ReadonlyArray) { - if (actual.length !== expected.length) { - this.raiseError(`Expected ${expected.length} completions, got ${actual.length} (${actual.map(a => a.name)}).`); - } + // First pass: test that names are right. Then we'll test details. + assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name)); ts.zipWith(actual, expected, (completion, expectedCompletion, index) => { const name = typeof expectedCompletion === "string" ? expectedCompletion : expectedCompletion.name; @@ -936,117 +846,6 @@ namespace FourSlash { }); } - public verifyCompletionsAt(markerName: string | ReadonlyArray, expected: ReadonlyArray, options?: FourSlashInterface.CompletionsAtOptions) { - this.verifyCompletions({ - marker: markerName, - exact: expected, - isNewIdentifierLocation: options && options.isNewIdentifierLocation, - preferences: options, - triggerCharacter: options && options.triggerCharacter, - }); - } - - public verifyCompletionListContains(entryId: ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: FourSlashInterface.VerifyCompletionListContainsOptions) { - const completions = this.getCompletionListAtCaret(options); - if (completions) { - this.assertItemInCompletionList(completions.entries, entryId, text, documentation, kind, spanIndex, hasAction, options); - } - else { - this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${JSON.stringify(entryId)}'.`); - } - } - - /** - * Verify that the completion list does NOT contain the given symbol. - * The symbol is considered matched with the symbol in the list if and only if all given parameters must matched. - * When any parameter is omitted, the parameter is ignored during comparison and assumed that the parameter with - * that property of the symbol in the list. - * @param symbol the name of symbol - * @param expectedText the text associated with the symbol - * @param expectedDocumentation the documentation text associated with the symbol - * @param expectedKind the kind of symbol (see ScriptElementKind) - * @param spanIndex the index of the range that the completion item's replacement text span should match - */ - public verifyCompletionListDoesNotContain(entryId: ts.Completions.CompletionEntryIdentifier, expectedText?: string, expectedDocumentation?: string, expectedKind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, options?: FourSlashInterface.CompletionsAtOptions) { - let replacementSpan: ts.TextSpan | undefined; - if (spanIndex !== undefined) { - replacementSpan = this.getTextSpanForRangeAtIndex(spanIndex); - } - - const completions = this.getCompletionListAtCaret(options); - if (completions) { - let filterCompletions = completions.entries.filter(e => e.name === entryId.name && e.source === entryId.source); - filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind || (typeof expectedKind === "object" && e.kind === expectedKind.kind)) : filterCompletions; - filterCompletions = filterCompletions.filter(entry => { - const details = this.getCompletionEntryDetails(entry.name); - const documentation = details && ts.displayPartsToString(details.documentation); - const text = details && ts.displayPartsToString(details.displayParts); - - // If any of the expected values are undefined, assume that users don't - // care about them. - if (replacementSpan && !ts.textSpansEqual(replacementSpan, entry.replacementSpan)) { - return false; - } - else if (expectedText && text !== expectedText) { - return false; - } - else if (expectedDocumentation && documentation !== expectedDocumentation) { - return false; - } - - return true; - }); - if (filterCompletions.length !== 0) { - // After filtered using all present criterion, if there are still symbol left in the list - // then these symbols must meet the criterion for Not supposed to be in the list. So we - // raise an error - let error = `Completion list did contain '${JSON.stringify(entryId)}\'.`; - const details = this.getCompletionEntryDetails(filterCompletions[0].name)!; - if (expectedText) { - error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + "."; - } - if (expectedDocumentation) { - error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + "."; - } - if (expectedKind) { - error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "."; - } - else { - error += "kind: " + filterCompletions[0].kind + "."; - } - if (replacementSpan) { - const spanText = filterCompletions[0].replacementSpan ? stringify(filterCompletions[0].replacementSpan) : undefined; - error += "Expected replacement span: " + stringify(replacementSpan) + " to equal: " + spanText + "."; - } - this.raiseError(error); - } - } - } - - public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) { - const details = this.getCompletionEntryDetails(entryName)!; - - assert(details, "no completion entry available"); - - assert.equal(ts.displayPartsToString(details.displayParts), expectedText, this.assertionMessageAtLastKnownMarker("completion entry details text")); - - if (expectedDocumentation !== undefined) { - assert.equal(ts.displayPartsToString(details.documentation), expectedDocumentation, this.assertionMessageAtLastKnownMarker("completion entry documentation")); - } - - if (kind !== undefined) { - assert.equal(details.kind, kind, this.assertionMessageAtLastKnownMarker("completion entry kind")); - } - - if (tags !== undefined) { - assert.equal(details.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); - ts.zipWith(tags, details.tags!, (expectedTag, actualTag) => { - assert.equal(actualTag.name, expectedTag.name); - assert.equal(actualTag.text, expectedTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); - }); - } - } - /** Use `getProgram` instead of accessing this directly. */ private _program: ts.Program; /** Use `getChecker` instead of accessing this directly. */ @@ -3172,74 +2971,6 @@ Actual: ${stringify(fullActual)}`); return text.substring(startPos, endPos); } - private assertItemInCompletionList( - items: ts.CompletionEntry[], - entryId: ts.Completions.CompletionEntryIdentifier, - text: string | undefined, - documentation: string | undefined, - kind: string | undefined | { kind?: string, kindModifiers?: string }, - spanIndex: number | undefined, - hasAction: boolean | undefined, - options: FourSlashInterface.VerifyCompletionListContainsOptions | undefined, - ) { - const eq = (a: T, b: T, msg: string) => { - assert.deepEqual(a, b, this.assertionMessageAtLastKnownMarker(msg + " for " + stringify(entryId))); - }; - const matchingItems = items.filter(item => item.name === entryId.name && item.source === entryId.source); - if (matchingItems.length === 0) { - const itemsString = items.map(item => stringify({ name: item.name, source: item.source, kind: item.kind })).join(",\n"); - this.raiseError(`Expected "${stringify({ entryId, text, documentation, kind })}" to be in list [${itemsString}]`); - } - else if (matchingItems.length > 1) { - this.raiseError(`Found duplicate completion items for ${stringify(entryId)}`); - } - const item = matchingItems[0]; - - if (documentation !== undefined || text !== undefined || entryId.source !== undefined) { - const details = this.getCompletionEntryDetails(item.name, item.source)!; - - if (documentation !== undefined) { - eq(ts.displayPartsToString(details.documentation), documentation, "completion item documentation"); - } - if (text !== undefined) { - eq(ts.displayPartsToString(details.displayParts), text, "completion item detail text"); - } - - if (entryId.source === undefined) { - eq(options && options.sourceDisplay, /*b*/ undefined, "source display"); - } - else { - eq(details.source, [ts.textPart(options!.sourceDisplay)], "source display"); - } - } - - if (kind !== undefined) { - if (typeof kind === "string") { - eq(item.kind, kind, "completion item kind"); - } - else { - if (kind.kind) { - eq(item.kind, kind.kind, "completion item kind"); - } - if (kind.kindModifiers !== undefined) { - eq(item.kindModifiers, kind.kindModifiers, "completion item kindModifiers"); - } - } - } - - - - if (spanIndex !== undefined) { - const span = this.getTextSpanForRangeAtIndex(spanIndex); - assert.isTrue(ts.textSpansEqual(span, item.replacementSpan), this.assertionMessageAtLastKnownMarker(stringify(span) + " does not equal " + stringify(item.replacementSpan) + " replacement span for " + stringify(entryId))); - } - - eq(item.hasAction, hasAction, "hasAction"); - eq(item.isRecommended, options && options.isRecommended, "isRecommended"); - eq(item.insertText, options && options.insertText, "insertText"); - eq(item.replacementSpan, options && options.replacementSpan && ts.createTextSpanFromRange(options.replacementSpan), "replacementSpan"); - } - private findFile(indexOrName: string | number): FourSlashFile { if (typeof indexOrName === "number") { const index = indexOrName; @@ -3289,16 +3020,6 @@ Actual: ${stringify(fullActual)}`); return `line ${(pos.line + 1)}, col ${pos.character}`; } - private getTextSpanForRangeAtIndex(index: number): ts.TextSpan { - const ranges = this.getRanges(); - if (ranges.length > index) { - return ts.createTextSpanFromRange(ranges[index]); - } - else { - throw this.raiseError("Supplied span index: " + index + " does not exist in range list of size: " + ranges.length); - } - } - public getMarkerByName(markerName: string) { const markerPos = this.testData.markerPositions.get(markerName); if (markerPos === undefined) { @@ -3418,7 +3139,7 @@ Actual: ${stringify(fullActual)}`); function runCode(code: string, state: TestState): void { // Compile and execute the test const wrappedCode = - `(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) { + `(function(test, goTo, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) { ${code} })`; try { @@ -3430,7 +3151,7 @@ ${code} const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); const f = eval(wrappedCode); - f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, verifyOperationIsCancelled); + f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); } catch (err) { throw err; @@ -3997,24 +3718,6 @@ namespace FourSlashInterface { export class VerifyNegatable { public not: VerifyNegatable; - public allowedClassElementKeywords = [ - "public", - "private", - "protected", - "static", - "abstract", - "readonly", - "get", - "set", - "constructor", - "async" - ]; - public allowedConstructorParameterKeywords = [ - "public", - "private", - "protected", - "readonly", - ]; constructor(protected state: FourSlash.TestState, private negative = false) { if (!negative) { @@ -4022,58 +3725,10 @@ namespace FourSlashInterface { } } - public completionListCount(expectedCount: number) { - this.state.verifyCompletionListCount(expectedCount, this.negative); - } - - // Verifies the completion list contains the specified symbol. The - // completion list is brought up if necessary - public completionListContains(entryId: string | ts.Completions.CompletionEntryIdentifier, text?: string, documentation?: string, kind?: string | { kind?: string, kindModifiers?: string }, spanIndex?: number, hasAction?: boolean, options?: VerifyCompletionListContainsOptions) { - if (typeof entryId === "string") { - entryId = { name: entryId, source: undefined }; - } - if (this.negative) { - this.state.verifyCompletionListDoesNotContain(entryId, text, documentation, kind, spanIndex, options); - } - else { - this.state.verifyCompletionListContains(entryId, text, documentation, kind, spanIndex, hasAction, options); - } - } - - // Verifies the completion list items count to be greater than the specified amount. The - // completion list is brought up if necessary - public completionListItemsCountIsGreaterThan(count: number) { - this.state.verifyCompletionListItemsCountIsGreaterThan(count, this.negative); - } - public assertHasRanges(ranges: FourSlash.Range[]) { assert(ranges.length !== 0, "Array of ranges is expected to be non-empty"); } - public completionListIsEmpty() { - this.state.verifyCompletionListIsEmpty(this.negative); - } - - public completionListContainsClassElementKeywords() { - for (const keyword of this.allowedClassElementKeywords) { - this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); - } - } - - public completionListContainsConstructorParameterKeywords() { - for (const keyword of this.allowedConstructorParameterKeywords) { - this.completionListContains(keyword, keyword, /*documentation*/ undefined, "keyword"); - } - } - - public completionListIsGlobal(expected: boolean) { - this.state.verifyCompletionListIsGlobal(expected); - } - - public completionListAllowsNewIdentifier() { - this.state.verifyCompletionListAllowsNewIdentifier(this.negative); - } - public noSignatureHelp(...markers: string[]): void { this.state.verifySignatureHelpPresence(/*expectPresent*/ false, /*triggerReason*/ undefined, markers); } @@ -4160,10 +3815,6 @@ namespace FourSlashInterface { super(state); } - public completionsAt(markerName: ArrayOrSingle, completions: ReadonlyArray, options?: CompletionsAtOptions) { - this.state.verifyCompletionsAt(markerName, completions, options); - } - public completions(...optionsArray: VerifyCompletionsOptions[]) { for (const options of optionsArray) { this.state.verifyCompletions(options); @@ -4413,10 +4064,6 @@ namespace FourSlashInterface { this.state.verifyNoDocumentHighlights(startRange); } - public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) { - this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind, tags); - } - /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ @@ -4761,6 +4408,477 @@ namespace FourSlashInterface { return { classificationType, text, textSpan }; } } + export namespace Completion { + const res: string[] = []; + for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) { + res.push(ts.Debug.assertDefined(ts.tokenToString(i))); + } + export const keywordsWithUndefined: ReadonlyArray = res; + export const keywords: ReadonlyArray = keywordsWithUndefined.filter(k => k !== "undefined"); + + export const typeKeywords: ReadonlyArray = + ["false", "null", "true", "void", "any", "boolean", "keyof", "never", "number", "object", "string", "symbol", "undefined", "unique", "unknown"]; + + const globalTypeDecls = [ + "Symbol", + "PropertyKey", + "PropertyDescriptor", + "PropertyDescriptorMap", + "Object", + "ObjectConstructor", + "Function", + "FunctionConstructor", + "CallableFunction", + "NewableFunction", + "IArguments", + "String", + "StringConstructor", + "Boolean", + "BooleanConstructor", + "Number", + "NumberConstructor", + "TemplateStringsArray", + "ImportMeta", + "Math", + "Date", + "DateConstructor", + "RegExpMatchArray", + "RegExpExecArray", + "RegExp", + "RegExpConstructor", + "Error", + "ErrorConstructor", + "EvalError", + "EvalErrorConstructor", + "RangeError", + "RangeErrorConstructor", + "ReferenceError", + "ReferenceErrorConstructor", + "SyntaxError", + "SyntaxErrorConstructor", + "TypeError", + "TypeErrorConstructor", + "URIError", + "URIErrorConstructor", + "JSON", + "ReadonlyArray", + "ConcatArray", + "Array", + "ArrayConstructor", + "TypedPropertyDescriptor", + "ClassDecorator", + "PropertyDecorator", + "MethodDecorator", + "ParameterDecorator", + "PromiseConstructorLike", + "PromiseLike", + "Promise", + "ArrayLike", + "Partial", + "Required", + "Readonly", + "Pick", + "Record", + "Exclude", + "Extract", + "NonNullable", + "Parameters", + "ConstructorParameters", + "ReturnType", + "InstanceType", + "ThisType", + "ArrayBuffer", + "ArrayBufferTypes", + "ArrayBufferLike", + "ArrayBufferConstructor", + "ArrayBufferView", + "DataView", + "DataViewConstructor", + "Int8Array", + "Int8ArrayConstructor", + "Uint8Array", + "Uint8ArrayConstructor", + "Uint8ClampedArray", + "Uint8ClampedArrayConstructor", + "Int16Array", + "Int16ArrayConstructor", + "Uint16Array", + "Uint16ArrayConstructor", + "Int32Array", + "Int32ArrayConstructor", + "Uint32Array", + "Uint32ArrayConstructor", + "Float32Array", + "Float32ArrayConstructor", + "Float64Array", + "Float64ArrayConstructor", + "Intl", + ]; + + export const globalTypes = globalTypesPlus([]); + + export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray { + return [ + ...globalTypeDecls, + ...plus, + ...typeKeywords, + ]; + } + + export const classElementKeywords: ReadonlyArray = + ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"]; + + export const constructorParameterKeywords: ReadonlyArray = + ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntry => ({ name, kind: "keyword" })); + + export const functionMembers: ReadonlyArray = [ + "apply", + "call", + "bind", + "toString", + "length", + { name: "arguments", text: "(property) Function.arguments: any" }, + "caller" + ]; + + export const stringMembers: ReadonlyArray = [ + "toString", + "charAt", + "charCodeAt", + "concat", + "indexOf", + "lastIndexOf", + "localeCompare", + "match", + "replace", + "search", + "slice", + "split", + "substring", + "toLowerCase", + "toLocaleLowerCase", + "toUpperCase", + "toLocaleUpperCase", + "trim", + "length", + "substr", + "valueOf", + ]; + + export const functionMembersWithPrototype: ReadonlyArray = [ + ...functionMembers.slice(0, 4), + "prototype", + ...functionMembers.slice(4), + ]; + + // TODO: Shouldn't propose type keywords in statement position + export const statementKeywordsWithTypes: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "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", + "of", + ]; + + export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => + k === "false" || k === "true" || k === "null" || k === "void" || !ts.contains(typeKeywords, k) && k !== "declare" && k !== "module"); + + export const globalsVars: ReadonlyArray = [ + "eval", + "parseInt", + "parseFloat", + "isNaN", + "isFinite", + "decodeURI", + "decodeURIComponent", + "encodeURI", + "encodeURIComponent", + "escape", + "unescape", + "NaN", + "Infinity", + "Object", + "Function", + "String", + "Boolean", + "Number", + "Math", + "Date", + "RegExp", + "Error", + "EvalError", + "RangeError", + "ReferenceError", + "SyntaxError", + "TypeError", + "URIError", + "JSON", + "Array", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "Intl", + ]; + + // TODO: many of these are inappropriate to always provide + export const globalsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ + "arguments", + ...plus, + ...globalsVars, + "undefined", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "yield", + "async", + ]; + + // TODO: many of these are inappropriate to always provide + export const globalKeywords: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "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", + "of", + ]; + + export const insideMethodKeywords: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "yield", + "async", + ]; + + export const globalKeywordsPlusUndefined: ReadonlyArray = (() => { + const i = globalKeywords.indexOf("unique"); + return [...globalKeywords.slice(0, i), "undefined", ...globalKeywords.slice(i)]; + })(); + + export const globals: ReadonlyArray = [...globalsVars, "undefined", ...globalKeywords]; + + export function globalsPlus(plus: ReadonlyArray): ReadonlyArray { + return [...globalsVars, ...plus, "undefined", ...globalKeywords]; + } + } export interface ReferenceGroup { definition: ReferenceGroupDefinition; @@ -4784,22 +4902,20 @@ namespace FourSlashInterface { readonly hasAction?: boolean, // If not specified, will assert that this is false. readonly isRecommended?: boolean; // If not specified, will assert that this is false. readonly kind?: string, // If not specified, won't assert about this - readonly text: string; - readonly documentation: string; + readonly kindModifiers?: string; + readonly text?: string; + readonly documentation?: string; readonly sourceDisplay?: string; readonly tags?: ReadonlyArray; }; - export interface CompletionsAtOptions extends Partial { - triggerCharacter?: ts.CompletionsTriggerCharacter; - isNewIdentifierLocation?: boolean; - } export interface VerifyCompletionsOptions { readonly marker?: ArrayOrSingle; - readonly isNewIdentifierLocation?: boolean; + readonly isNewIdentifierLocation?: boolean; // Always tested + readonly isGlobalCompletion?: boolean; // Only tested if set readonly exact?: ArrayOrSingle; readonly includes?: ArrayOrSingle; - readonly excludes?: ArrayOrSingle; + readonly excludes?: ArrayOrSingle; readonly preferences?: ts.UserPreferences; readonly triggerCharacter?: ts.CompletionsTriggerCharacter; } diff --git a/tests/cases/fourslash/argumentsAreAvailableAfterEditsAtEndOfFunction.ts b/tests/cases/fourslash/argumentsAreAvailableAfterEditsAtEndOfFunction.ts index 8a1efef397e..de2b99f2165 100644 --- a/tests/cases/fourslash/argumentsAreAvailableAfterEditsAtEndOfFunction.ts +++ b/tests/cases/fourslash/argumentsAreAvailableAfterEditsAtEndOfFunction.ts @@ -12,4 +12,4 @@ goTo.marker(); var text = "this.children = ch"; edit.insert(text); -verify.completionListContains("children", "(parameter) children: string[]"); \ No newline at end of file +verify.completions({ includes: { name: "children", text: "(parameter) children: string[]" }, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/asOperatorCompletion.ts b/tests/cases/fourslash/asOperatorCompletion.ts index 2eaaae7e75d..35ed2c5ebfa 100644 --- a/tests/cases/fourslash/asOperatorCompletion.ts +++ b/tests/cases/fourslash/asOperatorCompletion.ts @@ -4,5 +4,5 @@ //// var x; //// var y = x as /**/ -goTo.marker(); -verify.completionListContains('T'); +verify.completions({ marker: "", includes: "T" }); + diff --git a/tests/cases/fourslash/augmentedTypesClass2.ts b/tests/cases/fourslash/augmentedTypesClass2.ts index 90be770272b..89df22f28db 100644 --- a/tests/cases/fourslash/augmentedTypesClass2.ts +++ b/tests/cases/fourslash/augmentedTypesClass2.ts @@ -6,8 +6,6 @@ ////var r = new c5b(); ////r./*2*/ -goTo.marker('1'); -verify.not.completionListContains('y', 'var y: number'); +verify.completions({ marker: "1", excludes: ["y"] }); edit.backspace(4); -goTo.marker('2'); -verify.completionListContains('foo', '(method) c5b.foo(): void'); \ No newline at end of file +verify.completions({ marker: "2", exact: { name: "foo", text: "(method) c5b.foo(): void" } }); diff --git a/tests/cases/fourslash/augmentedTypesClass3.ts b/tests/cases/fourslash/augmentedTypesClass3.ts index 65e599a5744..ec53a1bee9f 100644 --- a/tests/cases/fourslash/augmentedTypesClass3.ts +++ b/tests/cases/fourslash/augmentedTypesClass3.ts @@ -8,6 +8,4 @@ verify.quickInfos({ 1: "class c5b\nnamespace c5b", 2: "class c5b\nnamespace c5b" }); - -goTo.marker('3'); -verify.completionListContains("c5b", "class c5b\nnamespace c5b"); \ No newline at end of file +verify.completions({ marker: "3", includes: { name: "c5b", text: "class c5b\nnamespace c5b" }}) diff --git a/tests/cases/fourslash/augmentedTypesModule1.ts b/tests/cases/fourslash/augmentedTypesModule1.ts index 6c518c16345..8b9f1e315e8 100644 --- a/tests/cases/fourslash/augmentedTypesModule1.ts +++ b/tests/cases/fourslash/augmentedTypesModule1.ts @@ -7,8 +7,5 @@ ////var x: m1c./*1*/; ////var /*2*/r = m1c; -goTo.marker('1'); -verify.completionListContains('I'); -verify.not.completionListContains('foo'); - +verify.completions({ marker: "1", exact: "I" }); verify.quickInfoAt("2", "var r: number"); diff --git a/tests/cases/fourslash/augmentedTypesModule2.ts b/tests/cases/fourslash/augmentedTypesModule2.ts index 8cab9a42700..a61b6586af1 100644 --- a/tests/cases/fourslash/augmentedTypesModule2.ts +++ b/tests/cases/fourslash/augmentedTypesModule2.ts @@ -7,11 +7,10 @@ verify.quickInfoAt("11", "function m2f(x: number): void\nnamespace m2f"); -goTo.marker('1'); -verify.completionListContains('I'); +verify.completions({ marker: "1", exact: "I" }); edit.insert('I.'); -verify.not.completionListContains('foo'); +verify.completions({ exact: undefined }); edit.backspace(1); verify.quickInfoAt("2", "var r: (x: number) => void"); diff --git a/tests/cases/fourslash/augmentedTypesModule3.ts b/tests/cases/fourslash/augmentedTypesModule3.ts index 9ab9850f993..42d45e8c7c8 100644 --- a/tests/cases/fourslash/augmentedTypesModule3.ts +++ b/tests/cases/fourslash/augmentedTypesModule3.ts @@ -5,11 +5,10 @@ ////var x: m2g./*1*/; ////var /*2*/r = m2g/*3*/; -goTo.marker('1'); -verify.completionListContains('C'); +verify.completions({ marker: "1", exact: "C" }); edit.insert('C.'); -verify.not.completionListContains('foo'); +verify.completions({ exact: undefined }); edit.backspace(1); verify.quickInfoAt("2", "var r: typeof m2g"); diff --git a/tests/cases/fourslash/augmentedTypesModule4.ts b/tests/cases/fourslash/augmentedTypesModule4.ts index 7a7ecb55219..de40dcc3d5b 100644 --- a/tests/cases/fourslash/augmentedTypesModule4.ts +++ b/tests/cases/fourslash/augmentedTypesModule4.ts @@ -1,6 +1,6 @@ /// -////module m3d { export var y = 2; } +////module m3d { export var y = 2; } ////declare class m3d { foo(): void } ////var /*1*/r = new m3d(); ////r./*2*/ @@ -8,12 +8,10 @@ verify.quickInfoAt("1", "var r: m3d"); -goTo.marker('2'); -verify.completionListContains('foo'); +verify.completions({ marker: "2", exact: "foo" }); edit.insert('foo();'); -goTo.marker('3'); -verify.completionListContains('y'); +verify.completions({ marker: "3", includes: "y" }); edit.insert('y;'); verify.quickInfoAt("4", "var r2: number"); diff --git a/tests/cases/fourslash/augmentedTypesModule5.ts b/tests/cases/fourslash/augmentedTypesModule5.ts index 9f38e4d34b8..4203fd2d810 100644 --- a/tests/cases/fourslash/augmentedTypesModule5.ts +++ b/tests/cases/fourslash/augmentedTypesModule5.ts @@ -1,6 +1,6 @@ /// -////declare class m3e { foo(): void } +////declare class m3e { foo(): void } ////module m3e { export var y = 2; } ////var /*1*/r = new m3e(); ////r./*2*/ @@ -8,13 +8,11 @@ verify.quickInfoAt("1", "var r: m3e"); -goTo.marker('2'); -verify.completionListContains('foo'); +verify.completions({ marker: "2", exact: "foo" }); edit.insert('foo();'); -goTo.marker('3'); -verify.completionListContains('y'); +verify.completions({ marker: "3", includes: "y" }); edit.insert('y;'); verify.quickInfoAt("4", "var r2: number"); diff --git a/tests/cases/fourslash/basicClassMembers.ts b/tests/cases/fourslash/basicClassMembers.ts index 9fad6731973..cecef90f4b1 100644 --- a/tests/cases/fourslash/basicClassMembers.ts +++ b/tests/cases/fourslash/basicClassMembers.ts @@ -7,6 +7,4 @@ goTo.eof(); edit.insert('t.'); -verify.completionListContains('x'); -verify.completionListContains('y'); -verify.not.completionListContains('z'); +verify.completions({ includes: ["x", "y"], excludes: "z" }); diff --git a/tests/cases/fourslash/cloduleAsBaseClass.ts b/tests/cases/fourslash/cloduleAsBaseClass.ts index 96b258aed44..15b991f8633 100644 --- a/tests/cases/fourslash/cloduleAsBaseClass.ts +++ b/tests/cases/fourslash/cloduleAsBaseClass.ts @@ -23,23 +23,8 @@ ////d./*1*/ ////D./*2*/ -goTo.marker('1'); -verify.completionListContains('foo'); -verify.completionListContains('foo2'); -verify.not.completionListContains('bar'); -verify.not.completionListContains('bar2'); -verify.not.completionListContains('baz'); -verify.not.completionListContains('x'); - +verify.completions({ marker: "1", exact: ["foo2", "foo"] }); edit.insert('foo()'); - -goTo.marker('2'); -verify.not.completionListContains('foo'); -verify.not.completionListContains('foo2'); -verify.completionListContains('bar'); -verify.completionListContains('bar2'); -verify.completionListContains('baz'); -verify.completionListContains('x'); +verify.completions({ marker: "2", exact: ["prototype", "bar2", "bar", "baz", "x", ...completion.functionMembers] }); edit.insert('bar()'); - -verify.noErrors(); \ No newline at end of file +verify.noErrors(); diff --git a/tests/cases/fourslash/closedCommentsInConstructor.ts b/tests/cases/fourslash/closedCommentsInConstructor.ts index 8a168a58354..ea39826172f 100644 --- a/tests/cases/fourslash/closedCommentsInConstructor.ts +++ b/tests/cases/fourslash/closedCommentsInConstructor.ts @@ -4,5 +4,4 @@ //// constructor(/* /**/ */) { } ////} -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/codeCompletionEscaping.ts b/tests/cases/fourslash/codeCompletionEscaping.ts index 5061a87e5b6..e582171575f 100644 --- a/tests/cases/fourslash/codeCompletionEscaping.ts +++ b/tests/cases/fourslash/codeCompletionEscaping.ts @@ -4,6 +4,10 @@ // @allowJs: true ////___foo; __foo;/**/ -goTo.marker(); -verify.completionListContains("__foo", undefined, undefined, "warning"); -verify.completionListContains("___foo", undefined, undefined, "warning"); +verify.completions({ + marker: "", + includes: [ + { name: "__foo", kind: "warning" }, + { name: "___foo", kind: "warning" }, + ], +}); diff --git a/tests/cases/fourslash/commentsClass.ts b/tests/cases/fourslash/commentsClass.ts index 87e9b9d3a48..12ebed64b53 100644 --- a/tests/cases/fourslash/commentsClass.ts +++ b/tests/cases/fourslash/commentsClass.ts @@ -106,22 +106,26 @@ verify.quickInfos({ 25: ["class c6", "class with statics and constructor"] }); -goTo.marker('26'); -verify.completionListContains("c2", "class c2", "This is class c2 without constructor"); -verify.completionListContains("i2", "var i2: c2", ""); -verify.completionListContains("i2_c", "var i2_c: typeof c2", ""); -verify.completionListContains("c3", "class c3", ""); -verify.completionListContains("i3", "var i3: c3", ""); -verify.completionListContains("i3_c", "var i3_c: typeof c3", ""); -verify.completionListContains("c4", "class c4", "Class comment"); -verify.completionListContains("i4", "var i4: c4", ""); -verify.completionListContains("i4_c", "var i4_c: typeof c4", ""); -verify.completionListContains("c5", "class c5", "Class with statics"); -verify.completionListContains("i5", "var i5: c5", ""); -verify.completionListContains("i5_c", "var i5_c: typeof c5"); -verify.completionListContains("c6", "class c6", "class with statics and constructor"); -verify.completionListContains("i6", "var i6: c6", ""); -verify.completionListContains("i6_c", "var i6_c: typeof c6", ""); +verify.completions({ + marker: "26", + includes: [ + { name: "c2", text: "class c2", documentation: "This is class c2 without constructor" }, + { name: "i2", text: "var i2: c2" }, + { name: "i2_c", text: "var i2_c: typeof c2" }, + { name: "c3", text: "class c3" }, + { name: "i3", text: "var i3: c3" }, + { name: "i3_c", text: "var i3_c: typeof c3" }, + { name: "c4", text: "class c4", documentation: "Class comment" }, + { name: "i4", text: "var i4: c4" }, + { name: "i4_c", text: "var i4_c: typeof c4" }, + { name: "c5", text: "class c5", documentation: "Class with statics" }, + { name: "i5", text: "var i5: c5" }, + { name: "i5_c", text: "var i5_c: typeof c5" }, + { name: "c6", text: "class c6", documentation: "class with statics and constructor" }, + { name: "i6", text: "var i6: c6" }, + { name: "i6_c", text: "var i6_c: typeof c6" }, + ], +}); verify.signatureHelp({ marker: "27", diff --git a/tests/cases/fourslash/commentsClassMembers.ts b/tests/cases/fourslash/commentsClassMembers.ts index b0ed3e9e48b..4457dc617cd 100644 --- a/tests/cases/fourslash/commentsClassMembers.ts +++ b/tests/cases/fourslash/commentsClassMembers.ts @@ -132,342 +132,163 @@ //// } ////} +const publicProperties: ReadonlyArray = [ + { name: "p1", text: "(property) c1.p1: number", documentation: "p1 is property of c1" }, + { name: "p2", text: "(method) c1.p2(b: number): number", documentation: "sum with property" }, + { name: "p3", text: "(property) c1.p3: number", documentation: "getter property 1\nsetter property 1" }, +]; +const publicNcProperties: ReadonlyArray = [ + { name: "nc_p1", text: "(property) c1.nc_p1: number" }, + { name: "nc_p2", text: "(method) c1.nc_p2(b: number): number" }, + { name: "nc_p3", text: "(property) c1.nc_p3: number" }, +]; +const locals: ReadonlyArray = [ + { name: "c1", text: "class c1", documentation: "This is comment for c1" }, + { name: "i1", text: "var i1: c1" }, + { name: "i1_p", text: "var i1_p: number" }, + { name: "i1_f", text: "var i1_f: (b: number) => number" }, + { name: "i1_r", text: "var i1_r: number" }, + { name: "i1_prop", text: "var i1_prop: number" }, + { name: "i1_nc_p", text: "var i1_nc_p: number" }, + { name: "i1_ncf", text: "var i1_ncf: (b: number) => number" }, + { name: "i1_ncr", text: "var i1_ncr: number" }, + { name: "i1_ncprop", text: "var i1_ncprop: number" }, + { name: "i1_s_p", text: "var i1_s_p: number" }, + { name: "i1_s_f", text: "var i1_s_f: (b: number) => number" }, + { name: "i1_s_r", text: "var i1_s_r: number" }, + { name: "i1_s_prop", text: "var i1_s_prop: number" }, + { name: "i1_s_nc_p", text: "var i1_s_nc_p: number" }, + { name: "i1_s_ncf", text: "var i1_s_ncf: (b: number) => number" }, + { name: "i1_s_ncr", text: "var i1_s_ncr: number" }, + { name: "i1_s_ncprop", text: "var i1_s_ncprop: number" }, + { name: "i1_c", text: "var i1_c: typeof c1" }, +]; + +verify.completions( + { + marker: ["4", "7", "9", "11", "12", "16", "19", "21", "23", "24"], + exact: [ + ...publicProperties, + { name: "pp1", text: "(property) c1.pp1: number", documentation: "pp1 is property of c1" }, + { name: "pp2", text: "(method) c1.pp2(b: number): number", documentation: "sum with property" }, + { name: "pp3", text: "(property) c1.pp3: number", documentation: "getter property 2\nsetter property 2" }, + ...publicNcProperties, + { name: "nc_pp1", text: "(property) c1.nc_pp1: number" }, + { name: "nc_pp2", text: "(method) c1.nc_pp2(b: number): number" }, + { name: "nc_pp3", text: "(property) c1.nc_pp3: number" }, + ], + }, + { + marker: ["5", "17"], + includes: { name: "b", text: "(parameter) b: number", documentation: "number to add" }, + }, + { + marker: ["13", "25"], + includes: [{ name: "value", text: "(parameter) value: number", documentation: "this is value" }], + isNewIdentifierLocation: true, + }, + { + marker: ["30", "34", "36", "39", "41", "88"], + exact: [ + "prototype", + { name: "s1", text: "(property) c1.s1: number", documentation: "s1 is static property of c1" }, + { name: "s2", text: "(method) c1.s2(b: number): number", documentation: "static sum with property" }, + { name: "s3", text: "(property) c1.s3: number", documentation: "static getter property\nsetter property 3" }, + { name: "nc_s1", text: "(property) c1.nc_s1: number" }, + { name: "nc_s2", text: "(method) c1.nc_s2(b: number): number" }, + { name: "nc_s3", text: "(property) c1.nc_s3: number" }, + ...completion.functionMembers, + ], + }, + { marker: ["29", "33", "38", "109"], includes: locals }, + { marker: ["35", "40", "87"], includes: locals, isNewIdentifierLocation: true }, + { marker: "31", includes: { name: "b", text: "(parameter) b: number", documentation: "number to add" } }, + { marker: "42", includes: { name: "value", text: "(parameter) value: number", documentation: "this is value" }, isNewIdentifierLocation: true }, + { marker: ["45", "52", "59"], includes: { name: "b", text: "(parameter) b: number" } }, + { marker: ["49", "56", "63"], includes: { name: "value", text: "(parameter) value: number" }, isNewIdentifierLocation: true }, + { marker: "67", exact: [...publicProperties, ...publicNcProperties] }, + { + marker: "110", + includes: [ + { name: "p1", text: "(property) cProperties.p1: number", documentation: "getter only property" }, + { name: "p2", text: "(property) cProperties.p2: number", documentation: "setter only property" }, + { name: "nc_p1", text: "(property) cProperties.nc_p1: number" }, + { name: "nc_p2", text: "(property) cProperties.nc_p2: number" }, + ], + }, + { + marker: "114", + includes: { + name: "a", + text: "(property) cWithConstructorProperty.a: number", + documentation: "more info about a\nthis is first parameter a", + tags: [{ name: "param", text: "a this is first parameter a" }], + }, + }, + { + marker: "115", + includes: { + name: "a", + text: "(parameter) a: number", + documentation: "more info about a\nthis is first parameter a", + tags: [{ name: "param", text: "a this is first parameter a" }], + }, + isNewIdentifierLocation: true, + }, +); + +verify.signatureHelp( + { marker: ["8", "13", "20", "25", "71"], docComment: "sum with property", parameterDocComment: "number to add" }, + { marker: ["35", "42", "92"], docComment: "static sum with property", parameterDocComment: "number to add" }, + { marker: ["47", "49", "54", "56", "61", "63", "81", "102"], docComment: "" }, + { marker: "65", docComment: "Constructor method" }, +); + verify.quickInfos({ 1: ["class c1", "This is comment for c1"], 2: ["(property) c1.p1: number", "p1 is property of c1"], - 3: ["(method) c1.p2(b: number): number", "sum with property"] -}); - -goTo.marker('4'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -goTo.marker('5'); -verify.completionListContains("b", "(parameter) b: number", "number to add"); - -verify.quickInfoAt("6", "(property) c1.p3: number", "getter property 1\nsetter property 1"); - -goTo.marker('7'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.signatureHelp({ marker: "8", docComment: "sum with property", parameterDocComment: "number to add" }); -verify.quickInfoAt("8q", "(method) c1.p2(b: number): number", "sum with property"); - -goTo.marker('9'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.quickInfoAt("10", "(property) c1.p3: number", "getter property 1\nsetter property 1"); - -goTo.marker('11'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -goTo.marker('12'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.signatureHelp({ marker: "13", docComment: "sum with property", parameterDocComment: "number to add" }); -verify.completionListContains("value", "(parameter) value: number", "this is value"); - -verify.quickInfos({ + 3: ["(method) c1.p2(b: number): number", "sum with property"], + 6: ["(property) c1.p3: number", "getter property 1\nsetter property 1"], + "8q": ["(method) c1.p2(b: number): number", "sum with property"], + 10: ["(property) c1.p3: number", "getter property 1\nsetter property 1"], "13q": ["(method) c1.p2(b: number): number", "sum with property"], 14: ["(property) c1.pp1: number", "pp1 is property of c1"], - 15: ["(method) c1.pp2(b: number): number", "sum with property"] -}); - -goTo.marker('16'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -goTo.marker('17'); -verify.completionListContains("b", "(parameter) b: number", "number to add"); - -verify.quickInfoAt("18", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); - -goTo.marker('19'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.signatureHelp({ marker: "20", docComment: "sum with property", parameterDocComment: "number to add" }); -verify.quickInfoAt("20q", "(method) c1.pp2(b: number): number", "sum with property"); - -goTo.marker('21'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.quickInfoAt("22", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); - -goTo.marker('23'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -goTo.marker('24'); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("pp1", "(property) c1.pp1: number", "pp1 is property of c1"); -verify.completionListContains("pp2", "(method) c1.pp2(b: number): number", "sum with property"); -verify.completionListContains("pp3", "(property) c1.pp3: number", "getter property 2\nsetter property 2"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); -verify.completionListContains("nc_pp1", "(property) c1.nc_pp1: number", ""); -verify.completionListContains("nc_pp2", "(method) c1.nc_pp2(b: number): number", ""); -verify.completionListContains("nc_pp3", "(property) c1.nc_pp3: number", ""); - -verify.signatureHelp({ marker: "25", docComment: "sum with property", parameterDocComment: "number to add" }); -verify.completionListContains("value", "(parameter) value: number", "this is value"); - -verify.quickInfos({ + 15: ["(method) c1.pp2(b: number): number", "sum with property"], + 18: ["(property) c1.pp3: number", "getter property 2\nsetter property 2"], + "20q": ["(method) c1.pp2(b: number): number", "sum with property"], + 22: ["(property) c1.pp3: number", "getter property 2\nsetter property 2"], "25q": ["(method) c1.pp2(b: number): number", "sum with property"], 26: ["constructor c1(): c1", "Constructor method"], 27: ["(property) c1.s1: number", "s1 is static property of c1"], - 28: ["(method) c1.s2(b: number): number", "static sum with property"] -}); - -goTo.marker('29'); -verify.completionListContains("c1", "class c1", "This is comment for c1"); - -goTo.marker('30'); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -goTo.marker('31'); -verify.completionListContains("b", "(parameter) b: number", "number to add"); - -verify.quickInfoAt("32", "(property) c1.s3: number", "static getter property\nsetter property 3"); - -goTo.marker('33'); -verify.completionListContains("c1", "class c1", "This is comment for c1"); - -goTo.marker('34'); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -verify.signatureHelp({ marker: "35", docComment: "static sum with property", parameterDocComment: "number to add" }); -verify.completionListContains("c1", "class c1", "This is comment for c1"); -verify.quickInfoAt("35q", "(method) c1.s2(b: number): number", "static sum with property"); - -goTo.marker('36'); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -verify.quickInfoAt("37", "(property) c1.s3: number", "static getter property\nsetter property 3"); - -goTo.marker('38'); -verify.completionListContains("c1", "class c1", "This is comment for c1"); - -goTo.marker('39'); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -goTo.marker('40'); -verify.completionListContains("c1", "class c1", "This is comment for c1"); - -goTo.marker('41'); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -verify.signatureHelp({ marker: "42", docComment: "static sum with property", parameterDocComment: "number to add" }); -verify.completionListContains("value", "(parameter) value: number", "this is value"); -verify.quickInfos({ + 28: ["(method) c1.s2(b: number): number", "static sum with property"], + 32: ["(property) c1.s3: number", "static getter property\nsetter property 3"], + "35q": ["(method) c1.s2(b: number): number", "static sum with property"], + 37: ["(property) c1.s3: number", "static getter property\nsetter property 3"], "42q": ["(method) c1.s2(b: number): number", "static sum with property"], 43: "(property) c1.nc_p1: number", - 44: "(method) c1.nc_p2(b: number): number" -}); - -goTo.marker('45'); -verify.completionListContains("b", "(parameter) b: number", ""); - -verify.quickInfoAt("46", "(property) c1.nc_p3: number"); - -verify.signatureHelp({ marker: "47", docComment: "" }); -verify.quickInfos({ + 44: "(method) c1.nc_p2(b: number): number", + 46: "(property) c1.nc_p3: number", "47q": "(method) c1.nc_p2(b: number): number", - 48: "(property) c1.nc_p3: number" -}); - -verify.signatureHelp({ marker: "49", docComment: "" }); -verify.completionListContains("value", "(parameter) value: number", ""); -verify.quickInfos({ + 48: "(property) c1.nc_p3: number", "49q": "(method) c1.nc_p2(b: number): number", 50: "(property) c1.nc_pp1: number", - 51: "(method) c1.nc_pp2(b: number): number" -}); - -goTo.marker('52'); -verify.completionListContains("b", "(parameter) b: number", ""); - -verify.quickInfoAt("53", "(property) c1.nc_pp3: number"); - -verify.signatureHelp({ marker: "54", docComment: "" }); -verify.quickInfos({ + 51: "(method) c1.nc_pp2(b: number): number", + 53: "(property) c1.nc_pp3: number", "54q": "(method) c1.nc_pp2(b: number): number", - 55: "(property) c1.nc_pp3: number" -}); - -verify.signatureHelp({ marker: "56", docComment: "" }); -verify.completionListContains("value", "(parameter) value: number", ""); -verify.quickInfos({ + 55: "(property) c1.nc_pp3: number", "56q": "(method) c1.nc_pp2(b: number): number", 57: "(property) c1.nc_s1: number", - 58: "(method) c1.nc_s2(b: number): number" -}); - -goTo.marker('59'); -verify.completionListContains("b", "(parameter) b: number", ""); - -verify.quickInfoAt("60", "(property) c1.nc_s3: number"); - -verify.signatureHelp({ marker: "61", docComment: "" }); -verify.quickInfos({ + 58: "(method) c1.nc_s2(b: number): number", + 60: "(property) c1.nc_s3: number", "61q": "(method) c1.nc_s2(b: number): number", - 62: "(property) c1.nc_s3: number" -}); - -verify.signatureHelp({ marker: "63", docComment: "" }); -verify.completionListContains("value", "(parameter) value: number", ""); -verify.quickInfos({ + 62: "(property) c1.nc_s3: number", "63q": "(method) c1.nc_s2(b: number): number", - 64: "var i1: c1" -}); - -verify.signatureHelp({ marker: "65", docComment: "Constructor method" }); -verify.quickInfos({ + 64: "var i1: c1", "65q": ["constructor c1(): c1", "Constructor method"], - 66: "var i1_p: number" -}); - -goTo.marker("67"); -verify.quickInfoIs("(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p1", "(property) c1.p1: number", "p1 is property of c1"); -verify.completionListContains("p2", "(method) c1.p2(b: number): number", "sum with property"); -verify.completionListContains("p3", "(property) c1.p3: number", "getter property 1\nsetter property 1"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(method) c1.nc_p2(b: number): number", ""); -verify.completionListContains("nc_p3", "(property) c1.nc_p3: number", ""); - -verify.quickInfos({ + 66: "var i1_p: number", 68: "var i1_f: (b: number) => number", 69: ["(method) c1.p2(b: number): number", "sum with property"], - 70: "var i1_r: number" -}); - -verify.signatureHelp({ marker: "71", docComment: "sum with property", parameterDocComment: "number to add" }); - -verify.quickInfos({ + 70: "var i1_r: number", "71q": ["(method) c1.p2(b: number): number", "sum with property"], 72: "var i1_prop: number", 73: ["(property) c1.p3: number", "getter property 1\nsetter property 1"], @@ -477,42 +298,17 @@ verify.quickInfos({ 77: "(property) c1.nc_p1: number", 78: "var i1_ncf: (b: number) => number", 79: "(method) c1.nc_p2(b: number): number", - 80: "var i1_ncr: number" -}); - -verify.signatureHelp({ marker: "81", docComment: "" }); - -verify.quickInfos({ + 80: "var i1_ncr: number", "81q": "(method) c1.nc_p2(b: number): number", 82: "var i1_ncprop: number", 83: "(property) c1.nc_p3: number", 84: "(property) c1.nc_p3: number", 85: "var i1_ncprop: number", - 86: "var i1_s_p: number" -}); - -goTo.marker('87'); -verify.quickInfoIs("class c1", "This is comment for c1"); -verify.completionListContains("c1", "class c1", "This is comment for c1"); - -goTo.marker('88'); -verify.quickInfoIs("(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s1", "(property) c1.s1: number", "s1 is static property of c1"); -verify.completionListContains("s2", "(method) c1.s2(b: number): number", "static sum with property"); -verify.completionListContains("s3", "(property) c1.s3: number", "static getter property\nsetter property 3"); -verify.completionListContains("nc_s1", "(property) c1.nc_s1: number", ""); -verify.completionListContains("nc_s2", "(method) c1.nc_s2(b: number): number", ""); -verify.completionListContains("nc_s3", "(property) c1.nc_s3: number", ""); - -verify.quickInfos({ + 86: "var i1_s_p: number", + 87: ["class c1", "This is comment for c1"], 89: "var i1_s_f: (b: number) => number", 90: ["(method) c1.s2(b: number): number", "static sum with property"], - 91: "var i1_s_r: number" -}); - -verify.signatureHelp({ marker: "92", docComment: "static sum with property", parameterDocComment: "number to add" }); - -verify.quickInfos({ + 91: "var i1_s_r: number", "92q": ["(method) c1.s2(b: number): number", "static sum with property"], 93: "var i1_s_prop: number", 94: ["(property) c1.s3: number", "static getter property\nsetter property 3"], @@ -522,69 +318,25 @@ verify.quickInfos({ 98: "(property) c1.nc_s1: number", 99: "var i1_s_ncf: (b: number) => number", 100: "(method) c1.nc_s2(b: number): number", - 101: "var i1_s_ncr: number" -}); - -verify.signatureHelp({ marker: "102", docComment: "" }); -verify.quickInfos({ + 101: "var i1_s_ncr: number", "102q": "(method) c1.nc_s2(b: number): number", 103: "var i1_s_ncprop: number", 104: "(property) c1.nc_s3: number", 105: "(property) c1.nc_s3: number", 106: "var i1_s_ncprop: number", 107: "var i1_c: typeof c1", - 108: ["class c1", "This is comment for c1"] -}); - -goTo.marker('109'); -verify.completionListContains("c1", "class c1", "This is comment for c1"); -verify.completionListContains("i1", "var i1: c1", ""); -verify.completionListContains("i1_p", "var i1_p: number", ""); -verify.completionListContains("i1_f", "var i1_f: (b: number) => number", ""); -verify.completionListContains("i1_r", "var i1_r: number", ""); -verify.completionListContains("i1_prop", "var i1_prop: number", ""); -verify.completionListContains("i1_nc_p", "var i1_nc_p: number", ""); -verify.completionListContains("i1_ncf", "var i1_ncf: (b: number) => number", ""); -verify.completionListContains("i1_ncr", "var i1_ncr: number", ""); -verify.completionListContains("i1_ncprop", "var i1_ncprop: number", ""); -verify.completionListContains("i1_s_p", "var i1_s_p: number", ""); -verify.completionListContains("i1_s_f", "var i1_s_f: (b: number) => number", ""); -verify.completionListContains("i1_s_r", "var i1_s_r: number", ""); -verify.completionListContains("i1_s_prop", "var i1_s_prop: number", ""); -verify.completionListContains("i1_s_nc_p", "var i1_s_nc_p: number", ""); -verify.completionListContains("i1_s_ncf", "var i1_s_ncf: (b: number) => number", ""); -verify.completionListContains("i1_s_ncr", "var i1_s_ncr: number", ""); -verify.completionListContains("i1_s_ncprop", "var i1_s_ncprop: number", ""); - -verify.completionListContains("i1_c", "var i1_c: typeof c1", ""); - -goTo.marker('110'); -verify.quickInfoIs("(property) cProperties.p2: number", "setter only property"); -verify.completionListContains("p1", "(property) cProperties.p1: number", "getter only property"); -verify.completionListContains("p2", "(property) cProperties.p2: number", "setter only property"); -verify.completionListContains("nc_p1", "(property) cProperties.nc_p1: number", ""); -verify.completionListContains("nc_p2", "(property) cProperties.nc_p2: number", ""); - -verify.quickInfos({ + 108: ["class c1", "This is comment for c1"], + 110: ["(property) cProperties.p2: number", "setter only property"], 111: ["(property) cProperties.p1: number", "getter only property"], 112: "(property) cProperties.nc_p2: number", - 113: "(property) cProperties.nc_p1: number" -}); - -goTo.marker('114'); -verify.completionListContains("a", "(property) cWithConstructorProperty.a: number", "more info about a\nthis is first parameter a"); -verify.quickInfoIs("(property) cWithConstructorProperty.a: number", "more info about a\nthis is first parameter a"); - -goTo.marker('115'); -verify.completionListContains("a", "(parameter) a: number", "more info about a\nthis is first parameter a"); -verify.quickInfoIs("(parameter) a: number", "more info about a\nthis is first parameter a"); - -verify.quickInfos({ + 113: "(property) cProperties.nc_p1: number", + 114: ["(property) cWithConstructorProperty.a: number", "more info about a\nthis is first parameter a"], + 115: ["(parameter) a: number", "more info about a\nthis is first parameter a"], 116: "this: this", 117: "(local var) bbbb: number", 118: "(local var) bbbb: number", 119: [ "constructor cWithConstructorProperty(a: number): cWithConstructorProperty", "this is class cWithConstructorProperty's constructor" - ] + ], }); diff --git a/tests/cases/fourslash/commentsCommentParsing.ts b/tests/cases/fourslash/commentsCommentParsing.ts index 8f7d35ce0f9..fe3d44d3e6a 100644 --- a/tests/cases/fourslash/commentsCommentParsing.ts +++ b/tests/cases/fourslash/commentsCommentParsing.ts @@ -280,10 +280,13 @@ verify.signatureHelp({ }); verify.quickInfoAt("17aq", "(parameter) b: number", "second number"); -goTo.marker('18'); -verify.quickInfoIs("(parameter) a: number", "first number"); -verify.completionListContains("a", "(parameter) a: number", "first number"); -verify.completionListContains("b", "(parameter) b: number", "second number"); +verify.completions({ + marker: "18", + includes: [ + { name: "a", text: "(parameter) a: number", documentation: "first number", tags: [{ name: "param", text: "a first number" }] }, + { name: "b", text: "(parameter) b: number", documentation: "second number", tags: [{ name: "param", text: "b second number" }] }, + ], +}); const multiplyTags: ReadonlyArray = [ { name: "param", text: "" }, @@ -316,9 +319,18 @@ verify.quickInfoAt("22aq", "(parameter) d: any"); verify.signatureHelp({ marker: "23", docComment: "This is multiplication function", parameterDocComment: "LastParam", tags: multiplyTags }); verify.quickInfoAt("23aq", "(parameter) e: any", "LastParam"); -goTo.marker('24'); -verify.completionListContains("aOrb", "(parameter) aOrb: any", ""); -verify.completionListContains("opt", "(parameter) opt: any", "optional parameter"); +verify.completions({ + marker: "24", + includes: [ + { name: "aOrb", text: "(parameter) aOrb: any" }, + { + name: "opt", + text: "(parameter) opt: any", + documentation: "optional parameter", + tags: [{ name: "param", text: "opt optional parameter" }], + }, + ] +}); verify.signatureHelp({ marker: "25", @@ -337,9 +349,32 @@ verify.quickInfos({ "26aq": "(parameter) b: string" }); -goTo.marker('27'); -verify.completionListContains("multiply", "function multiply(a: number, b: number, c?: number, d?: any, e?: any): void", "This is multiplication function"); -verify.completionListContains("f1", "function f1(a: number): any (+1 overload)", "fn f1 with number"); +verify.completions({ + marker: "27", + includes: [ + { + name: "multiply", + text: "function multiply(a: number, b: number, c?: number, d?: any, e?: any): void", + documentation: "This is multiplication function", + tags: [ + { name: "param", text: "" }, + { name: "param", text: "a first number" }, + { name: "param", text: "b" }, + { name: "param", text: "c" }, + { name: "param", text: "d" }, + { name: "anotherTag", text: undefined }, + { name: "param", text: "e LastParam" }, + { name: "anotherTag", text: undefined }, + ], + }, + { + name: "f1", + text: "function f1(a: number): any (+1 overload)", + documentation: "fn f1 with number", + tags: [{ name: "param", text: "b about b" }], + }, + ], +}); const subtractDoc = "This is subtract function"; const subtractTags: ReadonlyArray = [ @@ -429,11 +464,25 @@ verify.quickInfos({ verify.signatureHelp({ marker: "38", docComment: concatDoc, parameterDocComment: "is second string", tags: concatTags }); verify.quickInfoAt("38aq", "(parameter) bar: string", "is second string"); -goTo.marker('39'); -verify.completionListContains("a", "(parameter) a: number", "this is inline comment for a\nit is first parameter"); -verify.completionListContains("b", "(parameter) b: number", "this is inline comment for b"); -verify.completionListContains("c", "(parameter) c: number", "it is third parameter"); -verify.completionListContains("d", "(parameter) d: number", ""); +verify.completions({ + marker: "39", + includes: [ + { + name: "a", + text: "(parameter) a: number", + documentation: "this is inline comment for a\nit is first parameter", + tags: [{ name: "param", text: "a it is first parameter" }], + }, + { name: "b", text: "(parameter) b: number", documentation: "this is inline comment for b" }, + { + name: "c", + text: "(parameter) c: number", + documentation: "it is third parameter", + tags: [{ name: "param", text: "c it is third parameter" }], + }, + { name: "d", text: "(parameter) d: number" }, + ], +}); const jsdocTestDocComment = "this is jsdoc style function with param tag as well as inline parameter help"; const jsdocTestTags: ReadonlyArray = [ @@ -461,10 +510,22 @@ verify.quickInfoAt("42aq", "(parameter) c: number", "it is third parameter"); verify.signatureHelp({ marker: "43", docComment: jsdocTestDocComment, tags: jsdocTestTags }); verify.quickInfoAt("43aq", "(parameter) d: number"); -goTo.marker('44'); -verify.completionListContains("jsDocParamTest", "function jsDocParamTest(a: number, b: number, c: number, d: number): number", jsdocTestDocComment); -verify.completionListContains("x", "var x: any", "This is a comment"); -verify.completionListContains("y", "var y: any", "This is a comment"); +verify.completions({ + marker: "44", + includes: [ + { + name: "jsDocParamTest", + text: "function jsDocParamTest(a: number, b: number, c: number, d: number): number", + documentation: jsdocTestDocComment, + tags: [ + { name: "param", text: "a it is first parameter" }, + { name: "param", text: "c it is third parameter" }, + ], + }, + { name: "x", text: "var x: any", documentation: "This is a comment" }, + { name: "y", text: "var y: any", documentation: "This is a comment" }, + ], +}); verify.signatureHelp({ marker: "45", docComment: "This is function comment\nAnd properly aligned comment" }); verify.quickInfoAt("45q", "function jsDocCommentAlignmentTest1(): void", "This is function comment\nAnd properly aligned comment"); diff --git a/tests/cases/fourslash/commentsEnums.ts b/tests/cases/fourslash/commentsEnums.ts index 9fb29d4442b..54a5af1e837 100644 --- a/tests/cases/fourslash/commentsEnums.ts +++ b/tests/cases/fourslash/commentsEnums.ts @@ -14,22 +14,23 @@ verify.quickInfos({ 1: ["enum Colors", "Enum of colors"], 2: ["(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"], 3: ["(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"], - 4: "var x: Colors" + 4: "var x: Colors", + 5: ["enum Colors", "Enum of colors"], + 6: ["(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"], + 7: ["(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"], }); -verify.completions({ - marker: "5", - includes: { name: "Colors", text: "enum Colors", documentation: "Enum of colors" }, - isNewIdentifierLocation: true, -}); -verify.quickInfoIs("enum Colors", "Enum of colors"); - -const completions = [ - { name: "Cornflower", text: "(enum member) Colors.Cornflower = 0", documentation: "Fancy name for 'blue'" }, - { name: "FancyPink", text: "(enum member) Colors.FancyPink = 1", documentation: "Fancy name for 'pink'" }, -]; -verify.completions({ marker: "6", includes: completions }); -verify.quickInfoIs("(enum member) Colors.Cornflower = 0", "Fancy name for 'blue'"); - -verify.completions({ marker: "7", includes: completions }); -verify.quickInfoIs("(enum member) Colors.FancyPink = 1", "Fancy name for 'pink'"); \ No newline at end of file +verify.completions( + { + marker: "5", + includes: { name: "Colors", text: "enum Colors", documentation: "Enum of colors" }, + isNewIdentifierLocation: true, + }, + { + marker: ["6", "7"], + exact: [ + { name: "Cornflower", text: "(enum member) Colors.Cornflower = 0", documentation: "Fancy name for 'blue'" }, + { name: "FancyPink", text: "(enum member) Colors.FancyPink = 1", documentation: "Fancy name for 'pink'" }, + ] + }, +); diff --git a/tests/cases/fourslash/commentsExternalModules.ts b/tests/cases/fourslash/commentsExternalModules.ts index c1c12d8a3ce..25dc25b0331 100644 --- a/tests/cases/fourslash/commentsExternalModules.ts +++ b/tests/cases/fourslash/commentsExternalModules.ts @@ -34,49 +34,75 @@ goTo.file("commentsExternalModules_file0.ts"); verify.quickInfoAt("1", "namespace m1", "Namespace comment"); -goTo.marker('2'); -verify.completionListContains("b", "var b: number", "b's comment"); -verify.completionListContains("foo", "function foo(): number", "foo's comment"); +verify.completions({ + marker: "2", + includes: [ + { name: "b", text: "var b: number", documentation: "b's comment" }, + { name: "foo", text: "function foo(): number", documentation: "foo's comment" }, + ] +}); verify.signatureHelp({ marker: "3", docComment: "foo's comment" }); verify.quickInfoAt("3q", "function foo(): number", "foo's comment"); -goTo.marker('4'); -verify.completionListContains("m1", "namespace m1", "Namespace comment"); +verify.completions({ + marker: "4", + includes: { name: "m1", text: "namespace m1", documentation: "Namespace comment" }, +}); -goTo.marker('5'); -verify.completionListContains("b", "var m1.b: number", "b's comment"); -verify.completionListContains("fooExport", "function m1.fooExport(): number", "exported function"); -verify.completionListContains("m2", "namespace m1.m2"); +verify.completions({ + marker: "5", + includes: [ + { name: "b", text: "var m1.b: number", documentation: "b's comment" }, + { name: "fooExport", text: "function m1.fooExport(): number", documentation: "exported function" }, + { name: "m2", text: "namespace m1.m2", documentation: "m2 comments" }, + ], +}); verify.signatureHelp({ marker: "6", docComment: "exported function" }); verify.quickInfoAt("6q", "function m1.fooExport(): number", "exported function"); verify.quickInfoAt("7", "var myvar: m1.m2.c"); -goTo.marker('8'); -verify.completionListContains("c", "constructor m1.m2.c(): m1.m2.c", "class comment;"); -verify.completionListContains("i", "var m1.m2.i: m1.m2.c", "i"); +verify.completions({ + marker: "8", + includes: [ + { name: "c", text: "constructor m1.m2.c(): m1.m2.c", documentation: "class comment;" }, + { name: "i", text: "var m1.m2.i: m1.m2.c", documentation: "i" }, + ], +}); goTo.file("commentsExternalModules_file1.ts"); verify.quickInfoAt("9", 'import extMod = require("./commentsExternalModules_file0")', "This is on import declaration"); -goTo.marker('10'); -verify.completionListContains("extMod", 'import extMod = require("./commentsExternalModules_file0")', "This is on import declaration"); - -goTo.marker('11'); -verify.completionListContains("m1", "namespace extMod.m1"); - -goTo.marker('12'); -verify.completionListContains("b", "var extMod.m1.b: number", "b's comment"); -verify.completionListContains("fooExport", "function extMod.m1.fooExport(): number", "exported function"); -verify.completionListContains("m2", "namespace extMod.m1.m2"); +verify.completions( + { + marker: "10", + includes: { name: "extMod", text: 'import extMod = require("./commentsExternalModules_file0")', documentation: "This is on import declaration" }, + }, + { + marker: "11", + includes: { name: "m1", text: "namespace extMod.m1", documentation: "Namespace comment" }, + }, + { + marker: "12", + includes: [ + { name: "b", text: "var extMod.m1.b: number", documentation: "b's comment" }, + { name: "fooExport", text: "function extMod.m1.fooExport(): number", documentation: "exported function" }, + { name: "m2", text: "namespace extMod.m1.m2", documentation: "m2 comments" }, + ], + }, +); verify.signatureHelp({ marker: "13", docComment: "exported function" }); verify.quickInfoAt("13q", "function extMod.m1.fooExport(): number", "exported function"); verify.quickInfoAt("14", "var newVar: extMod.m1.m2.c"); -goTo.marker('15'); -verify.completionListContains("c", "constructor extMod.m1.m2.c(): extMod.m1.m2.c", "class comment;"); -verify.completionListContains("i", "var extMod.m1.m2.i: extMod.m1.m2.c", "i"); +verify.completions({ + marker: "15", + exact: [ + { name: "c", text: "constructor extMod.m1.m2.c(): extMod.m1.m2.c", documentation: "class comment;" }, + { name: "i", text: "var extMod.m1.m2.i: extMod.m1.m2.c", documentation: "i" }, + ], +}); diff --git a/tests/cases/fourslash/commentsFunctionDeclaration.ts b/tests/cases/fourslash/commentsFunctionDeclaration.ts index 7ecb46fb042..609621f6336 100644 --- a/tests/cases/fourslash/commentsFunctionDeclaration.ts +++ b/tests/cases/fourslash/commentsFunctionDeclaration.ts @@ -24,8 +24,7 @@ verify.quickInfoAt("1", "function foo(): void", "This comment should appear for verify.quickInfoAt("2", "function foo(): void", "This comment should appear for foo"); -goTo.marker('3'); -verify.completionListContains('foo', 'function foo(): void', 'This comment should appear for foo'); +verify.completions({ marker: "3", includes: { name: "foo", text: "function foo(): void", documentation: "This comment should appear for foo" }}) verify.signatureHelp({ marker: "4", docComment: "This comment should appear for foo" }); @@ -33,14 +32,22 @@ verify.quickInfoAt("5", "function fooWithParameters(a: string, b: number): void" verify.quickInfoAt("6", "(local var) d: string"); -goTo.marker('7'); -verify.completionListContains('a', '(parameter) a: string', 'this is comment about a'); -verify.completionListContains('b', '(parameter) b: number', 'this is comment for b'); +verify.completions({ + marker: "7", + includes: [ + { name: "a", text: "(parameter) a: string", documentation: "this is comment about a" }, + { name: "b", text: "(parameter) b: number", documentation: "this is comment for b" }, + ], + isNewIdentifierLocation: true, +}); verify.quickInfoAt("8", "function fooWithParameters(a: string, b: number): void", "This is comment for function signature"); goTo.marker('9'); -verify.completionListContains('fooWithParameters', 'function fooWithParameters(a: string, b: number): void', 'This is comment for function signature'); +verify.completions({ + marker: "9", + includes: { name: "fooWithParameters", text: "function fooWithParameters(a: string, b: number): void", documentation: "This is comment for function signature" } +}) verify.signatureHelp( { marker: "10", docComment: "This is comment for function signature", parameterDocComment: "this is comment about a" }, diff --git a/tests/cases/fourslash/commentsFunctionExpression.ts b/tests/cases/fourslash/commentsFunctionExpression.ts index f62572a4666..01bbf40045c 100644 --- a/tests/cases/fourslash/commentsFunctionExpression.ts +++ b/tests/cases/fourslash/commentsFunctionExpression.ts @@ -34,16 +34,24 @@ verify.quickInfoAt("1", "var lambdaFoo: (a: number, b: number) => number", "this is lambda comment\nlambdaFoo var comment"); -goTo.marker('2'); -verify.completionListContains('a', '(parameter) a: number', 'param a'); -verify.completionListContains('b', '(parameter) b: number', 'param b'); +verify.completions({ + marker: "2", + includes: [ + { name: "a", text: "(parameter) a: number", documentation: "param a" }, + { name: "b", text: "(parameter) b: number", documentation: "param b" }, + ], +}); // pick up doccomments from the lambda itself verify.quickInfoAt("3", "var lambddaNoVarComment: (a: number, b: number) => number", "this is lambda multiplication"); -goTo.marker('4'); -verify.completionListContains('lambdaFoo', 'var lambdaFoo: (a: number, b: number) => number', "this is lambda comment\nlambdaFoo var comment"); -verify.completionListContains('lambddaNoVarComment', 'var lambddaNoVarComment: (a: number, b: number) => number', 'this is lambda multiplication'); +verify.completions({ + marker: "4", + includes: [ + { name: "lambdaFoo", text: "var lambdaFoo: (a: number, b: number) => number", documentation: "this is lambda comment\nlambdaFoo var comment" }, + { name: "lambddaNoVarComment", text: "var lambddaNoVarComment: (a: number, b: number) => number", documentation: "this is lambda multiplication" }, + ] +}); verify.signatureHelp( { @@ -73,11 +81,33 @@ verify.quickInfos({ ] }); -goTo.marker('15'); -verify.completionListContains('s', '(parameter) s: string', "On parameter\nparam on expression\nthe first parameter!"); +verify.completions({ + marker: "15", + includes: { + name: "s", + text: "(parameter) s: string", + documentation: "On parameter\nparam on expression\nthe first parameter!", + tags: [ + { name: "param", text: "s param on expression" }, + { name: "param", text: "s the first parameter!" }, + ], + }, +}); verify.quickInfoAt("16", "var assigned: (s: string) => number", "Summary on expression\nOn variable"); -goTo.marker('17'); -verify.completionListContains("assigned", "var assigned: (s: string) => number", "Summary on expression\nOn variable"); +verify.completions({ + marker: "17", + includes: [{ + name: "assigned", + text: "var assigned: (s: string) => number", + documentation: "Summary on expression\nOn variable", + tags: [ + { name: "param", text: "s param on expression" }, + { name: "returns", text: "return on expression" }, + { name: "param", text: "s the first parameter!" }, + { name: "returns", text: "the parameter's length" }, + ], + }, +]}); verify.signatureHelp({ marker: "18", docComment: "Summary on expression\nOn variable", diff --git a/tests/cases/fourslash/commentsInheritance.ts b/tests/cases/fourslash/commentsInheritance.ts index aac3cf287f4..d5111e04a47 100644 --- a/tests/cases/fourslash/commentsInheritance.ts +++ b/tests/cases/fourslash/commentsInheritance.ts @@ -220,19 +220,23 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); -verify.completionListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); -verify.completionListContains("i1_l1", "(property) i1.i1_l1: () => void", "i1_l1"); -verify.completionListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); -verify.completionListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); -verify.completionListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) i1.p1: number", ""); -verify.completionListContains("f1", "(method) i1.f1(): void", ""); -verify.completionListContains("l1", "(property) i1.l1: () => void", ""); -verify.completionListContains("nc_p1", "(property) i1.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) i1.nc_f1(): void", ""); -verify.completionListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); +verify.completions({ + marker: ["1", "11"], + includes: [ + { name: "i1_p1", text: "(property) i1.i1_p1: number", documentation: "i1_p1" }, + { name: "i1_f1", text: "(method) i1.i1_f1(): void", documentation: "i1_f1" }, + { name: "i1_l1", text: "(property) i1.i1_l1: () => void", documentation: "i1_l1" }, + { name: "i1_nc_p1", text: "(property) i1.i1_nc_p1: number" }, + { name: "i1_nc_f1", text: "(method) i1.i1_nc_f1(): void" }, + { name: "i1_nc_l1", text: "(property) i1.i1_nc_l1: () => void" }, + { name: "p1", text: "(property) i1.p1: number" }, + { name: "f1", text: "(method) i1.f1(): void" }, + { name: "l1", text: "(property) i1.l1: () => void" }, + { name: "nc_p1", text: "(property) i1.nc_p1: number" }, + { name: "nc_f1", text: "(method) i1.nc_f1(): void" }, + { name: "nc_l1", text: "(property) i1.nc_l1: () => void" }, + ], +}); verify.signatureHelp( { marker: "2", docComment: "i1_f1" }, { marker: ["3", "4", "5", "l2", "l3", "l4", "l5"], docComment: "" }, @@ -250,19 +254,23 @@ verify.quickInfos({ l5q: "(property) i1.nc_l1: () => void" }); -goTo.marker('6'); -verify.completionListContains("i1_p1", "(property) c1.i1_p1: number", "i1_p1"); -verify.completionListContains("i1_f1", "(method) c1.i1_f1(): void", "i1_f1"); -verify.completionListContains("i1_l1", "(property) c1.i1_l1: () => void", "i1_l1"); -verify.completionListContains("i1_nc_p1", "(property) c1.i1_nc_p1: number", ""); -verify.completionListContains("i1_nc_f1", "(method) c1.i1_nc_f1(): void", ""); -verify.completionListContains("i1_nc_l1", "(property) c1.i1_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) c1.p1: number", "c1_p1"); -verify.completionListContains("f1", "(method) c1.f1(): void", "c1_f1"); -verify.completionListContains("l1", "(property) c1.l1: () => void", "c1_l1"); -verify.completionListContains("nc_p1", "(property) c1.nc_p1: number", "c1_nc_p1"); -verify.completionListContains("nc_f1", "(method) c1.nc_f1(): void", "c1_nc_f1"); -verify.completionListContains("nc_l1", "(property) c1.nc_l1: () => void", "c1_nc_l1"); +verify.completions({ + marker: "6", + includes: [ + { name: "i1_p1", text: "(property) c1.i1_p1: number", documentation: "i1_p1" }, + { name: "i1_f1", text: "(method) c1.i1_f1(): void", documentation: "i1_f1" }, + { name: "i1_l1", text: "(property) c1.i1_l1: () => void", documentation: "i1_l1" }, + { name: "i1_nc_p1", text: "(property) c1.i1_nc_p1: number" }, + { name: "i1_nc_f1", text: "(method) c1.i1_nc_f1(): void" }, + { name: "i1_nc_l1", text: "(property) c1.i1_nc_l1: () => void" }, + { name: "p1", text: "(property) c1.p1: number", documentation: "c1_p1" }, + { name: "f1", text: "(method) c1.f1(): void", documentation: "c1_f1" }, + { name: "l1", text: "(property) c1.l1: () => void", documentation: "c1_l1" }, + { name: "nc_p1", text: "(property) c1.nc_p1: number", documentation: "c1_nc_p1" }, + { name: "nc_f1", text: "(method) c1.nc_f1(): void", documentation: "c1_nc_f1" }, + { name: "nc_l1", text: "(property) c1.nc_l1: () => void", documentation: "c1_nc_l1" }, + ], +}); verify.signatureHelp( { marker: "7", docComment: "i1_f1" }, { marker: "9", docComment: "c1_f1" }, @@ -284,19 +292,23 @@ verify.quickInfos({ l10q: ["(property) c1.nc_l1: () => void", "c1_nc_l1"], }); -goTo.marker('11'); -verify.completionListContains("i1_p1", "(property) i1.i1_p1: number", "i1_p1"); -verify.completionListContains("i1_f1", "(method) i1.i1_f1(): void", "i1_f1"); -verify.completionListContains("i1_l1", "(property) i1.i1_l1: () => void", "i1_l1"); -verify.completionListContains("i1_nc_p1", "(property) i1.i1_nc_p1: number", ""); -verify.completionListContains("i1_nc_f1", "(method) i1.i1_nc_f1(): void", ""); -verify.completionListContains("i1_nc_l1", "(property) i1.i1_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) i1.p1: number", ""); -verify.completionListContains("f1", "(method) i1.f1(): void", ""); -verify.completionListContains("l1", "(property) i1.l1: () => void", ""); -verify.completionListContains("nc_p1", "(property) i1.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) i1.nc_f1(): void", ""); -verify.completionListContains("nc_l1", "(property) i1.nc_l1: () => void", ""); +verify.completions({ + marker: "11", + includes: [ + { name: "i1_p1", text: "(property) i1.i1_p1: number", documentation: "i1_p1" }, + { name: "i1_f1", text: "(method) i1.i1_f1(): void", documentation: "i1_f1" }, + { name: "i1_l1", text: "(property) i1.i1_l1: () => void", documentation: "i1_l1" }, + { name: "i1_nc_p1", text: "(property) i1.i1_nc_p1: number" }, + { name: "i1_nc_f1", text: "(method) i1.i1_nc_f1(): void" }, + { name: "i1_nc_l1", text: "(property) i1.i1_nc_l1: () => void" }, + { name: "p1", text: "(property) i1.p1: number" }, + { name: "f1", text: "(method) i1.f1(): void" }, + { name: "l1", text: "(property) i1.l1: () => void" }, + { name: "nc_p1", text: "(property) i1.nc_p1: number" }, + { name: "nc_f1", text: "(method) i1.nc_f1(): void" }, + { name: "nc_l1", text: "(property) i1.nc_l1: () => void" }, + ], +}); verify.signatureHelp( { marker: "12", docComment: "i1_f1" }, { marker: ["13", "14", "15", "l12", "l13", "l14", "l15"], docComment: "" }, @@ -313,14 +325,21 @@ verify.quickInfos({ l15q: "(property) i1.nc_l1: () => void", }); -goTo.marker('16'); -verify.not.completionListContains("i1", "interface i1", "i1 is interface with properties"); -verify.completionListContains("i1_i", "var i1_i: i1", ""); -verify.completionListContains("c1", "class c1", ""); -verify.completionListContains("c1_i", "var c1_i: c1", ""); - -goTo.marker('16i'); -verify.completionListContains("i1", "interface i1", "i1 is interface with properties"); +verify.completions( + { + marker: "16", + includes: [ + { name: "i1_i", text: "var i1_i: i1" }, + { name: "c1", text: "class c1" }, + { name: "c1_i", text: "var c1_i: c1" }, + ], + excludes: "i1", + }, + { + marker: "16i", + includes: { name: "i1", text: "interface i1", documentation: "i1 is interface with properties" }, + }, +); verify.quickInfos({ "17iq": "var c2_i: c2", @@ -342,19 +361,23 @@ verify.quickInfos({ "18q": "constructor c3(): c3" }); -goTo.marker('19'); -verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); -verify.completionListContains("p1", "(property) c2.p1: number", "c2 p1"); -verify.completionListContains("f1", "(method) c2.f1(): void", "c2 f1"); -verify.completionListContains("prop", "(property) c2.prop: number", "c2 prop"); -verify.completionListContains("nc_p1", "(property) c2.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) c2.nc_f1(): void", ""); -verify.completionListContains("nc_prop", "(property) c2.nc_prop: number", ""); +verify.completions({ + marker: ["19", "29"], + includes: [ + { name: "c2_p1", text: "(property) c2.c2_p1: number", documentation: "c2 c2_p1" }, + { name: "c2_f1", text: "(method) c2.c2_f1(): void", documentation: "c2 c2_f1" }, + { name: "c2_prop", text: "(property) c2.c2_prop: number", documentation: "c2 c2_prop" }, + { name: "c2_nc_p1", text: "(property) c2.c2_nc_p1: number" }, + { name: "c2_nc_f1", text: "(method) c2.c2_nc_f1(): void" }, + { name: "c2_nc_prop", text: "(property) c2.c2_nc_prop: number" }, + { name: "p1", text: "(property) c2.p1: number", documentation: "c2 p1" }, + { name: "f1", text: "(method) c2.f1(): void", documentation: "c2 f1" }, + { name: "prop", text: "(property) c2.prop: number", documentation: "c2 prop" }, + { name: "nc_p1", text: "(property) c2.nc_p1: number" }, + { name: "nc_f1", text: "(method) c2.nc_f1(): void" }, + { name: "nc_prop", text: "(property) c2.nc_prop: number" }, + ], +}); verify.signatureHelp( { marker: "20", docComment: "c2 c2_f1" }, { marker: "22", docComment: "c2 f1" }, @@ -368,19 +391,23 @@ verify.quickInfos({ "23q": "(method) c2.nc_f1(): void" }); -goTo.marker('24'); -verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number", ""); -verify.completionListContains("p1", "(property) c3.p1: number", "c3 p1"); -verify.completionListContains("f1", "(method) c3.f1(): void", "c3 f1"); -verify.completionListContains("prop", "(property) c3.prop: number", "c3 prop"); -verify.completionListContains("nc_p1", "(property) c3.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) c3.nc_f1(): void", ""); -verify.completionListContains("nc_prop", "(property) c3.nc_prop: number", ""); +verify.completions({ + marker: "24", + includes: [ + { name: "c2_p1", text: "(property) c2.c2_p1: number", documentation: "c2 c2_p1" }, + { name: "c2_f1", text: "(method) c2.c2_f1(): void", documentation: "c2 c2_f1" }, + { name: "c2_prop", text: "(property) c2.c2_prop: number", documentation: "c2 c2_prop" }, + { name: "c2_nc_p1", text: "(property) c2.c2_nc_p1: number" }, + { name: "c2_nc_f1", text: "(method) c2.c2_nc_f1(): void" }, + { name: "c2_nc_prop", text: "(property) c2.c2_nc_prop: number" }, + { name: "p1", text: "(property) c3.p1: number", documentation: "c3 p1" }, + { name: "f1", text: "(method) c3.f1(): void", documentation: "c3 f1" }, + { name: "prop", text: "(property) c3.prop: number", documentation: "c3 prop" }, + { name: "nc_p1", text: "(property) c3.nc_p1: number" }, + { name: "nc_f1", text: "(method) c3.nc_f1(): void" }, + { name: "nc_prop", text: "(property) c3.nc_prop: number" }, + ], +}); verify.signatureHelp( { marker: "25", docComment: "c2 c2_f1" }, { marker: "27", docComment: "c3 f1" }, @@ -394,19 +421,6 @@ verify.quickInfos({ "28q": "(method) c3.nc_f1(): void" }); -goTo.marker('29'); -verify.completionListContains("c2_p1", "(property) c2.c2_p1: number", "c2 c2_p1"); -verify.completionListContains("c2_f1", "(method) c2.c2_f1(): void", "c2 c2_f1"); -verify.completionListContains("c2_prop", "(property) c2.c2_prop: number", "c2 c2_prop"); -verify.completionListContains("c2_nc_p1", "(property) c2.c2_nc_p1: number", ""); -verify.completionListContains("c2_nc_f1", "(method) c2.c2_nc_f1(): void", ""); -verify.completionListContains("c2_nc_prop", "(property) c2.c2_nc_prop: number"); -verify.completionListContains("p1", "(property) c2.p1: number", "c2 p1"); -verify.completionListContains("f1", "(method) c2.f1(): void", "c2 f1"); -verify.completionListContains("prop", "(property) c2.prop: number", "c2 prop"); -verify.completionListContains("nc_p1", "(property) c2.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) c2.nc_f1(): void", ""); -verify.completionListContains("nc_prop", "(property) c2.nc_prop: number", ""); verify.signatureHelp( { marker: "30", docComment: "c2 c2_f1" }, { marker: "32", docComment: "c2 f1" }, @@ -426,27 +440,36 @@ verify.quickInfos({ "34q": ["constructor c4(a: number): c4", "c2 constructor"] }); -goTo.marker('35'); -verify.completionListContains("c2", "class c2", ""); -verify.completionListContains("c2_i", "var c2_i: c2", ""); -verify.completionListContains("c3", "class c3", ""); -verify.completionListContains("c3_i", "var c3_i: c3", ""); -verify.completionListContains("c4", "class c4", ""); -verify.completionListContains("c4_i", "var c4_i: c4", ""); - -goTo.marker('36'); -verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", "i2_l1"); -verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) i2.p1: number", "i2 p1"); -verify.completionListContains("f1", "(method) i2.f1(): void", "i2 f1"); -verify.completionListContains("l1", "(property) i2.l1: () => void", "i2 l1"); -verify.completionListContains("nc_p1", "(property) i2.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) i2.nc_f1(): void", ""); -verify.completionListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); +verify.completions( + { + marker: "35", + includes: [ + { name: "c2", text: "class c2" }, + { name: "c2_i", text: "var c2_i: c2" }, + { name: "c3", text: "class c3" }, + { name: "c3_i", text: "var c3_i: c3" }, + { name: "c4", text: "class c4" }, + { name: "c4_i", text: "var c4_i: c4" }, + ], + }, + { + marker: ["36", "46"], + includes: [ + { name: "i2_p1", text: "(property) i2.i2_p1: number", documentation: "i2_p1" }, + { name: "i2_f1", text: "(method) i2.i2_f1(): void", documentation: "i2_f1" }, + { name: "i2_l1", text: "(property) i2.i2_l1: () => void", documentation: "i2_l1" }, + { name: "i2_nc_p1", text: "(property) i2.i2_nc_p1: number" }, + { name: "i2_nc_f1", text: "(method) i2.i2_nc_f1(): void" }, + { name: "i2_nc_l1", text: "(property) i2.i2_nc_l1: () => void" }, + { name: "p1", text: "(property) i2.p1: number", documentation: "i2 p1" }, + { name: "f1", text: "(method) i2.f1(): void", documentation: "i2 f1" }, + { name: "l1", text: "(property) i2.l1: () => void", documentation: "i2 l1" }, + { name: "nc_p1", text: "(property) i2.nc_p1: number" }, + { name: "nc_f1", text: "(method) i2.nc_f1(): void" }, + { name: "nc_l1", text: "(property) i2.nc_l1: () => void" }, + ], + }, +); verify.signatureHelp( { marker: "37", docComment: "i2_f1" }, { marker: "39", docComment: "i2 f1" }, @@ -466,19 +489,23 @@ verify.quickInfos({ "l40q": "(property) i2.nc_l1: () => void", }); -goTo.marker('41'); -verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", "i2_l1"); -verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) i3.p1: number", "i3 p1"); -verify.completionListContains("f1", "(method) i3.f1(): void", "i3 f1"); -verify.completionListContains("l1", "(property) i3.l1: () => void", "i3 l1"); -verify.completionListContains("nc_p1", "(property) i3.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) i3.nc_f1(): void", ""); -verify.completionListContains("nc_l1", "(property) i3.nc_l1: () => void", ""); +verify.completions({ + marker: "41", + includes: [ + { name: "i2_p1", text: "(property) i2.i2_p1: number", documentation: "i2_p1" }, + { name: "i2_f1", text: "(method) i2.i2_f1(): void", documentation: "i2_f1" }, + { name: "i2_l1", text: "(property) i2.i2_l1: () => void", documentation: "i2_l1" }, + { name: "i2_nc_p1", text: "(property) i2.i2_nc_p1: number" }, + { name: "i2_nc_f1", text: "(method) i2.i2_nc_f1(): void" }, + { name: "i2_nc_l1", text: "(property) i2.i2_nc_l1: () => void" }, + { name: "p1", text: "(property) i3.p1: number", documentation: "i3 p1" }, + { name: "f1", text: "(method) i3.f1(): void", documentation: "i3 f1" }, + { name: "l1", text: "(property) i3.l1: () => void", documentation: "i3 l1" }, + { name: "nc_p1", text: "(property) i3.nc_p1: number" }, + { name: "nc_f1", text: "(method) i3.nc_f1(): void" }, + { name: "nc_l1", text: "(property) i3.nc_l1: () => void" }, + ], +}); verify.signatureHelp( { marker: "42", docComment: "i2_f1" }, { marker: "44", docComment: "i3 f1" }, @@ -496,19 +523,23 @@ verify.quickInfos({ l45q: "(property) i3.nc_l1: () => void" }); -goTo.marker('46'); -verify.completionListContains("i2_p1", "(property) i2.i2_p1: number", "i2_p1"); -verify.completionListContains("i2_f1", "(method) i2.i2_f1(): void", "i2_f1"); -verify.completionListContains("i2_l1", "(property) i2.i2_l1: () => void", "i2_l1"); -verify.completionListContains("i2_nc_p1", "(property) i2.i2_nc_p1: number", ""); -verify.completionListContains("i2_nc_f1", "(method) i2.i2_nc_f1(): void", ""); -verify.completionListContains("i2_nc_l1", "(property) i2.i2_nc_l1: () => void", ""); -verify.completionListContains("p1", "(property) i2.p1: number", "i2 p1"); -verify.completionListContains("f1", "(method) i2.f1(): void", "i2 f1"); -verify.completionListContains("l1", "(property) i2.l1: () => void", "i2 l1"); -verify.completionListContains("nc_p1", "(property) i2.nc_p1: number", ""); -verify.completionListContains("nc_f1", "(method) i2.nc_f1(): void", ""); -verify.completionListContains("nc_l1", "(property) i2.nc_l1: () => void", ""); +verify.completions({ + marker: "46", + includes: [ + { name: "i2_p1", text: "(property) i2.i2_p1: number", documentation: "i2_p1" }, + { name: "i2_f1", text: "(method) i2.i2_f1(): void", documentation: "i2_f1" }, + { name: "i2_l1", text: "(property) i2.i2_l1: () => void", documentation: "i2_l1" }, + { name: "i2_nc_p1", text: "(property) i2.i2_nc_p1: number" }, + { name: "i2_nc_f1", text: "(method) i2.i2_nc_f1(): void" }, + { name: "i2_nc_l1", text: "(property) i2.i2_nc_l1: () => void" }, + { name: "p1", text: "(property) i2.p1: number", documentation: "i2 p1" }, + { name: "f1", text: "(method) i2.f1(): void", documentation: "i2 f1" }, + { name: "l1", text: "(property) i2.l1: () => void", documentation: "i2 l1" }, + { name: "nc_p1", text: "(property) i2.nc_p1: number" }, + { name: "nc_f1", text: "(method) i2.nc_f1(): void" }, + { name: "nc_l1", text: "(property) i2.nc_l1: () => void" }, + ], +}); verify.signatureHelp( { marker: "47", docComment: "i2_f1" }, { marker: "49", docComment: "i2 f1" }, @@ -526,15 +557,23 @@ verify.quickInfos({ l40q: "(property) i2.nc_l1: () => void" }); -goTo.marker('51'); -verify.not.completionListContains("i2", "interface i2", ""); -verify.completionListContains("i2_i", "var i2_i: i2", ""); -verify.not.completionListContains("i3", "interface i3", ""); -verify.completionListContains("i3_i", "var i3_i: i3", ""); - -goTo.marker('51i'); -verify.completionListContains("i2", "interface i2", ""); -verify.completionListContains("i3", "interface i3", ""); +verify.completions( + { + marker: "51", + includes: [ + { name: "i2_i", text: "var i2_i: i2" }, + { name: "i3_i", text: "var i3_i: i3" }, + ], + excludes: ["i2", "i3"], + }, + { + marker: "51i", + includes: [ + { name: "i2", text: "interface i2" }, + { name: "i3", text: "interface i3" }, + ], + }, +); verify.quickInfos({ 52: ["constructor c5(): c5", "c5 class"], diff --git a/tests/cases/fourslash/commentsInterface.ts b/tests/cases/fourslash/commentsInterface.ts index fdeeb8bb3eb..3071ae47d56 100644 --- a/tests/cases/fourslash/commentsInterface.ts +++ b/tests/cases/fourslash/commentsInterface.ts @@ -7,7 +7,7 @@ ////interface nc_/*3*/i1 { ////} ////var nc_/*4*/i1_i: nc_i1; -/////** this is interface 2 with memebers*/ +/////** this is interface 2 with members*/ ////interface i/*5*/2 { //// /** this is x*/ //// x: number; @@ -73,19 +73,25 @@ verify.quickInfos({ 2: "var i1_i: i1", 3: "interface nc_i1", 4: "var nc_i1_i: nc_i1", - 5: ["interface i2", "this is interface 2 with memebers"], + 5: ["interface i2", "this is interface 2 with members"], 6: "var i2_i: i2", 7: "var i2_i_x: number" }); -goTo.marker('8'); -verify.quickInfoIs("(property) i2.x: number", "this is x"); -verify.completionListContains("x", "(property) i2.x: number", "this is x"); -verify.completionListContains("foo", "(property) i2.foo: (b: number) => string", "this is foo"); -verify.completionListContains("nc_x", "(property) i2.nc_x: number", ""); -verify.completionListContains("nc_foo", "(property) i2.nc_foo: (b: number) => string", ""); -verify.completionListContains("fnfoo", "(method) i2.fnfoo(b: number): string", "this is fnfoo"); -verify.completionListContains("nc_fnfoo", "(method) i2.nc_fnfoo(b: number): string", ""); +verify.quickInfoAt("8", "(property) i2.x: number", "this is x"); +verify.completions({ + marker: "8", + exact: [ + { name: "x", text: "(property) i2.x: number", documentation: "this is x" }, + { name: "foo", text: "(property) i2.foo: (b: number) => string", documentation: "this is foo" }, + { name: "nc_x", text: "(property) i2.nc_x: number" }, + { name: "nc_foo", text: "(property) i2.nc_foo: (b: number) => string" }, + { name: "fnfoo", text: "(method) i2.fnfoo(b: number): string", documentation: "this is fnfoo" }, + { name: "nc_fnfoo", text: "(method) i2.nc_fnfoo(b: number): string" }, + ...completion.functionMembersWithPrototype, + ], + isNewIdentifierLocation: true, +}); verify.quickInfos({ 9: "var i2_i_foo: (b: number) => string", @@ -148,49 +154,59 @@ verify.quickInfos({ verify.signatureHelp({ marker: "33", docComment: "" }); verify.quickInfoAt("33q", "(method) i2.nc_fnfoo(b: number): string"); -goTo.marker('34'); -verify.not.completionListContains("i1", "interface i1", "this is interface 1"); -verify.completionListContains("i1_i", "var i1_i: i1", ""); -verify.not.completionListContains("nc_i1", "interface nc_i1", ""); -verify.completionListContains("nc_i1_i", "var nc_i1_i: nc_i1", ""); -verify.not.completionListContains("i2", "interface i2", "this is interface 2 with memebers"); -verify.completionListContains("i2_i", "var i2_i: i2", ""); -verify.completionListContains("i2_i_x", "var i2_i_x: number", ""); -verify.completionListContains("i2_i_foo", "var i2_i_foo: (b: number) => string", ""); -verify.completionListContains("i2_i_foo_r", "var i2_i_foo_r: string", ""); -verify.completionListContains("i2_i_i2_si", "var i2_i_i2_si: number", ""); -verify.completionListContains("i2_i_i2_ii", "var i2_i_i2_ii: number", ""); -verify.completionListContains("i2_i_n", "var i2_i_n: any", ""); -verify.completionListContains("i2_i_nc_x", "var i2_i_nc_x: number", ""); -verify.completionListContains("i2_i_nc_foo", "var i2_i_nc_foo: (b: number) => string", ""); -verify.completionListContains("i2_i_nc_foo_r", "var i2_i_nc_foo_r: string", ""); -verify.completionListContains("i2_i_r", "var i2_i_r: number", ""); -verify.completionListContains("i2_i_fnfoo", "var i2_i_fnfoo: (b: number) => string", ""); -verify.completionListContains("i2_i_fnfoo_r", "var i2_i_fnfoo_r: string", ""); -verify.completionListContains("i2_i_nc_fnfoo", "var i2_i_nc_fnfoo: (b: number) => string", ""); -verify.completionListContains("i2_i_nc_fnfoo_r", "var i2_i_nc_fnfoo_r: string", ""); - -goTo.marker('34i'); -verify.completionListContains("i1", "interface i1", "this is interface 1"); -verify.completionListContains("nc_i1", "interface nc_i1", ""); -verify.completionListContains("i2", "interface i2", "this is interface 2 with memebers"); - -goTo.marker('36'); -verify.completionListContains("a", "(parameter) a: number", "i3_i a"); +verify.completions( + { + marker: "34", + includes: [ + { name: "i1_i", text: "var i1_i: i1" }, + { name: "nc_i1_i", text: "var nc_i1_i: nc_i1", documentation: "" }, + { name: "i2_i", text: "var i2_i: i2" }, + { name: "i2_i_x", text: "var i2_i_x: number" }, + { name: "i2_i_foo", text: "var i2_i_foo: (b: number) => string" }, + { name: "i2_i_foo_r", text: "var i2_i_foo_r: string" }, + { name: "i2_i_i2_si", text: "var i2_i_i2_si: number" }, + { name: "i2_i_i2_ii", text: "var i2_i_i2_ii: number" }, + { name: "i2_i_n", text: "var i2_i_n: any" }, + { name: "i2_i_nc_x", text: "var i2_i_nc_x: number" }, + { name: "i2_i_nc_foo", text: "var i2_i_nc_foo: (b: number) => string" }, + { name: "i2_i_nc_foo_r", text: "var i2_i_nc_foo_r: string" }, + { name: "i2_i_r", text: "var i2_i_r: number" }, + { name: "i2_i_fnfoo", text: "var i2_i_fnfoo: (b: number) => string" }, + { name: "i2_i_fnfoo_r", text: "var i2_i_fnfoo_r: string" }, + { name: "i2_i_nc_fnfoo", text: "var i2_i_nc_fnfoo: (b: number) => string" }, + { name: "i2_i_nc_fnfoo_r", text: "var i2_i_nc_fnfoo_r: string" }, + ], + excludes: ["i1", "nc_i1", "i2"], + }, + { + marker: "34i", + includes: [ + { name: "i1", text: "interface i1", documentation: "this is interface 1" }, + { name: "nc_i1", text: "interface nc_i1" }, + { name: "i2", text: "interface i2", documentation: "this is interface 2 with members" }, + ], + }, + { + marker: "36", includes: { name: "a", text: "(parameter) a: number", documentation: "i3_i a" }, + } +); verify.quickInfoAt("40q", "var i3_i: i3"); -goTo.marker('40'); -verify.not.completionListContains("i3", "interface i3", ""); -verify.completionListContains("i3_i", "var i3_i: i3", ""); +verify.completions({ marker: "40", includes: { name: "i3_i", text: "var i3_i: i3" }, excludes: "i3" }); goTo.marker('41'); verify.quickInfoIs("(method) i3.f(a: number): string", "Function i3 f"); -verify.completionListContains("f", "(method) i3.f(a: number): string", "Function i3 f"); -verify.completionListContains("l", "(property) i3.l: (b: number) => string", "i3 l"); -verify.completionListContains("x", "(property) i3.x: number", "Comment i3 x"); -verify.completionListContains("nc_f", "(method) i3.nc_f(a: number): string", ""); -verify.completionListContains("nc_l", "(property) i3.nc_l: (b: number) => string", ""); -verify.completionListContains("nc_x", "(property) i3.nc_x: number", ""); +verify.completions({ + marker: "41", + exact: [ + { name: "x", text: "(property) i3.x: number", documentation: "Comment i3 x" }, + { name: "f", text: "(method) i3.f(a: number): string", documentation: "Function i3 f" }, + { name: "l", text: "(property) i3.l: (b: number) => string", documentation: "i3 l" }, + { name: "nc_x", text: "(property) i3.nc_x: number" }, + { name: "nc_f", text: "(method) i3.nc_f(a: number): string" }, + { name: "nc_l", text: "(property) i3.nc_l: (b: number) => string" }, + ], +}); verify.signatureHelp({ marker: "42", docComment: "Function i3 f", parameterDocComment: "number parameter" }); diff --git a/tests/cases/fourslash/commentsModules.ts b/tests/cases/fourslash/commentsModules.ts index 545c1569096..c9e9806aa9b 100644 --- a/tests/cases/fourslash/commentsModules.ts +++ b/tests/cases/fourslash/commentsModules.ts @@ -98,134 +98,84 @@ verify.quickInfoAt("1", "namespace m1", "Namespace comment"); -goTo.marker('2'); -verify.completionListContains("b", "var b: number", "b's comment"); -verify.completionListContains("foo", "function foo(): number", "foo's comment"); +verify.completions({ + marker: "2", + includes: [ + { name: "b", text: "var b: number", documentation: "b's comment" }, + { name: "foo", text: "function foo(): number", documentation: "foo's comment" }, + ], +}); verify.signatureHelp({ marker: "3", docComment: "foo's comment" }); verify.quickInfoAt("3q", "function foo(): number", "foo's comment"); -goTo.marker('4'); -verify.completionListContains("m1", "namespace m1", "Namespace comment"); +verify.completions( + { marker: "4", includes: { name: "m1", text: "namespace m1", documentation: "Namespace comment" } }, + { + marker: "5", + includes: [ + { name: "b", text: "var m1.b: number", documentation: "b's comment" }, + { name: "fooExport", text: "function m1.fooExport(): number", documentation: "exported function" }, + { name: "m2", text: "namespace m1.m2", documentation: "m2 comments" }, + ], + }, +); -goTo.marker('5'); -verify.completionListContains("b", "var m1.b: number", "b's comment"); -verify.completionListContains("fooExport", "function m1.fooExport(): number", "exported function"); -verify.completionListContains("m2", "namespace m1.m2"); -verify.quickInfoIs("function m1.fooExport(): number", "exported function"); +verify.quickInfoAt("5", "function m1.fooExport(): number", "exported function"); verify.signatureHelp({ marker: "6", docComment: "exported function" }); verify.quickInfoAt("7", "var myvar: m1.m2.c"); -goTo.marker('8'); -verify.quickInfoIs("constructor m1.m2.c(): m1.m2.c", "class comment;"); -verify.completionListContains("c", "constructor m1.m2.c(): m1.m2.c", "class comment;"); -verify.completionListContains("i", "var m1.m2.i: m1.m2.c", "i"); +verify.quickInfoAt("8", "constructor m1.m2.c(): m1.m2.c", "class comment;"); +verify.completions( + { + marker: "8", + includes: [ + { name: "c", text: "constructor m1.m2.c(): m1.m2.c", documentation: "class comment;" }, + { name: "i", text: "var m1.m2.i: m1.m2.c", documentation: "i" }, + ], + } +); -goTo.marker('9'); -verify.completionListContains("m2", "namespace m2", "namespace comment of m2.m3"); -verify.quickInfoIs("namespace m2", "namespace comment of m2.m3"); +function both(marker: string, name: string, text: string, documentation?: string) { + verify.completions({ marker, includes: { name, text, documentation } }); + verify.quickInfoAt(marker, text, documentation); +} -goTo.marker('10'); -verify.completionListContains("m3", "namespace m2.m3"); -verify.quickInfoIs("namespace m2.m3", "namespace comment of m2.m3"); +both("9", "m2", "namespace m2", "namespace comment of m2.m3"); +both("10", "m3", "namespace m2.m3", "namespace comment of m2.m3"); +both("11", "c", "constructor m2.m3.c(): m2.m3.c", "Exported class comment"); +both("12", "m3", "namespace m3", "namespace comment of m3.m4.m5"); +both("13", "m4", "namespace m3.m4", "namespace comment of m3.m4.m5"); +both("14", "m5", "namespace m3.m4.m5", "namespace comment of m3.m4.m5"); +both("15", "c", "constructor m3.m4.m5.c(): m3.m4.m5.c", "Exported class comment"); -goTo.marker('11'); -verify.quickInfoIs("constructor m2.m3.c(): m2.m3.c", "Exported class comment"); -verify.completionListContains("c", "constructor m2.m3.c(): m2.m3.c", "Exported class comment"); +both("16", "m4", "namespace m4", "namespace comment of m4.m5.m6"); +both("17", "m5", "namespace m4.m5", "namespace comment of m4.m5.m6"); +both("18", "m6", "namespace m4.m5.m6", "namespace comment of m4.m5.m6"); +both("19", "m7", "namespace m4.m5.m6.m7"); -goTo.marker('12'); -verify.completionListContains("m3", "namespace m3", "namespace comment of m3.m4.m5"); -verify.quickInfoIs("namespace m3", "namespace comment of m3.m4.m5"); +verify.completions({ + marker: "20", + includes: { name: "c", text: "constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", documentation: "Exported class comment" }, +}); +verify.quickInfoAt("20", "constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", "Exported class comment"); -goTo.marker('13'); -verify.completionListContains("m4", "namespace m3.m4", "namespace comment of m3.m4.m5"); -verify.quickInfoIs("namespace m3.m4", "namespace comment of m3.m4.m5"); - -goTo.marker('14'); -verify.completionListContains("m5", "namespace m3.m4.m5"); -verify.quickInfoIs("namespace m3.m4.m5", "namespace comment of m3.m4.m5"); - -goTo.marker('15'); -verify.quickInfoIs("constructor m3.m4.m5.c(): m3.m4.m5.c", "Exported class comment"); -verify.completionListContains("c", "constructor m3.m4.m5.c(): m3.m4.m5.c", "Exported class comment"); - -goTo.marker('16'); -verify.completionListContains("m4", "namespace m4", "namespace comment of m4.m5.m6"); -verify.quickInfoIs("namespace m4", "namespace comment of m4.m5.m6"); - -goTo.marker('17'); -verify.completionListContains("m5", "namespace m4.m5", "namespace comment of m4.m5.m6"); -verify.quickInfoIs("namespace m4.m5", "namespace comment of m4.m5.m6"); - -goTo.marker('18'); -verify.completionListContains("m6", "namespace m4.m5.m6"); -verify.quickInfoIs("namespace m4.m5.m6", "namespace comment of m4.m5.m6"); - -goTo.marker('19'); -verify.completionListContains("m7", "namespace m4.m5.m6.m7"); -verify.quickInfoIs("namespace m4.m5.m6.m7"); - -goTo.marker('20'); -verify.completionListContains("c", "constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", "Exported class comment"); -verify.quickInfoIs("constructor m4.m5.m6.m7.c(): m4.m5.m6.m7.c", "Exported class comment"); - -goTo.marker('21'); -verify.completionListContains("m5", "namespace m5"); -verify.quickInfoIs("namespace m5", "namespace comment of m5.m6.m7"); - -goTo.marker('22'); -verify.completionListContains("m6", "namespace m5.m6"); -verify.quickInfoIs("namespace m5.m6", "namespace comment of m5.m6.m7"); - -goTo.marker('23'); -verify.completionListContains("m7", "namespace m5.m6.m7"); -verify.quickInfoIs("namespace m5.m6.m7", "namespace comment of m5.m6.m7"); - -goTo.marker('24'); -verify.completionListContains("m8", "namespace m5.m6.m7.m8"); -verify.quickInfoIs("namespace m5.m6.m7.m8", "namespace m8 comment"); - -goTo.marker('25'); -verify.completionListContains("c", "constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c", "Exported class comment"); -verify.quickInfoIs("constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c", "Exported class comment"); - -goTo.marker('26'); -verify.completionListContains("m6", "namespace m6"); -verify.quickInfoIs("namespace m6"); - -goTo.marker('27'); -verify.completionListContains("m7", "namespace m6.m7"); -verify.quickInfoIs("namespace m6.m7"); - -goTo.marker('28'); -verify.completionListContains("m8", "namespace m6.m7.m8"); -verify.quickInfoIs("namespace m6.m7.m8"); - -goTo.marker('29'); -verify.completionListContains("c", "constructor m6.m7.m8.c(): m6.m7.m8.c", "Exported class comment"); -verify.quickInfoIs("constructor m6.m7.m8.c(): m6.m7.m8.c", "Exported class comment"); - -goTo.marker('30'); -verify.completionListContains("m7", "namespace m7"); -verify.quickInfoIs("namespace m7"); - -goTo.marker('31'); -verify.completionListContains("m8", "namespace m7.m8"); -verify.quickInfoIs("namespace m7.m8"); - -goTo.marker('32'); -verify.completionListContains("m9", "namespace m7.m8.m9"); -verify.quickInfoIs("namespace m7.m8.m9", "namespace m9 comment"); - -goTo.marker('33'); -verify.completionListContains("c", "constructor m7.m8.m9.c(): m7.m8.m9.c", "Exported class comment"); -verify.quickInfoIs("constructor m7.m8.m9.c(): m7.m8.m9.c", "Exported class comment"); - -goTo.marker('34'); -verify.completionListContains("c", 'class c', ""); -verify.quickInfoIs('class c'); +both("21", "m5", "namespace m5", "namespace comment of m5.m6.m7"); +both("22", "m6", "namespace m5.m6", "namespace comment of m5.m6.m7"); +both("23", "m7", "namespace m5.m6.m7", "namespace comment of m5.m6.m7"); +both("24", "m8", "namespace m5.m6.m7.m8", "namespace m8 comment"); +both("25", "c", "constructor m5.m6.m7.m8.c(): m5.m6.m7.m8.c", "Exported class comment"); +both("26", "m6", "namespace m6"); +both("27", "m7", "namespace m6.m7"); +both("28", "m8", "namespace m6.m7.m8"); +both("29", "c", "constructor m6.m7.m8.c(): m6.m7.m8.c", "Exported class comment"); +both("30", "m7", "namespace m7"); +both("31", "m8", "namespace m7.m8"); +both("32", "m9", "namespace m7.m8.m9", "namespace m9 comment"); +both("33", "c", "constructor m7.m8.m9.c(): m7.m8.m9.c", "Exported class comment"); +both("34", "c", "class c"); verify.quickInfos({ 35: "var myComplexVal: number", diff --git a/tests/cases/fourslash/commentsMultiModuleMultiFile.ts b/tests/cases/fourslash/commentsMultiModuleMultiFile.ts index 00256ec1334..ec7ec032ed9 100644 --- a/tests/cases/fourslash/commentsMultiModuleMultiFile.ts +++ b/tests/cases/fourslash/commentsMultiModuleMultiFile.ts @@ -28,12 +28,11 @@ const comment = "this is multi declare namespace\nthi is multi namespace 2\nthis is multi namespace 3 comment"; -goTo.marker('1'); -verify.completionListContains("multiM", "namespace multiM", comment); +verify.completions({ + marker: ["1", "7"], + includes: { name: "multiM", text: "namespace multiM", documentation: comment }, +}); for (const marker of ["2", "3", "4", "5", "6", "8"]) { verify.quickInfoAt(marker, "namespace multiM", comment); } - -goTo.marker('7'); -verify.completionListContains("multiM", "namespace multiM", comment); diff --git a/tests/cases/fourslash/commentsMultiModuleSingleFile.ts b/tests/cases/fourslash/commentsMultiModuleSingleFile.ts index dd10fb5a707..e5fb0f055a9 100644 --- a/tests/cases/fourslash/commentsMultiModuleSingleFile.ts +++ b/tests/cases/fourslash/commentsMultiModuleSingleFile.ts @@ -18,8 +18,7 @@ const comment = "this is multi declare namespace\nthi is multi namespace 2"; -goTo.marker('1'); -verify.completionListContains("multiM", "namespace multiM", comment); +verify.completions({ marker: "1", includes: { name: "multiM", text: "namespace multiM", documentation: comment } }); for (const marker of ["2", "3", "4", "5"]) { verify.quickInfoAt(marker, "namespace multiM", comment); diff --git a/tests/cases/fourslash/commentsOverloads.ts b/tests/cases/fourslash/commentsOverloads.ts index 372eedbb2da..630d1d9cdee 100644 --- a/tests/cases/fourslash/commentsOverloads.ts +++ b/tests/cases/fourslash/commentsOverloads.ts @@ -272,21 +272,27 @@ verify.signatureHelp( { marker: "o16", overloadsCount: 2, docComment: "this is signature 4 - with number parameter", parameterDocComment: "param a" }, ); -goTo.marker('17'); -verify.completionListContains('f1', 'function f1(a: number): number (+1 overload)', 'this is signature 1'); -verify.completionListContains('f2', 'function f2(a: number): number (+1 overload)', 'this is signature 2\nthis is f2 var comment'); -verify.completionListContains('f3', 'function f3(a: number): number (+1 overload)', ''); -verify.completionListContains('f4', 'function f4(a: number): number (+1 overload)', 'this is signature 4 - with number parameter'); - -goTo.marker('18'); -verify.not.completionListContains('i1', 'interface i1', ''); -verify.completionListContains('i1_i', 'var i1_i: i1\nnew (b: number) => any (+1 overload)', ''); -verify.not.completionListContains('i2', 'interface i2', ''); -verify.completionListContains('i2_i', 'var i2_i: i2\nnew (a: string) => any (+1 overload)', ''); -verify.not.completionListContains('i3', 'interface i3', ''); -verify.completionListContains('i3_i', 'var i3_i: i3\nnew (a: string) => any (+1 overload)', 'new 1'); -verify.not.completionListContains('i4', 'interface i4', ''); -verify.completionListContains('i4_i', 'var i4_i: i4\nnew (a: string) => any (+1 overload)', ''); +verify.completions( + { + marker: "17", + includes: [ + { name: "f1", text: "function f1(a: number): number (+1 overload)", documentation: "this is signature 1" }, + { name: "f2", text: "function f2(a: number): number (+1 overload)", documentation: "this is signature 2\nthis is f2 var comment" }, + { name: "f3", text: "function f3(a: number): number (+1 overload)" }, + { name: "f4", text: "function f4(a: number): number (+1 overload)", documentation: "this is signature 4 - with number parameter" }, + ], + }, + { + marker: "18", + includes: [ + { name: "i1_i", text: "var i1_i: i1\nnew (b: number) => any (+1 overload)" }, + { name: "i2_i", text: "var i2_i: i2\nnew (a: string) => any (+1 overload)" }, + { name: "i3_i", text: "var i3_i: i3\nnew (a: string) => any (+1 overload)", documentation: "new 1" }, + { name: "i4_i", text: "var i4_i: i4\nnew (a: string) => any (+1 overload)" }, + ], + excludes: ["i1", "i2", "i3", "i4"], + }, +); verify.signatureHelp({ marker: "19", overloadsCount: 2 }); verify.quickInfoAt("19q", "var i1_i: i1\nnew (b: number) => any (+1 overload)"); @@ -301,11 +307,15 @@ verify.signatureHelp({ marker: "22", overloadsCount: 2, docComment: "this is sig goTo.marker('22q'); verify.quickInfoAt("22q", "var i1_i: i1\n(b: string) => number (+1 overload)", "this is signature 2"); -goTo.marker('23'); -verify.completionListContains('foo', '(method) i1.foo(a: number): number (+1 overload)', 'foo 1'); -verify.completionListContains('foo2', '(method) i1.foo2(a: number): number (+1 overload)', 'foo2 2'); -verify.completionListContains('foo3', '(method) i1.foo3(a: number): number (+1 overload)', ''); -verify.completionListContains('foo4', '(method) i1.foo4(a: number): number (+1 overload)', 'foo4 1'); +verify.completions({ + marker: "23", + includes: [ + { name: "foo" , text: "(method) i1.foo(a: number): number (+1 overload)", documentation: "foo 1" }, + { name: "foo2", text: "(method) i1.foo2(a: number): number (+1 overload)", documentation: "foo2 2" }, + { name: "foo3", text: "(method) i1.foo3(a: number): number (+1 overload)" }, + { name: "foo4", text: "(method) i1.foo4(a: number): number (+1 overload)", documentation: "foo4 1" }, + ], +}); verify.signatureHelp({ marker: "24", overloadsCount: 2, docComment: "foo 1" }); verify.quickInfoAt("24q", "(method) i1.foo(a: number): number (+1 overload)", "foo 1"); @@ -367,12 +377,16 @@ verify.quickInfoAt("42q", "var i4_i: i4\n(a: number) => number (+1 overload)"); verify.signatureHelp({ marker: "43", overloadsCount: 2 }); verify.quickInfoAt("43q", "var i4_i: i4\n(b: string) => number (+1 overload)"); -goTo.marker('44'); -verify.completionListContains('prop1', '(method) c.prop1(a: number): number (+1 overload)', ''); -verify.completionListContains('prop2', '(method) c.prop2(a: number): number (+1 overload)', 'prop2 1'); -verify.completionListContains('prop3', '(method) c.prop3(a: number): number (+1 overload)', 'prop3 2'); -verify.completionListContains('prop4', '(method) c.prop4(a: number): number (+1 overload)', 'prop4 1'); -verify.completionListContains('prop5', '(method) c.prop5(a: number): number (+1 overload)', 'prop5 1'); +verify.completions({ + marker: "44", + exact: [ + { name: "prop1", text: "(method) c.prop1(a: number): number (+1 overload)" }, + { name: "prop2", text: "(method) c.prop2(a: number): number (+1 overload)", documentation: "prop2 1" }, + { name: "prop3", text: "(method) c.prop3(a: number): number (+1 overload)", documentation: "prop3 2" }, + { name: "prop4", text: "(method) c.prop4(a: number): number (+1 overload)", documentation: "prop4 1" }, + { name: "prop5", text: "(method) c.prop5(a: number): number (+1 overload)", documentation: "prop5 1" }, + ], +}); verify.signatureHelp({ marker: "45", overloadsCount: 2 }); verify.quickInfoAt("45q", "(method) c.prop1(a: number): number (+1 overload)"); @@ -434,26 +448,30 @@ verify.quickInfoAt("63q", "constructor c5(a: number): c5 (+1 overload)", "c5 1") verify.signatureHelp({ marker: "64", overloadsCount: 2, docComment: "c5 2" }); verify.quickInfoAt("64q", "constructor c5(b: string): c5 (+1 overload)", "c5 2"); -goTo.marker('65'); -verify.completionListContains("c", "class c", ""); -verify.completionListContains("c1", "class c1", ""); -verify.completionListContains("c2", "class c2", ""); -verify.completionListContains("c3", "class c3", ""); -verify.completionListContains("c4", "class c4", ""); -verify.completionListContains("c5", "class c5", ""); -verify.completionListContains("c_i", "var c_i: c", ""); -verify.completionListContains("c1_i_1", "var c1_i_1: c1", ""); -verify.completionListContains("c2_i_1", "var c2_i_1: c2", ""); -verify.completionListContains("c3_i_1", "var c3_i_1: c3", ""); -verify.completionListContains("c4_i_1", "var c4_i_1: c4", ""); -verify.completionListContains("c5_i_1", "var c5_i_1: c5", ""); -verify.completionListContains("c1_i_2", "var c1_i_2: c1", ""); -verify.completionListContains("c2_i_2", "var c2_i_2: c2", ""); -verify.completionListContains("c3_i_2", "var c3_i_2: c3", ""); -verify.completionListContains("c4_i_2", "var c4_i_2: c4", ""); -verify.completionListContains("c5_i_2", "var c5_i_2: c5", ""); -verify.completionListContains('multiOverload', 'function multiOverload(a: number): string (+2 overloads)', 'This is multiOverload F1 1'); -verify.completionListContains('ambientF1', 'function ambientF1(a: number): string (+2 overloads)', 'This is ambient F1 1'); +verify.completions({ + marker: "65", + includes: [ + { name: "c", text: "class c" }, + { name: "c1", text: "class c1" }, + { name: "c2", text: "class c2" }, + { name: "c3", text: "class c3" }, + { name: "c4", text: "class c4" }, + { name: "c5", text: "class c5" }, + { name: "c_i", text: "var c_i: c" }, + { name: "c1_i_1", text: "var c1_i_1: c1" }, + { name: "c2_i_1", text: "var c2_i_1: c2" }, + { name: "c3_i_1", text: "var c3_i_1: c3" }, + { name: "c4_i_1", text: "var c4_i_1: c4" }, + { name: "c5_i_1", text: "var c5_i_1: c5" }, + { name: "c1_i_2", text: "var c1_i_2: c1" }, + { name: "c2_i_2", text: "var c2_i_2: c2" }, + { name: "c3_i_2", text: "var c3_i_2: c3" }, + { name: "c4_i_2", text: "var c4_i_2: c4" }, + { name: "c5_i_2", text: "var c5_i_2: c5" }, + { name: "multiOverload", text: "function multiOverload(a: number): string (+2 overloads)", documentation: "This is multiOverload F1 1" }, + { name: "ambientF1", text: "function ambientF1(a: number): string (+2 overloads)", documentation: "This is ambient F1 1" }, + ], +}); verify.quickInfos({ 66: "var c1_i_1: c1", diff --git a/tests/cases/fourslash/completionAfterAtChar.ts b/tests/cases/fourslash/completionAfterAtChar.ts index 4f3581cd483..dbdfc89a27c 100644 --- a/tests/cases/fourslash/completionAfterAtChar.ts +++ b/tests/cases/fourslash/completionAfterAtChar.ts @@ -2,5 +2,4 @@ ////@a/**/ -goTo.marker(); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: completion.globals }); diff --git a/tests/cases/fourslash/completionAfterBackslashFollowingString.ts b/tests/cases/fourslash/completionAfterBackslashFollowingString.ts index 2e8587ffd1f..f3b1b6b195b 100644 --- a/tests/cases/fourslash/completionAfterBackslashFollowingString.ts +++ b/tests/cases/fourslash/completionAfterBackslashFollowingString.ts @@ -2,5 +2,4 @@ ////Harness.newLine = ""\n/**/ -goTo.marker(); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: completion.globals }); diff --git a/tests/cases/fourslash/completionAfterBrace.ts b/tests/cases/fourslash/completionAfterBrace.ts index ec6cc13689d..b9951459137 100644 --- a/tests/cases/fourslash/completionAfterBrace.ts +++ b/tests/cases/fourslash/completionAfterBrace.ts @@ -1,9 +1,7 @@ /// -//// +//// //// }/**/ -//// +//// - -goTo.marker(); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: completion.globals }); diff --git a/tests/cases/fourslash/completionAfterDotDotDot.ts b/tests/cases/fourslash/completionAfterDotDotDot.ts index 10c2d39b8cb..fc9ab05bbae 100644 --- a/tests/cases/fourslash/completionAfterDotDotDot.ts +++ b/tests/cases/fourslash/completionAfterDotDotDot.ts @@ -2,5 +2,4 @@ ////.../**/ -goTo.marker(); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: completion.globals }); diff --git a/tests/cases/fourslash/completionAwaitKeyword.ts b/tests/cases/fourslash/completionAwaitKeyword.ts deleted file mode 100644 index 3cb565cf88b..00000000000 --- a/tests/cases/fourslash/completionAwaitKeyword.ts +++ /dev/null @@ -1,4 +0,0 @@ -//// /**/ - -goTo.marker("") -verify.completionListContains("await"); \ No newline at end of file diff --git a/tests/cases/fourslash/completionBeforeSemanticDiagnosticsInArrowFunction1.ts b/tests/cases/fourslash/completionBeforeSemanticDiagnosticsInArrowFunction1.ts index d66c1620751..3e7c5ddf1f3 100644 --- a/tests/cases/fourslash/completionBeforeSemanticDiagnosticsInArrowFunction1.ts +++ b/tests/cases/fourslash/completionBeforeSemanticDiagnosticsInArrowFunction1.ts @@ -11,8 +11,7 @@ edit.insert("A"); // Bring up completion to force a pull resolve. This will end up resolving several symbols and // producing unreported diagnostics (i.e. that 'V' wasn't found). -verify.completionListContains("T"); -verify.completionEntryDetailIs("T", "(type parameter) T in (x: any): void"); +verify.completions({ includes: { name: "T", text: "(type parameter) T in (x: any): void" } }); // There should now be a single error. verify.numberOfErrorsInCurrentFile(1); diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index 8945245a286..9da74be0bb1 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -1,5 +1,7 @@ /// +// @noLib: true + ////abstract class B { //// private privateMethod() { } //// protected protectedMethod() { }; @@ -114,149 +116,111 @@ ////} ////class O extends B { //// constructor(public a) { -//// }, +//// }, //// /*classElementAfterConstructorSeparatedByComma*/ ////} -const allowedKeywordCount = verify.allowedClassElementKeywords.length; -type CompletionInfo = [string, string]; -type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; +const getValue: FourSlashInterface.ExpectedCompletionEntry = { name: "getValue", text: "(method) B.getValue(): number" }; +const protectedMethod: FourSlashInterface.ExpectedCompletionEntry = { name: "protectedMethod", text: "(method) B.protectedMethod(): void" }; +const staticMethod: FourSlashInterface.ExpectedCompletionEntry = { name: "staticMethod", text: "(method) B.staticMethod(): void" }; -function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { - for (const marker of classElementCompletionLocations) { - goTo.marker(marker); - verifyCompletionInfo(validMembers, verify); - verifyCompletionInfo(invalidMembers, verify.not); - verify.completionListContainsClassElementKeywords(); - verify.completionListCount(allowedKeywordCount + validMembers.length); - } -} - -function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { - for (const [symbol, text] of memberInfo) { - verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); - } -} - -const allMembersOfBase: CompletionInfo[] = [ - ["getValue", "(method) B.getValue(): number"], - ["protectedMethod", "(method) B.protectedMethod(): void"], - ["privateMethod", "(method) B.privateMethod(): void"], - ["staticMethod", "(method) B.staticMethod(): void"] -]; -const publicCompletionInfoOfD1: CompletionInfo[] = [ - ["getValue1", "(method) D1.getValue1(): number"] -]; -const publicCompletionInfoOfD2: CompletionInfo[] = [ - ["protectedMethod", "(method) D2.protectedMethod(): void"] -]; -function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInfoVerifier { - const validMembers: CompletionInfo[] = []; - const invalidMembers: CompletionInfo[] = []; - for (const member of allMembersOfBase) { - if (fn(member)) { - validMembers.push(member); - } - else { - invalidMembers.push(member); - } - } - return { validMembers, invalidMembers }; -} - - -const instanceMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue" || a === "protectedMethod"); -const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "staticMethod"); -const instanceWithoutProtectedMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue"); -const instanceWithoutPublicMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "protectedMethod"); - -const instanceMemberInfoD1: CompletionInfoVerifier = { - validMembers: instanceMemberInfo.validMembers.concat(publicCompletionInfoOfD1), - invalidMembers: instanceMemberInfo.invalidMembers -}; -const instanceMemberInfoD2: CompletionInfoVerifier = { - validMembers: instanceWithoutProtectedMemberInfo.validMembers.concat(publicCompletionInfoOfD2), - invalidMembers: instanceWithoutProtectedMemberInfo.invalidMembers -}; -const staticMemberInfoDn: CompletionInfoVerifier = { - validMembers: staticMemberInfo.validMembers, - invalidMembers: staticMemberInfo.invalidMembers.concat(publicCompletionInfoOfD1, publicCompletionInfoOfD2) -}; - -// Not a class element declaration location -const nonClassElementMarkers = [ - "InsideMethod" -]; -for (const marker of nonClassElementMarkers) { - goTo.marker(marker); - verifyCompletionInfo(allMembersOfBase, verify.not); - verify.not.completionListIsEmpty(); -} - -// Only keywords allowed at this position since they dont extend the class or are private -const onlyClassElementKeywordLocations = [ - "abstractClass", - "classThatDoesNotExtendAnotherClass", - "classThatHasWrittenPrivateKeyword", - "classElementContainingPrivateStatic", - "classThatStartedWritingIdentifierAfterPrivateModifier", - "classThatStartedWritingIdentifierAfterPrivateStaticModifier" -]; -verifyClassElementLocations({ validMembers: [], invalidMembers: allMembersOfBase }, onlyClassElementKeywordLocations); - -// Instance base members and class member keywords allowed -const classInstanceElementLocations = [ - "classThatIsEmptyAndExtendingAnotherClass", - "classThatHasDifferentMethodThanBase", - "classThatHasDifferentMethodThanBaseAfterMethod", - "classThatHasWrittenPublicKeyword", - "classThatStartedWritingIdentifier", - "propDeclarationWithoutSemicolon", - "propDeclarationWithSemicolon", - "propAssignmentWithSemicolon", - "propAssignmentWithoutSemicolon", - "methodSignatureWithoutSemicolon", - "methodSignatureWithSemicolon", - "methodImplementation", - "accessorSignatureWithoutSemicolon", - "accessorSignatureImplementation", - "classThatHasWrittenGetKeyword", - "classThatHasWrittenSetKeyword", - "classThatStartedWritingIdentifierOfGetAccessor", - "classThatStartedWritingIdentifierOfSetAccessor", - "classThatStartedWritingIdentifierAfterModifier", - "classThatHasWrittenAsyncKeyword", - "classElementAfterConstructorSeparatedByComma" -]; -verifyClassElementLocations(instanceMemberInfo, classInstanceElementLocations); - -// Static Base members and class member keywords allowed -const staticClassLocations = [ - "classElementContainingStatic", - "classThatStartedWritingIdentifierAfterStaticModifier" -]; -verifyClassElementLocations(staticMemberInfo, staticClassLocations); - -const classInstanceElementWithoutPublicMethodLocations = [ - "classThatHasAlreadyImplementedAnotherClassMethod", - "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", -]; -verifyClassElementLocations(instanceWithoutPublicMemberInfo, classInstanceElementWithoutPublicMethodLocations); - -const classInstanceElementWithoutProtectedMethodLocations = [ - "classThatHasAlreadyImplementedAnotherClassProtectedMethod", - "classThatHasDifferentMethodThanBaseAfterProtectedMethod", -]; -verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations); - -// instance memebers in D1 and base class are shown -verifyClassElementLocations(instanceMemberInfoD1, ["classThatExtendsClassExtendingAnotherClass"]); - -// instance memebers in D2 and base class are shown -verifyClassElementLocations(instanceMemberInfoD2, ["classThatExtendsClassExtendingAnotherClassWithOverridingMember"]); - -// static base members and class member keywords allowed -verifyClassElementLocations(staticMemberInfoDn, [ - "classThatExtendsClassExtendingAnotherClassAndTypesStatic", - "classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic" -]); \ No newline at end of file +verify.completions( + { + // Not a class element declaration location + marker: "InsideMethod", + exact: [ + "arguments", + "B", "C", "D", "D1", "D2", "D3", "D4", "D5", "D6", "E", "F", "F2", "G", "G2", "H", "I", "J", "K", "L", "L2", "M", "N", "O", + "undefined", + ...completion.insideMethodKeywords, + ], + }, + { + // Only keywords allowed at this position since they dont extend the class or are private + marker: [ + "abstractClass", + "classThatDoesNotExtendAnotherClass", + "classThatHasWrittenPrivateKeyword", + "classElementContainingPrivateStatic", + "classThatStartedWritingIdentifierAfterPrivateModifier", + "classThatStartedWritingIdentifierAfterPrivateStaticModifier", + ], + exact: ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"], + isNewIdentifierLocation: true, + }, + { + // Instance base members and class member keywords allowed + marker:[ + "classThatIsEmptyAndExtendingAnotherClass", + "classThatHasDifferentMethodThanBase", + "classThatHasDifferentMethodThanBaseAfterMethod", + "classThatHasWrittenPublicKeyword", + "classThatStartedWritingIdentifier", + "propDeclarationWithoutSemicolon", + "propDeclarationWithSemicolon", + "propAssignmentWithSemicolon", + "propAssignmentWithoutSemicolon", + "methodSignatureWithoutSemicolon", + "methodSignatureWithSemicolon", + "methodImplementation", + "accessorSignatureWithoutSemicolon", + "accessorSignatureImplementation", + "classThatHasWrittenGetKeyword", + "classThatHasWrittenSetKeyword", + "classThatStartedWritingIdentifierOfGetAccessor", + "classThatStartedWritingIdentifierOfSetAccessor", + "classThatStartedWritingIdentifierAfterModifier", + "classThatHasWrittenAsyncKeyword", + "classElementAfterConstructorSeparatedByComma", + ], + exact: [protectedMethod, getValue, ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + // Static Base members and class member keywords allowed + marker: ["classElementContainingStatic", "classThatStartedWritingIdentifierAfterStaticModifier"], + exact: [staticMethod, ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + marker: [ + "classThatHasAlreadyImplementedAnotherClassMethod", + "classThatHasAlreadyImplementedAnotherClassMethodAfterMethod", + ], + exact: [protectedMethod, ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + marker: [ + "classThatHasAlreadyImplementedAnotherClassProtectedMethod", + "classThatHasDifferentMethodThanBaseAfterProtectedMethod", + ], + exact: [getValue, ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + // instance memebers in D1 and base class are shown + marker: "classThatExtendsClassExtendingAnotherClass", + exact: ["getValue1", "protectedMethod", "getValue", ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + // instance memebers in D2 and base class are shown + marker: "classThatExtendsClassExtendingAnotherClassWithOverridingMember", + exact: [ + { name: "protectedMethod", text: "(method) D2.protectedMethod(): void" }, + getValue, + ...completion.classElementKeywords, + ], + isNewIdentifierLocation: true, + }, + { + // static base members and class member keywords allowed + marker: [ + "classThatExtendsClassExtendingAnotherClassAndTypesStatic", + "classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic" + ], + exact: [staticMethod, ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, +); diff --git a/tests/cases/fourslash/completionEntryForClassMembers2.ts b/tests/cases/fourslash/completionEntryForClassMembers2.ts index 9d2d158cd55..1048b5b47d0 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers2.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers2.ts @@ -188,268 +188,216 @@ //// static /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ ////} -const allowedKeywordCount = verify.allowedClassElementKeywords.length; -type CompletionInfo = [string, string]; -type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] }; - -function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) { - for (const marker of classElementCompletionLocations) { - goTo.marker(marker); - verifyCompletionInfo(validMembers, verify); - verifyCompletionInfo(invalidMembers, verify.not); - verify.completionListContainsClassElementKeywords(); - verify.completionListCount(allowedKeywordCount + validMembers.length); - } -} - -function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) { - for (const [symbol, text] of memberInfo) { - verify.completionListContains(symbol, text, /*documentation*/ undefined, "method"); - } -} - -const validInstanceMembersOfBaseClassB: CompletionInfo[] = [ - ["getValue", "(method) B.getValue(): string | boolean"], - ["protectedMethod", "(method) B.protectedMethod(): void"], +const validInstanceMembersOfBaseClassB: ReadonlyArray = [ + { name: "protectedMethod", text: "(method) B.protectedMethod(): void" }, + { name: "getValue", text: "(method) B.getValue(): string | boolean" }, ]; -const validStaticMembersOfBaseClassB: CompletionInfo[] = [ - ["staticMethod", "(method) B.staticMethod(): void"] +const validStaticMembersOfBaseClassB: ReadonlyArray = [ + { name: "staticMethod", text: "(method) B.staticMethod(): void" }, ]; -const privateMembersOfBaseClassB: CompletionInfo[] = [ - ["privateMethod", "(method) B.privateMethod(): void"], +const privateMembersOfBaseClassB: ReadonlyArray = [ + { name: "privateMethod", text: "(method) B.privateMethod(): void" }, ]; -const protectedPropertiesOfBaseClassB0: CompletionInfo[] = [ - ["protectedMethod", "(method) B0.protectedMethod(): void"], - ["protectedMethod1", "(method) B0.protectedMethod1(): void"], +const protectedPropertiesOfBaseClassB0: ReadonlyArray = [ + { name: "protectedMethod", text: "(method) B0.protectedMethod(): void" }, + { name: "protectedMethod1", text: "(method) B0.protectedMethod1(): void" }, ]; -const publicPropertiesOfBaseClassB0: CompletionInfo[] = [ - ["getValue", "(method) B0.getValue(): string | boolean"], - ["getValue1", "(method) B0.getValue1(): string | boolean"], +const publicPropertiesOfBaseClassB0: ReadonlyArray = [ + { name: "getValue", text: "(method) B0.getValue(): string | boolean" }, + { name: "getValue1", text: "(method) B0.getValue1(): string | boolean" }, ]; -const validInstanceMembersOfBaseClassB0: CompletionInfo[] = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); -const validStaticMembersOfBaseClassB0: CompletionInfo[] = [ - ["staticMethod", "(method) B0.staticMethod(): void"], - ["staticMethod1", "(method) B0.staticMethod1(): void"] +const validInstanceMembersOfBaseClassB0: ReadonlyArray = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); +const validInstanceMembersOfBaseClassB0_2 : ReadonlyArray = [ + protectedPropertiesOfBaseClassB0[0], + publicPropertiesOfBaseClassB0[0], + protectedPropertiesOfBaseClassB0[1], + publicPropertiesOfBaseClassB0[1], ]; -const privateMembersOfBaseClassB0: CompletionInfo[] = [ - ["privateMethod", "(method) B0.privateMethod(): void"], - ["privateMethod1", "(method) B0.privateMethod1(): void"], +const validStaticMembersOfBaseClassB0: ReadonlyArray = [ + { name: "staticMethod", text: "(method) B0.staticMethod(): void" }, + { name: "staticMethod1", text: "(method) B0.staticMethod1(): void" }, ]; -const membersOfI: CompletionInfo[] = [ - ["methodOfInterface", "(method) I.methodOfInterface(): number"], +const privateMembersOfBaseClassB0: ReadonlyArray = [ + { name: "privateMethod", text: "(method) B0.privateMethod(): void" }, + { name: "privateMethod1", text: "(method) B0.privateMethod1(): void" }, ]; -const membersOfI2: CompletionInfo[] = [ - ["methodOfInterface2", "(method) I2.methodOfInterface2(): number"], +const membersOfI: ReadonlyArray = [ + { name: "methodOfInterface", text: "(method) I.methodOfInterface(): number" }, ]; -const membersOfI3: CompletionInfo[] = [ - ["getValue", "(method) I3.getValue(): string"], - ["method", "(method) I3.method(): string"], +const membersOfI2: ReadonlyArray = [ + { name: "methodOfInterface2", text: "(method) I2.methodOfInterface2(): number" }, ]; -const membersOfI4: CompletionInfo[] = [ - ["staticMethod", "(method) I4.staticMethod(): void"], - ["method", "(method) I4.method(): string"], +const membersOfI3: ReadonlyArray = [ + { name: "getValue", text: "(method) I3.getValue(): string" }, + { name: "method", text: "(method) I3.method(): string" }, ]; -const membersOfI5: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ - ["methodOfInterface5", "(method) I5.methodOfInterface5(): number"] +const membersOfI4: ReadonlyArray = [ + { name: "staticMethod", text: "(method) I4.staticMethod(): void" }, + { name: "method", text: "(method) I4.method(): string" }, +]; +const membersOfI5: ReadonlyArray = publicPropertiesOfBaseClassB0.concat([ + { name: "methodOfInterface5", text: "(method) I5.methodOfInterface5(): number" }, ]); -const membersOfI6: CompletionInfo[] = publicPropertiesOfBaseClassB0.concat([ - ["staticMethod", "(method) I6.staticMethod(): void"], - ["methodOfInterface6", "(method) I6.methodOfInterface6(): number"] -]); -const membersOfI7: CompletionInfo[] = membersOfI.concat([ - ["methodOfInterface7", "(method) I7.methodOfInterface7(): number"] +const membersOfJustI5: ReadonlyArray = [ + { name: "methodOfInterface5", text: "(method) I5.methodOfInterface5(): number" }, +]; +const membersOfI6: ReadonlyArray = publicPropertiesOfBaseClassB0.concat([ + { name: "staticMethod", text: "(method) I6.staticMethod(): void" }, + { name: "methodOfInterface6", text: "(method) I6.methodOfInterface6(): number" }, ]); +const membersOfI7: ReadonlyArray = [ + { name: "methodOfInterface7", text: "(method) I7.methodOfInterface7(): number" }, + ...membersOfI, +]; +const membersOfI7_2: ReadonlyArray = [ + ...membersOfI, + { name: "methodOfInterface7", text: "(method) I7.methodOfInterface7(): number" }, +]; -function getCompletionInfoVerifier( - validMembers: CompletionInfo[], - invalidMembers: CompletionInfo[], - arrayToDistribute: CompletionInfo[], - isValidDistributionCriteria: (v: CompletionInfo) => boolean): CompletionInfoVerifier { - if (arrayToDistribute) { - validMembers = validMembers.concat(arrayToDistribute.filter(isValidDistributionCriteria)); - invalidMembers = invalidMembers.concat(arrayToDistribute.filter(v => !isValidDistributionCriteria(v))); - } - return { - validMembers, - invalidMembers - } -} - -const noMembers: CompletionInfo[] = []; -const membersOfIAndI2 = membersOfI.concat(membersOfI2); +const noMembers: ReadonlyArray = []; +const membersOfIAndI2 = [...membersOfI, ...membersOfI2]; const invalidMembersOfBAtInstanceLocation = privateMembersOfBaseClassB.concat(validStaticMembersOfBaseClassB); -// members of I and I2 -verifyClassElementLocations({ validMembers: membersOfIAndI2, invalidMembers: noMembers }, [ - "implementsIAndI2", - "implementsIAndI2AndWritingMethodNameOfI" -]); -// Static location so no members of I and I2 -verifyClassElementLocations({ validMembers: noMembers, invalidMembers: membersOfIAndI2 }, - ["implementsIAndI2AndWritingStatic"]); +const allInstanceBAndIAndI2 = [...validInstanceMembersOfBaseClassB, ...membersOfIAndI2]; -const allInstanceBAndIAndI2 = membersOfIAndI2.concat(validInstanceMembersOfBaseClassB); -// members of instance B, I and I2 -verifyClassElementLocations({ - validMembers: allInstanceBAndIAndI2, - invalidMembers: invalidMembersOfBAtInstanceLocation -}, ["extendsBAndImplementsIAndI2"]); - -// static location so only static members of B and no members of instance B, I and I2 -verifyClassElementLocations({ - validMembers: validStaticMembersOfBaseClassB, - invalidMembers: privateMembersOfBaseClassB.concat(allInstanceBAndIAndI2) -}, [ - "extendsBAndImplementsIAndI2AndWritingStatic", - "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" - ]); - -// instance members of B without protectedMethod, I and I2 -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ membersOfIAndI2, - /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, - /*arrayToDistribute*/ validInstanceMembersOfBaseClassB, - value => value[0] !== "protectedMethod"), - ["extendsBAndImplementsIAndI2WithMethodFromB"]); - -// instance members of B, members of T without methodOfInterface and I2 -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ membersOfI2.concat(validInstanceMembersOfBaseClassB), - /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, - /*arrayToDistribute*/ membersOfI, - value => value[0] !== "methodOfInterface"), - ["extendsBAndImplementsIAndI2WithMethodFromI"]); - -// instance members of B without protectedMethod, members of T without methodOfInterface and I2 -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ membersOfI2, - /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, - /*arrayToDistribute*/ membersOfI.concat(validInstanceMembersOfBaseClassB), - value => value[0] !== "methodOfInterface" && value[0] !== "protectedMethod"), - ["extendsBAndImplementsIAndI2WithMethodFromBAndI"]); - -// members of B and members of I3 that are not same as name of method in B -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ validInstanceMembersOfBaseClassB, - /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, - /*arrayToDistribute*/ membersOfI3, - value => value[0] !== "getValue"), - ["extendsBAndImplementsI3WithSameNameMembers"]); - -// members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ noMembers, - /*invalidMembers*/ invalidMembersOfBAtInstanceLocation, - /*arrayToDistribute*/ membersOfI3.concat(validInstanceMembersOfBaseClassB), - value => value[0] !== "getValue"), - ["extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember"]); - -const invalidMembersOfB0AtInstanceSide = privateMembersOfBaseClassB0.concat(validStaticMembersOfBaseClassB0); -const invalidMembersOfB0AtStaticSide = privateMembersOfBaseClassB0.concat(validInstanceMembersOfBaseClassB0); -// members of B0 and members of I4 -verifyClassElementLocations({ - validMembers: validInstanceMembersOfBaseClassB0.concat(membersOfI4), - invalidMembers: invalidMembersOfB0AtInstanceSide -}, [ - "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic" - ]); - -// members of B0 and members of I4 that are not staticMethod -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ validInstanceMembersOfBaseClassB0, - /*invalidMembers*/ invalidMembersOfB0AtInstanceSide, - /*arrayToDistribute*/ membersOfI4, - value => value[0] !== "staticMethod" - ), [ - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth" - ]); - -// static members of B0 -verifyClassElementLocations({ - validMembers: validStaticMembersOfBaseClassB0, - invalidMembers: invalidMembersOfB0AtStaticSide.concat(membersOfI4) -}, [ - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic" - ]); - -// static members of B0 without staticMethod -verifyClassElementLocations( - getCompletionInfoVerifier( - /*validMembers*/ noMembers, - /*invalidMembers*/ invalidMembersOfB0AtStaticSide.concat(membersOfI4), - /*arrayToDistribute*/ validStaticMembersOfBaseClassB0, - value => value[0] !== "staticMethod" - ), [ - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", - "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic" - ]); - -// members of I7 extends I -verifyClassElementLocations({ validMembers: membersOfI7, invalidMembers: noMembers }, [ - "implementsI7whichExtendsI", - "implementsI7whichExtendsIAndAlsoImplementsI", - "implementsIAndAlsoImplementsI7whichExtendsI" -]); +const invalidMembersOfB0AtInstanceSide = [...privateMembersOfBaseClassB0, ...validStaticMembersOfBaseClassB0]; +const invalidMembersOfB0AtStaticSide = [...privateMembersOfBaseClassB0, validInstanceMembersOfBaseClassB0]; const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide; -// members of I5 extends B0 -verifyClassElementLocations({ - validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), - invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 -}, [ - "implementsI5ThatExtendsB0", - ]); -// members of I6 extends B0 -verifyClassElementLocations({ - validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), - invalidMembers: invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 -}, [ - "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", - ]); +const tests: ReadonlyArray<{ readonly marker: string | ReadonlyArray, readonly members: ReadonlyArray }> = [ + // members of I and I2 + { marker: ["implementsIAndI2", "implementsIAndI2AndWritingMethodNameOfI"], members: membersOfIAndI2 }, + // Static location so no members of I and I2 + { marker: "implementsIAndI2AndWritingStatic", members: [] }, + // members of instance B, I and I2 + { marker: "extendsBAndImplementsIAndI2", members: allInstanceBAndIAndI2 }, + // static location so only static members of B and no members of instance B, I and I2 + { + marker: [ + "extendsBAndImplementsIAndI2AndWritingStatic", + "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" + ], + members: validStaticMembersOfBaseClassB, + }, + // instance members of B without protectedMethod, I and I2 + { marker: "extendsBAndImplementsIAndI2WithMethodFromB",members: [validInstanceMembersOfBaseClassB[1], ...membersOfIAndI2] }, //TODO:NEATER + // instance members of B, members of T without methodOfInterface and I2 + { marker: "extendsBAndImplementsIAndI2WithMethodFromI", members: [...validInstanceMembersOfBaseClassB, ...membersOfI2] }, + // instance members of B without protectedMethod, members of T without methodOfInterface and I2 + { marker: "extendsBAndImplementsIAndI2WithMethodFromBAndI", members: [validInstanceMembersOfBaseClassB[1], ...membersOfI2] }, + // members of B and members of I3 that are not same as name of method in B + { marker: "extendsBAndImplementsI3WithSameNameMembers", members: [...validInstanceMembersOfBaseClassB, membersOfI3[1]] }, //TODO:NEATER + // members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B + { marker: "extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember", members: [validInstanceMembersOfBaseClassB[0], membersOfI3[1]] }, //TODO:NEATER + // members of B0 and members of I4 + { + marker: [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic", + ], + members: [...validInstanceMembersOfBaseClassB0_2, ...membersOfI4], + }, + // members of B0 and members of I4 that are not staticMethod + { + marker: [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth", + ], + members: [...validInstanceMembersOfBaseClassB0_2, membersOfI4[1]], //TODO:NEATER + }, + // static members of B0 + { + marker: [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic", + ], + members: validStaticMembersOfBaseClassB0, + }, + // static members of B0 without staticMethod + { + marker: [ + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", + "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic", + ], + members: [validStaticMembersOfBaseClassB0[1]] // TODO:NEATER + }, + // members of I7 extends I + { + marker: [ + "implementsI7whichExtendsI", + "implementsI7whichExtendsIAndAlsoImplementsI", + ], + members: membersOfI7, + }, + { + marker: "implementsIAndAlsoImplementsI7whichExtendsI", + members: membersOfI7_2, + }, + // members of I5 extends B0 + { + marker: "implementsI5ThatExtendsB0", + members: [...membersOfJustI5, protectedPropertiesOfBaseClassB0[0], publicPropertiesOfBaseClassB0[0], protectedPropertiesOfBaseClassB0[1], publicPropertiesOfBaseClassB0[1]], //TODO:NEATER + }, + // members of I6 extends B0 + { + marker: "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", + //TODO:NEATER + members:[ + membersOfI6[3], + membersOfI6[2], + protectedPropertiesOfBaseClassB0[0], + membersOfI6[0], + protectedPropertiesOfBaseClassB0[1], + membersOfI6[1], + ], + }, + // members of B0 and I5 that extends B0 + { + marker: "extendsB0AndImplementsI5ThatExtendsB0", + members: [ + protectedPropertiesOfBaseClassB0[0], + membersOfI5[0], + protectedPropertiesOfBaseClassB0[1], + membersOfI5[1], + membersOfI5[2], + ], + }, + // members of B0 and I6 that extends B0 + { + marker: "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0", + members: [ + protectedPropertiesOfBaseClassB0[0], + membersOfI6[0], + protectedPropertiesOfBaseClassB0[1], + membersOfI6[1], + membersOfI6[3], + membersOfI6[2], + ], + }, + // nothing on static side as these do not extend any other class + { + marker: [ + "implementsI5ThatExtendsB0TypesStatic", + "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic", + ], + members: [], + }, + { + marker: [ + "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", + "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic", + ], + // statics of base B but nothing from instance side + members: validStaticMembersOfBaseClassB0, + }, +]; -// members of B0 and I5 that extends B0 -verifyClassElementLocations({ - validMembers: membersOfI5.concat(protectedPropertiesOfBaseClassB0), - invalidMembers: invalidMembersOfB0AtInstanceSide -}, [ - "extendsB0AndImplementsI5ThatExtendsB0" - ]); - -// members of B0 and I6 that extends B0 -verifyClassElementLocations({ - validMembers: membersOfI6.concat(protectedPropertiesOfBaseClassB0), - invalidMembers: invalidMembersOfB0AtInstanceSide -}, [ - "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0" - ]); - -// nothing on static side as these do not extend any other class -verifyClassElementLocations({ - validMembers: [], - invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) -}, [ - "implementsI5ThatExtendsB0TypesStatic", - "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" - ]); - -// statics of base B but nothing from instance side -verifyClassElementLocations({ - validMembers: validStaticMembersOfBaseClassB0, - invalidMembers: membersOfI5.concat(membersOfI6, invalidMembersOfB0AtStaticSide) -}, [ - "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", - "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic" - ]); \ No newline at end of file +verify.completions(...tests.map(({ marker, members }): FourSlashInterface.CompletionsOptions => ({ + marker, + exact: [...members.map(m => ({ ...m, kind: "method" })), ...completion.classElementKeywords], + isNewIdentifierLocation: true, +}))); diff --git a/tests/cases/fourslash/completionEntryForClassMembers3.ts b/tests/cases/fourslash/completionEntryForClassMembers3.ts index a27c5959e6d..ff33116b064 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers3.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers3.ts @@ -15,11 +15,15 @@ //// zap() { } //// b/*3*/: any; ////} -const allowedKeywordCount = verify.allowedClassElementKeywords.length; + function verifyHasBar() { - verify.completionListContains("bar", "(method) IFoo.bar(): void", /*documentation*/ undefined, "method"); - verify.completionListContainsClassElementKeywords(); - verify.completionListCount(allowedKeywordCount + 1); + verify.completions({ + exact: [ + { name: "bar", text: "(method) IFoo.bar(): void", kind: "method" }, + ...completion.classElementKeywords, + ], + isNewIdentifierLocation: true, + }); } goTo.marker("1"); diff --git a/tests/cases/fourslash/completionEntryForConst.ts b/tests/cases/fourslash/completionEntryForConst.ts index 933212d4ef7..c89dd821245 100644 --- a/tests/cases/fourslash/completionEntryForConst.ts +++ b/tests/cases/fourslash/completionEntryForConst.ts @@ -3,5 +3,4 @@ ////const c = "s"; /////**/ -goTo.marker(); -verify.completionListContains("c", "const c: \"s\"", /*documentation*/ undefined, "const"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "c", text: 'const c: "s"', kind: "const" } }); diff --git a/tests/cases/fourslash/completionEntryForDeferredMappedTypeMembers.ts b/tests/cases/fourslash/completionEntryForDeferredMappedTypeMembers.ts index 785ac32ee39..e1ec3b0102e 100644 --- a/tests/cases/fourslash/completionEntryForDeferredMappedTypeMembers.ts +++ b/tests/cases/fourslash/completionEntryForDeferredMappedTypeMembers.ts @@ -9,9 +9,4 @@ //// out.a./*2*/a //// out.a.a./*3*/a -goTo.marker('1'); -verify.completionListCount(1); -goTo.marker('2'); -verify.completionListCount(1); -goTo.marker('3'); -verify.completionListCount(1); +verify.completions({ marker: test.markers(), exact: "a" }); diff --git a/tests/cases/fourslash/completionEntryForImportName.ts b/tests/cases/fourslash/completionEntryForImportName.ts index 5773eb5376e..2567d7f3e11 100644 --- a/tests/cases/fourslash/completionEntryForImportName.ts +++ b/tests/cases/fourslash/completionEntryForImportName.ts @@ -2,10 +2,9 @@ ////import /*1*/ /*2*/ -goTo.marker('1'); -verify.completionListIsEmpty(); +verify.completions({ marker: "1", exact: undefined }); edit.insert('q'); -verify.completionListIsEmpty(); +verify.completions({ exact: undefined }); verifyIncompleteImportName(); goTo.marker('2'); @@ -18,7 +17,6 @@ edit.insert("a."); verifyIncompleteImportName(); function verifyIncompleteImportName() { - goTo.marker('1'); - verify.completionListIsEmpty(); + verify.completions({ marker: "1", exact: undefined }); verify.quickInfoIs("import q"); } \ No newline at end of file diff --git a/tests/cases/fourslash/completionEntryForPropertyFromUnionOfModuleType.ts b/tests/cases/fourslash/completionEntryForPropertyFromUnionOfModuleType.ts index a9205b97f1f..70a0c863f87 100644 --- a/tests/cases/fourslash/completionEntryForPropertyFromUnionOfModuleType.ts +++ b/tests/cases/fourslash/completionEntryForPropertyFromUnionOfModuleType.ts @@ -11,5 +11,4 @@ ////var q: typeof E | typeof F; ////var j = q./*1*/ -goTo.marker('1'); -verify.completionListContains('n', "(property) n: number"); \ No newline at end of file +verify.completions({ marker: "1", exact: [{ name: "n", text: "(property) n: number" }] }); diff --git a/tests/cases/fourslash/completionEntryForShorthandPropertyAssignment.ts b/tests/cases/fourslash/completionEntryForShorthandPropertyAssignment.ts index dae5762d92c..51779afa36d 100644 --- a/tests/cases/fourslash/completionEntryForShorthandPropertyAssignment.ts +++ b/tests/cases/fourslash/completionEntryForShorthandPropertyAssignment.ts @@ -2,5 +2,4 @@ //// var person: {name:string; id:number} = {n/**/ -goTo.marker(); -verify.completionListContains("name", /*text*/ undefined, /*documentation*/ undefined, "property"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "name", kind: "property" } }); diff --git a/tests/cases/fourslash/completionEntryForUnionMethod.ts b/tests/cases/fourslash/completionEntryForUnionMethod.ts index f8fd9ad9dc9..71b77025110 100644 --- a/tests/cases/fourslash/completionEntryForUnionMethod.ts +++ b/tests/cases/fourslash/completionEntryForUnionMethod.ts @@ -3,9 +3,19 @@ ////var y: Array|Array; ////y.map/**/( -goTo.marker(); -verify.quickInfoIs( - "(property) map: ((callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any) => U[])", - "Calls a defined callback function on each element of an array, and returns an array that contains the results."); +const text = "(property) map: ((callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any) => U[])"; +const documentation = "Calls a defined callback function on each element of an array, and returns an array that contains the results."; -verify.completionListContains('map', "(property) map: ((callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | ((callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any) => U[])"); \ No newline at end of file +verify.quickInfoAt("", text, documentation); +verify.completions({ + marker: "", + includes: { + name: "map", + text, + documentation, + tags: [ + { name: "param", text: "callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array." }, + { name: "param", text: "thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value." } + ], + }, +}); diff --git a/tests/cases/fourslash/completionEntryForUnionProperty.ts b/tests/cases/fourslash/completionEntryForUnionProperty.ts index 0ffc184693c..ea5e34d95dd 100644 --- a/tests/cases/fourslash/completionEntryForUnionProperty.ts +++ b/tests/cases/fourslash/completionEntryForUnionProperty.ts @@ -14,7 +14,10 @@ //// ////x./**/ -goTo.marker(); -verify.completionListContains("commonProperty", "(property) commonProperty: string | number"); -verify.completionListContains("commonFunction", "(method) commonFunction(): number"); -verify.completionListCount(2); \ No newline at end of file +verify.completions({ + marker: "", + exact: [ + { name: "commonProperty", text: "(property) commonProperty: string | number" }, + { name: "commonFunction", text: "(method) commonFunction(): number" }, + ], +}); diff --git a/tests/cases/fourslash/completionEntryForUnionProperty2.ts b/tests/cases/fourslash/completionEntryForUnionProperty2.ts index 604052ff1b5..c254213e473 100644 --- a/tests/cases/fourslash/completionEntryForUnionProperty2.ts +++ b/tests/cases/fourslash/completionEntryForUnionProperty2.ts @@ -14,7 +14,10 @@ //// ////x.commonProperty./**/ -goTo.marker(); -verify.completionListContains("toString", "(method) toString(): string"); -verify.completionListContains("valueOf", "(method) valueOf(): string | number"); -verify.completionListCount(2); \ No newline at end of file +verify.completions({ + marker: "", + exact: [ + { name: "toString", text: "(method) toString(): string", documentation: "Returns a string representation of a string.", }, + { name: "valueOf", text: "(method) valueOf(): string | number", documentation: "Returns the primitive value of the specified object." }, + ], +}); diff --git a/tests/cases/fourslash/completionEntryOnNarrowedType.ts b/tests/cases/fourslash/completionEntryOnNarrowedType.ts index f81572ccebf..aa8f7a64e7f 100644 --- a/tests/cases/fourslash/completionEntryOnNarrowedType.ts +++ b/tests/cases/fourslash/completionEntryOnNarrowedType.ts @@ -10,11 +10,8 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string | number"); - -goTo.marker('2'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: number"); - -goTo.marker('3'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string"); \ No newline at end of file +verify.completions( + { marker: "1", includes: { name: "strOrNum", text: "(parameter) strOrNum: string | number" } }, + { marker: "2", includes: { name: "strOrNum", text: "(parameter) strOrNum: number" } }, + { marker: "3", includes: { name: "strOrNum", text: "(parameter) strOrNum: string" } }, +); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts index 1b1cbe9a4df..a913a4d5e65 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment1.ts @@ -3,8 +3,6 @@ //// export interface Configfiles { //// jspm: string; //// 'jspm:browser': string; -//// 'jspm:dev': string; -//// 'jspm:node': string; //// } //// let files: Configfiles; @@ -13,5 +11,7 @@ //// '/*1*/': '' //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"']); -verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"]); +verify.completions( + { marker: "0", exact: ["jspm", '"jspm:browser"'] }, + { marker: "1", exact: ["jspm", "jspm:browser"] }, +); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts index 669e58bdac1..1f779908ca1 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment2.ts @@ -7,8 +7,6 @@ //// export interface ConfigFiles { //// jspm: string; //// 'jspm:browser': string; -//// 'jspm:dev': string; -//// 'jspm:node': string; //// } //// let config: Config; @@ -19,5 +17,7 @@ //// } //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"', '"jspm:dev"', '"jspm:node"']); -verify.completionsAt("1", ["jspm", "jspm:browser", "jspm:dev", "jspm:node"]); +verify.completions( + { marker: "0", exact: ["jspm", '"jspm:browser"'] }, + { marker: "1", exact: ["jspm", "jspm:browser"] }, +); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts index 7878750c6fa..fe8818e7831 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment3.ts @@ -15,5 +15,7 @@ //// '/*1*/': "" //// } -verify.completionsAt("0", ["jspm", '"jspm:browser"']); -verify.completionsAt("1", ["jspm", "jspm:browser"]); +verify.completions( + { marker: "0", exact: ["jspm", '"jspm:browser"'] }, + { marker: "1", exact: ["jspm", "jspm:browser"] }, +); diff --git a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts index 703e6738098..ff654b57f16 100644 --- a/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts +++ b/tests/cases/fourslash/completionForQuotedPropertyInPropertyAssignment4.ts @@ -3,8 +3,6 @@ //// export interface ConfigFiles { //// jspm: string; //// 'jspm:browser': string; -//// 'jspm:dev': string; -//// 'jspm:node': string; //// } //// function foo(c: ConfigFiles) {} @@ -13,12 +11,8 @@ //// "/*1*/": "", //// }) -goTo.marker('0'); -verify.completionListContains("jspm"); -//verify.completionListAllowsNewIdentifier(); -//verify.completionListCount(1); -/*goTo.marker('1'); -verify.completionListContains("jspm:dev"); -verify.completionListAllowsNewIdentifier(); -verify.completionListCount(4);*/ +verify.completions( + { marker: "0", exact: ["jspm", '"jspm:browser"'] }, + { marker: "1", exact: ["jspm", "jspm:browser"] }, +); diff --git a/tests/cases/fourslash/completionForStringLiteral.ts b/tests/cases/fourslash/completionForStringLiteral.ts index 7a14f6b6519..66fd26f26dd 100644 --- a/tests/cases/fourslash/completionForStringLiteral.ts +++ b/tests/cases/fourslash/completionForStringLiteral.ts @@ -6,10 +6,4 @@ ////function f(a: Options) { }; ////f("/*2*/ -goTo.marker('1'); -verify.completionListContains("Option 1"); -verify.completionListCount(3); - -goTo.marker('2'); -verify.completionListContains("Option 2"); -verify.completionListCount(3); +verify.completions({ marker: ["1", "2"], exact: ["Option 1", "Option 2", "Option 3"] }); diff --git a/tests/cases/fourslash/completionForStringLiteral10.ts b/tests/cases/fourslash/completionForStringLiteral10.ts index 76a98eb732f..0da078af6d8 100644 --- a/tests/cases/fourslash/completionForStringLiteral10.ts +++ b/tests/cases/fourslash/completionForStringLiteral10.ts @@ -4,9 +4,4 @@ ////let a: As; ////if ('/**/' != a -goTo.marker(); -verify.completionListContains("arf"); -verify.completionListContains("abacus"); -verify.completionListContains("abaddon"); -verify.completionListCount(3); - +verify.completions({ marker: "", exact: ["arf", "abacus", "abaddon"] }); diff --git a/tests/cases/fourslash/completionForStringLiteral11.ts b/tests/cases/fourslash/completionForStringLiteral11.ts index f6acac28a65..c0edc8e2a61 100644 --- a/tests/cases/fourslash/completionForStringLiteral11.ts +++ b/tests/cases/fourslash/completionForStringLiteral11.ts @@ -6,9 +6,4 @@ //// case '/**/ ////} -goTo.marker(); -verify.completionListContains("arf"); -verify.completionListContains("abacus"); -verify.completionListContains("abaddon"); -verify.completionListCount(3); - +verify.completions({ marker: "", exact: ["arf", "abacus", "abaddon" ] }); diff --git a/tests/cases/fourslash/completionForStringLiteral12.ts b/tests/cases/fourslash/completionForStringLiteral12.ts index 22bb2f00a43..a8ccfb08402 100644 --- a/tests/cases/fourslash/completionForStringLiteral12.ts +++ b/tests/cases/fourslash/completionForStringLiteral12.ts @@ -5,6 +5,4 @@ ////function foo(x: string) {} ////foo("/**/") -goTo.marker(); -verify.completionListContains("bla"); -verify.completionListCount(1); +verify.completions({ marker: "", exact: "bla" }); diff --git a/tests/cases/fourslash/completionForStringLiteral13.ts b/tests/cases/fourslash/completionForStringLiteral13.ts index 391a1ed5083..5e3c7a56a2e 100644 --- a/tests/cases/fourslash/completionForStringLiteral13.ts +++ b/tests/cases/fourslash/completionForStringLiteral13.ts @@ -10,5 +10,4 @@ ////var Promise: PromiseConstructor; ////Promise["/*1*/"]; -goTo.marker('1'); -verify.not.completionListContains("__@species"); +verify.completions({ marker: "1", exact: [] }); diff --git a/tests/cases/fourslash/completionForStringLiteral2.ts b/tests/cases/fourslash/completionForStringLiteral2.ts index 2bc783f7e53..d6b71594d88 100644 --- a/tests/cases/fourslash/completionForStringLiteral2.ts +++ b/tests/cases/fourslash/completionForStringLiteral2.ts @@ -11,5 +11,7 @@ ////o["/*2*/ ; ////p["/*3*/"]; -verify.completionsAt(["1", "2"], ["foo", "bar", "some other name"]); -verify.completionsAt("3", ["a"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: ["1", "2"], exact: ["foo", "bar", "some other name"] }, + { marker: "3", exact: "a", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteral3.ts b/tests/cases/fourslash/completionForStringLiteral3.ts index 4e0a2133a0a..9ebcec52593 100644 --- a/tests/cases/fourslash/completionForStringLiteral3.ts +++ b/tests/cases/fourslash/completionForStringLiteral3.ts @@ -9,4 +9,4 @@ //// ////f("/*2*/ -verify.completionsAt(["1", "2"], ["A", "B", "C"], { isNewIdentifierLocation: true }); +verify.completions({ marker: ["1", "2"], exact: ["A", "B", "C"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteral4.ts b/tests/cases/fourslash/completionForStringLiteral4.ts index 5629926bd18..d05e353fd23 100644 --- a/tests/cases/fourslash/completionForStringLiteral4.ts +++ b/tests/cases/fourslash/completionForStringLiteral4.ts @@ -17,7 +17,4 @@ goTo.marker('1'); verify.quickInfoExists(); verify.quickInfoIs('function f(p1: "literal", p2: "literal", p3: "other1" | "other2", p4: number | "literal", p5: true | 12): string', 'I am documentation'); -goTo.marker('2'); -verify.completionListContains("other1"); -verify.completionListContains("other2"); -verify.completionListCount(2); +verify.completions({ marker: "2", exact: ["other1", "other2"] }); diff --git a/tests/cases/fourslash/completionForStringLiteral5.ts b/tests/cases/fourslash/completionForStringLiteral5.ts index a850ee3aafc..3592d374341 100644 --- a/tests/cases/fourslash/completionForStringLiteral5.ts +++ b/tests/cases/fourslash/completionForStringLiteral5.ts @@ -8,8 +8,4 @@ ////function f(a: K) { }; ////f("/*1*/ -goTo.marker('1'); -verify.completionListContains("foo"); -verify.completionListContains("bar"); -verify.completionListCount(2); - +verify.completions({ marker: "1", exact: ["foo", "bar"] }); diff --git a/tests/cases/fourslash/completionForStringLiteral6.ts b/tests/cases/fourslash/completionForStringLiteral6.ts index ac4a378abfb..df08f56aa9a 100644 --- a/tests/cases/fourslash/completionForStringLiteral6.ts +++ b/tests/cases/fourslash/completionForStringLiteral6.ts @@ -6,7 +6,4 @@ ////function bar(f: Foo) { }; ////bar({x: "/**/"}); -goTo.marker(); -verify.completionListContains("abc"); -verify.completionListContains("def"); -verify.completionListCount(2); +verify.completions({ marker: "", exact: ["abc", "def"] }); diff --git a/tests/cases/fourslash/completionForStringLiteral7.ts b/tests/cases/fourslash/completionForStringLiteral7.ts index 23a12f9ea4b..13cf2814c86 100644 --- a/tests/cases/fourslash/completionForStringLiteral7.ts +++ b/tests/cases/fourslash/completionForStringLiteral7.ts @@ -5,5 +5,7 @@ ////function f(x: T, ...args: U[]) { }; ////f("/*1*/", "/*2*/", "/*3*/"); -verify.completionsAt("1", ["foo", "bar"]); -verify.completionsAt(["2", "3"], ["oof", "rab"]); +verify.completions( + { marker: "1", exact: ["foo", "bar"] }, + { marker: ["2", "3"], exact: ["oof", "rab"] }, +); diff --git a/tests/cases/fourslash/completionForStringLiteral8.ts b/tests/cases/fourslash/completionForStringLiteral8.ts index 727bdf6e6a4..bec0ab05b12 100644 --- a/tests/cases/fourslash/completionForStringLiteral8.ts +++ b/tests/cases/fourslash/completionForStringLiteral8.ts @@ -4,9 +4,4 @@ ////let a: As; ////if (a === '/**/ -goTo.marker(); -verify.completionListContains("arf"); -verify.completionListContains("abacus"); -verify.completionListContains("abaddon"); -verify.completionListCount(3); - +verify.completions({ marker: "", exact: ["arf", "abacus", "abaddon"] }); diff --git a/tests/cases/fourslash/completionForStringLiteralExport.ts b/tests/cases/fourslash/completionForStringLiteralExport.ts index f20ae1b39f1..43275689b0a 100644 --- a/tests/cases/fourslash/completionForStringLiteralExport.ts +++ b/tests/cases/fourslash/completionForStringLiteralExport.ts @@ -21,7 +21,9 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -verify.completionsAt(["0", "4"], ["someFile1", "my_typings", "sub"], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); -verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); -verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: ["0", "4"], exact: ["someFile1", "my_typings", "sub"], isNewIdentifierLocation: true }, + { marker: "1", exact: "someFile2", isNewIdentifierLocation: true }, + { marker: "2", exact: { name: "some-module", replacementSpan: test.ranges()[0] }, isNewIdentifierLocation: true }, + { marker: "3", exact: "fourslash", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteralFromSignature.ts b/tests/cases/fourslash/completionForStringLiteralFromSignature.ts index ec7d046ef9b..b9e96c7603b 100644 --- a/tests/cases/fourslash/completionForStringLiteralFromSignature.ts +++ b/tests/cases/fourslash/completionForStringLiteralFromSignature.ts @@ -4,4 +4,4 @@ ////declare function f(a: string): void; ////f("/**/"); -verify.completionsAt("", ["x"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: "x", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralFromSignature2.ts b/tests/cases/fourslash/completionForStringLiteralFromSignature2.ts index 176efac4e55..f070d7e2389 100644 --- a/tests/cases/fourslash/completionForStringLiteralFromSignature2.ts +++ b/tests/cases/fourslash/completionForStringLiteralFromSignature2.ts @@ -4,4 +4,4 @@ ////declare function f(a: string, b: number): void; ////f("/**/", 0); -verify.completionsAt("", [], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: [], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralImport1.ts b/tests/cases/fourslash/completionForStringLiteralImport1.ts index 0c279d7504c..7705d802ecc 100644 --- a/tests/cases/fourslash/completionForStringLiteralImport1.ts +++ b/tests/cases/fourslash/completionForStringLiteralImport1.ts @@ -20,7 +20,9 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -verify.completionsAt("0", ["someFile1", "my_typings", "sub"], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); -verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); -verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: "0", exact: ["someFile1", "my_typings", "sub"], isNewIdentifierLocation: true }, + { marker: "1", exact: "someFile2", isNewIdentifierLocation: true }, + { marker: "2", exact: { name: "some-module", replacementSpan: test.ranges()[0] }, isNewIdentifierLocation: true }, + { marker: "3", exact: "fourslash", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteralImport2.ts b/tests/cases/fourslash/completionForStringLiteralImport2.ts index 885686f4999..727fd52a218 100644 --- a/tests/cases/fourslash/completionForStringLiteralImport2.ts +++ b/tests/cases/fourslash/completionForStringLiteralImport2.ts @@ -20,7 +20,9 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -verify.completionsAt("0", ["someFile.ts", "my_typings", "sub"], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["some-module"], { isNewIdentifierLocation: true }); -verify.completionsAt("2", ["someOtherFile.ts"], { isNewIdentifierLocation: true }); -verify.completionsAt("3", ["some-module"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: "0", exact: ["someFile.ts", "my_typings", "sub"], isNewIdentifierLocation: true }, + { marker: "1", exact: "some-module", isNewIdentifierLocation: true }, + { marker: "2", exact: "someOtherFile.ts", isNewIdentifierLocation: true }, + { marker: "3", exact: "some-module", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteralInIndexedAccess01.ts b/tests/cases/fourslash/completionForStringLiteralInIndexedAccess01.ts index 0a86f5396c4..14f11ba227e 100644 --- a/tests/cases/fourslash/completionForStringLiteralInIndexedAccess01.ts +++ b/tests/cases/fourslash/completionForStringLiteralInIndexedAccess01.ts @@ -7,7 +7,4 @@ //// ////let x: Foo["/*1*/"] -goTo.marker("1"); -verify.completionListContains("foo"); -verify.completionListContains("bar"); -verify.completionListCount(2); +verify.completions({ marker: "1", exact: ["foo", "bar"] }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts index ad45719caea..6737384aff0 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport1.ts @@ -42,7 +42,9 @@ //// /*unlisted-module*/ ["import_as", "import_equals", "require"].forEach((kind, i) => { - verify.completionsAt(`${kind}0`, ["fake-module", "fake-module-dev"], { isNewIdentifierLocation: true }); - verify.completionsAt(`${kind}1`, ["dts", "index", "ts", "tsx"], { isNewIdentifierLocation: true }); - verify.completionsAt(`${kind}2`, ["fake-module", "fake-module-dev"].map(name => ({ name, replacementSpan: test.ranges()[i] })), { isNewIdentifierLocation: true }); + verify.completions( + { marker: `${kind}0`, exact: ["fake-module", "fake-module-dev"], isNewIdentifierLocation: true }, + { marker: `${kind}1`, exact: ["dts", "index", "ts", "tsx"], isNewIdentifierLocation: true }, + { marker: `${kind}2`, exact: ["fake-module", "fake-module-dev"].map(name => ({ name, replacementSpan: test.ranges()[i] })), isNewIdentifierLocation: true }, + ); }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport10.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport10.ts index d85d207dc04..5e568e2507e 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport10.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport10.ts @@ -24,4 +24,4 @@ // @Filename: dir1/dir2/dir3/node_modules/fake-module3/ts.ts //// -verify.completions({ marker: test.markerNames(), exact: [], isNewIdentifierLocation: true }); +verify.completions({ marker: test.markers(), exact: [], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport12.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport12.ts index 4d7ffccf8b8..8a3970fb96e 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport12.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport12.ts @@ -16,7 +16,7 @@ //// } verify.completions({ - marker: test.markerNames(), + marker: test.markers(), exact: ["module", "dev-module", "peer-module", "optional-module"], isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport2.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport2.ts index a8fe2b5679d..5a0dd978476 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport2.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport2.ts @@ -27,4 +27,4 @@ // @Filename: ambient.ts //// declare module "fake-module/other" -verify.completionsAt(["import_as0", "import_equals0", "require0"], ["other", "repeated"], { isNewIdentifierLocation: true }) +verify.completions({ marker: ["import_as0", "import_equals0", "require0"], exact: ["other", "repeated"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport3.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport3.ts index 450b7fb0062..a2fbca92b17 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport3.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport3.ts @@ -27,4 +27,8 @@ // @Filename: node_modules/fake-module/repeated.jsx //// /*repeatedjsx*/ -verify.completionsAt(["import_as0", "import_equals0", "require0"], ["dts", "js", "jsx", "repeated", "ts", "tsx"], { isNewIdentifierLocation: true }); +verify.completions({ + marker: ["import_as0", "import_equals0", "require0"], + exact: ["dts", "js", "jsx", "repeated", "ts", "tsx"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport4.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport4.ts index e35ffa19924..7c8692e4e7e 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport4.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport4.ts @@ -23,7 +23,7 @@ //// verify.completions({ - marker: test.markerNames(), + marker: test.markers(), exact: ["fake-module3", "fake-module2", "fake-module"], isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport7.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport7.ts index f12c87c5fc3..fa144081001 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport7.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport7.ts @@ -18,7 +18,7 @@ //// verify.completions({ - marker: test.markerNames(), + marker: test.markers(), exact: ["module", "module-from-node"], isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts index 58b3f6695a6..20bb304d125 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport8.ts @@ -41,7 +41,7 @@ //// export var z = 5; verify.completions({ - marker: test.markerNames(), + marker: test.markers(), exact: ["2test", "prefix", "prefix-only", "0test", "1test"], isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport9.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport9.ts index 3a5f28b0f0c..cdb08070db7 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport9.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport9.ts @@ -25,4 +25,4 @@ // @Filename: some/other/path.ts //// export var y = 10; -verify.completions({ marker: test.markerNames(), exact: ["module1", "module2"], isNewIdentifierLocation: true }); +verify.completions({ marker: test.markers(), exact: ["module1", "module2"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings1.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings1.ts index 687103629e2..7329c5828b0 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings1.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings1.ts @@ -23,13 +23,4 @@ // @Filename: my_other_typings/module-z/index.d.ts //// export var z = 9; - -const kinds = ["types_ref", "import_as", "import_equals", "require"]; - -for (const kind of kinds) { - goTo.marker(kind + "0"); - verify.completionListContains("module-x"); - verify.completionListContains("module-y"); - verify.completionListContains("module-z"); - verify.not.completionListItemsCountIsGreaterThan(3); -} +verify.completions({ marker: test.markers(), exact: ["module-x", "module-y", "module-z"], isNewIdentifierLocation: true }) diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings2.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings2.ts index 12a4fcf243f..cea75b50c45 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings2.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings2.ts @@ -21,12 +21,4 @@ // @Filename: my_other_typings/module-z/index.d.ts //// export var z = 9; - -const kinds = ["types_ref", "import_as", "import_equals", "require"]; - -for (const kind of kinds) { - goTo.marker(kind + "0"); - verify.completionListContains("module-x"); - verify.completionListContains("module-z"); - verify.not.completionListItemsCountIsGreaterThan(2); -} +verify.completions({ marker: test.markers(), exact: ["module-x", "module-z"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings3.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings3.ts index 5f56de77984..1e998c6e966 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings3.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImportTypings3.ts @@ -18,4 +18,8 @@ // @Filename: package.json //// { "dependencies": { "@types/module-y": "latest" } } -verify.completionsAt(["types_ref0", "import_as0", "import_equals0", "require0"], ["module-x", "module-y"], { isNewIdentifierLocation: true }); +verify.completions({ + marker: ["types_ref0", "import_as0", "import_equals0", "require0"], + exact: ["module-x", "module-y"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionForStringLiteralRelativeImport4.ts b/tests/cases/fourslash/completionForStringLiteralRelativeImport4.ts index 1cfacb08838..cacb3c19174 100644 --- a/tests/cases/fourslash/completionForStringLiteralRelativeImport4.ts +++ b/tests/cases/fourslash/completionForStringLiteralRelativeImport4.ts @@ -38,7 +38,7 @@ //// verify.completions({ - marker: test.markerNames(), + marker: test.markers(), exact: ["module1", "module2", "more", "module0"], isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSFalse.ts b/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSFalse.ts index f343ce8699b..e5260281f06 100644 --- a/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSFalse.ts +++ b/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSFalse.ts @@ -22,51 +22,32 @@ // @Filename: f1.ts -//// /*f1*/ +//// // @Filename: f2.js -//// /*f2*/ +//// // @Filename: f3.d.ts -//// /*f3*/ +//// // @Filename: f4.tsx -//// /f4*/ +//// // @Filename: f5.js -//// /*f5*/ +//// // @Filename: f6.jsx -//// /*f6*/ +//// // @Filename: f7.ts -//// /*f7*/ +//// // @Filename: d1/f8.ts -//// /*d1f1*/ +//// // @Filename: d1/f9.ts -//// /*d1f9*/ +//// // @Filename: d2/f10.ts -//// /*d2f1*/ +//// // @Filename: d2/f11.ts -//// /*d2f11*/ +//// const kinds = ["import_as", "import_equals", "require"]; - -for (const kind of kinds) { - goTo.marker(kind + "0"); - verify.completionListIsEmpty(); - - goTo.marker(kind + "1"); - verify.completionListContains("f1"); - verify.completionListContains("f3"); - verify.completionListContains("f4"); - verify.completionListContains("f7"); - verify.completionListContains("d1"); - verify.completionListContains("d2"); - verify.not.completionListItemsCountIsGreaterThan(6); - - goTo.marker(kind + "2"); - verify.completionListContains("f8"); - verify.completionListContains("f9"); - verify.not.completionListItemsCountIsGreaterThan(2); - - goTo.marker(kind + "3"); - verify.completionListContains("f10"); - verify.completionListContains("f11"); - verify.completionListContains("d3"); - verify.not.completionListItemsCountIsGreaterThan(3); -} \ No newline at end of file +verify.completions( + { marker: kinds.map(k => k + "0"), exact: [], isNewIdentifierLocation: true }, + { marker: kinds.map(k => k + "1"), exact: ["f1", "f3", "f4", "f7", "d1", "d2"], isNewIdentifierLocation: true }, + { marker: kinds.map(k => k + "2"), exact: ["f8", "f9"], isNewIdentifierLocation: true }, + { marker: kinds.map(k => k + "3"), exact: ["f10", "f11", "d3"], isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSTrue.ts b/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSTrue.ts index 6eab9aaeca2..b9fe6bebdf7 100644 --- a/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSTrue.ts +++ b/tests/cases/fourslash/completionForStringLiteralRelativeImportAllowJSTrue.ts @@ -15,34 +15,24 @@ //// var foo6 = require("./f/*require1*/ // @Filename: f1.ts -//// /f1*/ +//// // @Filename: f2.js -//// /*f2*/ +//// // @Filename: f3.d.ts -//// /*f3*/ +//// // @Filename: f4.tsx -//// /*f4*/ +//// // @Filename: f5.js -//// /*f5*/ +//// // @Filename: f6.jsx -//// /*f6*/ +//// // @Filename: g1.ts -//// /*g1*/ +//// // @Filename: g2.js -//// /*g2*/ -const kinds = ["import_as", "import_equals", "require"]; +//// -for (const kind of kinds) { - for(let i = 0; i < 2; ++i) { - goTo.marker(kind + i); - verify.completionListContains("f1"); - verify.completionListContains("f2"); - verify.completionListContains("f3"); - verify.completionListContains("f4"); - verify.completionListContains("f5"); - verify.completionListContains("f6"); - verify.completionListContains("g1"); - verify.completionListContains("g2"); - verify.not.completionListItemsCountIsGreaterThan(8); - } -} \ No newline at end of file +verify.completions({ + marker: test.markers(), + exact: ["f1", "f2", "f3", "f4", "f5", "f6", "g1", "g2"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts b/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts index 4815e52edf5..8571f483eeb 100644 --- a/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts +++ b/tests/cases/fourslash/completionForStringLiteralWithDynamicImport.ts @@ -20,7 +20,9 @@ // @Filename: my_typings/some-module/index.d.ts //// export var x = 9; -verify.completionsAt("0", ["someFile1", "my_typings", "sub"], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["someFile2"], { isNewIdentifierLocation: true }); -verify.completionsAt("2", [{ name: "some-module", replacementSpan: test.ranges()[0] }], { isNewIdentifierLocation: true }); -verify.completionsAt("3", ["fourslash"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: "0", exact: ["someFile1", "my_typings", "sub"], isNewIdentifierLocation: true }, + { marker: "1", exact: "someFile2", isNewIdentifierLocation: true }, + { marker: "2", exact: { name: "some-module", replacementSpan: test.ranges()[0] }, isNewIdentifierLocation: true }, + { marker: "3", exact: "fourslash", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionForStringLiteral_details.ts b/tests/cases/fourslash/completionForStringLiteral_details.ts index 547c1fc5f81..f7ef83f6f39 100644 --- a/tests/cases/fourslash/completionForStringLiteral_details.ts +++ b/tests/cases/fourslash/completionForStringLiteral_details.ts @@ -17,12 +17,14 @@ ////declare const o: I; ////o["/*prop*/"]; -goTo.marker("path"); -verify.completionListContains("other", "other", "", "script"); - -goTo.marker("type"); -verify.completionListContains("a", "a", "", "string"); - -goTo.marker("prop"); -verify.completionListContains("x", "(property) I.x: number", "Prop doc", "property"); -verify.completionListContains("m", "(method) I.m(): void", "Method doc", "method"); +verify.completions( + { marker: "path", includes: { name: "other", text: "other", kind: "script" }, isNewIdentifierLocation: true }, + { marker: "type", exact: { name: "a", text: "a", kind: "string" } }, + { + marker: "prop", + exact: [ + { name: "x", text: "(property) I.x: number", documentation: "Prop doc", kind: "property" }, + { name: "m", text: "(method) I.m(): void", documentation: "Method doc", kind: "method" }, + ], + }, +); diff --git a/tests/cases/fourslash/completionImportMeta.ts b/tests/cases/fourslash/completionImportMeta.ts index cac84c2c82f..45b6f889a11 100644 --- a/tests/cases/fourslash/completionImportMeta.ts +++ b/tests/cases/fourslash/completionImportMeta.ts @@ -2,5 +2,4 @@ ////import./**/ -goTo.marker(""); -verify.completionListContains("meta"); \ No newline at end of file +verify.completions({ marker: "", exact: "meta" }); diff --git a/tests/cases/fourslash/completionInAugmentedClassModule.ts b/tests/cases/fourslash/completionInAugmentedClassModule.ts index 18ea0dbbcb6..2ea90b2e0f2 100644 --- a/tests/cases/fourslash/completionInAugmentedClassModule.ts +++ b/tests/cases/fourslash/completionInAugmentedClassModule.ts @@ -4,5 +4,4 @@ ////module m3f { export interface I { foo(): void } } ////var x: m3f./**/ -goTo.marker(); -verify.not.completionListContains("foo"); \ No newline at end of file +verify.completions({ marker: "", exact: "I" }); diff --git a/tests/cases/fourslash/completionInFunctionLikeBody.ts b/tests/cases/fourslash/completionInFunctionLikeBody.ts index 76e1249e760..95407b8f018 100644 --- a/tests/cases/fourslash/completionInFunctionLikeBody.ts +++ b/tests/cases/fourslash/completionInFunctionLikeBody.ts @@ -12,35 +12,12 @@ //// } //// /*4*/ //// } - - -goTo.marker("1"); -verify.completionListContains("async", "async", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("public", "public", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("private", "private", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("protected", "protected", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("constructor", "constructor", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("readonly", "readonly", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("static", "static", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("abstract", "abstract", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("get", "get", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("set", "set", /*documentation*/ undefined, "keyword"); - -goTo.marker("2"); -verify.completionListContains("async", "async", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("public", "public", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("private", "private", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("protected", "protected", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("constructor", "constructor", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("readonly", "readonly", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("static", "static", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("abstract", "abstract", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("get", "get", /*documentation*/ undefined, "keyword"); -verify.not.completionListContains("set", "set", /*documentation*/ undefined, "keyword"); - -goTo.marker("3"); -verify.completionListContainsClassElementKeywords(); - -goTo.marker("4"); -verify.completionListContainsClassElementKeywords(); +verify.completions( + { + marker: ["1", "2"], + includes: "async", + excludes: ["public", "private", "protected", "constructor", "readonly", "static", "abstract", "get", "set"], + }, + { marker: ["3", "4"], exact: completion.classElementKeywords, isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionInIncompleteCallExpression.ts b/tests/cases/fourslash/completionInIncompleteCallExpression.ts index eda8cf14378..eb24d0abce6 100644 --- a/tests/cases/fourslash/completionInIncompleteCallExpression.ts +++ b/tests/cases/fourslash/completionInIncompleteCallExpression.ts @@ -3,7 +3,5 @@ ////var array = [1, 2, 4] ////function a4(x, y, z) { } ////a4(.../**/ - -goTo.marker(); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: completion.globalsPlus(["a4", "array"]) }); diff --git a/tests/cases/fourslash/completionInJSDocFunctionNew.ts b/tests/cases/fourslash/completionInJSDocFunctionNew.ts index 2d2b47bad3f..8cf8502aa20 100644 --- a/tests/cases/fourslash/completionInJSDocFunctionNew.ts +++ b/tests/cases/fourslash/completionInJSDocFunctionNew.ts @@ -5,5 +5,4 @@ /////** @type {function (new: string, string): string} */ ////var f = function () { return new/**/; } -goTo.marker(); -verify.completionListContains('new'); +verify.completions({ marker: "", includes: "new" }); diff --git a/tests/cases/fourslash/completionInJSDocFunctionThis.ts b/tests/cases/fourslash/completionInJSDocFunctionThis.ts index 2eedbc8e062..4f732fdcec1 100644 --- a/tests/cases/fourslash/completionInJSDocFunctionThis.ts +++ b/tests/cases/fourslash/completionInJSDocFunctionThis.ts @@ -4,5 +4,4 @@ /////** @type {function (this: string, string): string} */ ////var f = function (s) { return this/**/; } -goTo.marker(); -verify.completionListContains('this') +verify.completions({ marker: "", includes: "this" }); diff --git a/tests/cases/fourslash/completionInJsDoc.ts b/tests/cases/fourslash/completionInJsDoc.ts index 1a9170ca950..ef438b8f4be 100644 --- a/tests/cases/fourslash/completionInJsDoc.ts +++ b/tests/cases/fourslash/completionInJsDoc.ts @@ -54,56 +54,10 @@ //// //// /** @param /*16*/ */ -goTo.marker('1'); -verify.completionListContains("constructor"); -verify.completionListContains("param"); -verify.completionListContains("type"); -verify.completionListContains("method"); -verify.completionListContains("template"); - -goTo.marker('2'); -verify.completionListContains("constructor"); -verify.completionListContains("param"); -verify.completionListContains("type"); - -goTo.marker('3'); -verify.completionListIsEmpty(); - -goTo.marker('4'); -verify.completionListContains('number'); - -goTo.marker('5'); -verify.completionListContains('number'); - -goTo.marker('6'); -verify.completionListIsEmpty(); - -goTo.marker('7'); -verify.completionListIsEmpty(); - -goTo.marker('8'); -verify.completionListContains('number'); - -goTo.marker('9'); -verify.completionListContains("@argument"); - -goTo.marker('10'); -verify.completionListContains("@returns"); - -goTo.marker('11'); -verify.completionListContains("@argument"); - -goTo.marker('12'); -verify.completionListContains("@constructor"); - -goTo.marker('13'); -verify.completionListContains("@param"); - -goTo.marker('14'); -verify.completionListIsEmpty(); - -goTo.marker('15'); -verify.completionListIsEmpty(); - -goTo.marker('16'); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions( + { marker: ["1", "2"], includes: ["constructor", "param", "type", "method", "template"] }, + { marker: ["3", "15", "16"], exact: [] }, + { marker: ["4", "5", "8"], includes: "number" }, + { marker: ["6", "7", "14"], exact: undefined }, + { marker: ["9", "10", "11", "12", "13"], includes: ["@argument", "@returns"] }, +); diff --git a/tests/cases/fourslash/completionInJsDocQualifiedNames.ts b/tests/cases/fourslash/completionInJsDocQualifiedNames.ts index 0de3ad0d21c..f5ce027f131 100644 --- a/tests/cases/fourslash/completionInJsDocQualifiedNames.ts +++ b/tests/cases/fourslash/completionInJsDocQualifiedNames.ts @@ -11,5 +11,4 @@ /////** @type {Foo./**/} */ ////const x = 0; -goTo.marker(); -verify.completionListContains("T", "type T = number", "tee", "type"); +verify.completions({ marker: "", includes: { name: "T", text: "type T = number", documentation: "tee", kind: "type" } }); diff --git a/tests/cases/fourslash/completionInNamedImportLocation.ts b/tests/cases/fourslash/completionInNamedImportLocation.ts index 596de652cc3..85db087f11b 100644 --- a/tests/cases/fourslash/completionInNamedImportLocation.ts +++ b/tests/cases/fourslash/completionInNamedImportLocation.ts @@ -12,12 +12,7 @@ ////import { x, /*2*/ } from "./file"; goTo.file("a.ts"); -goTo.marker('1'); -verify.completionListContains("x", "var x: number"); -verify.completionListContains("y", "var y: number"); -verify.not.completionListContains("C"); - -goTo.marker('2'); -verify.not.completionListContains("x", "var x: number"); -verify.completionListContains("y", "var y: number"); -verify.not.completionListContains("C"); \ No newline at end of file +verify.completions( + { marker: "1", exact: [{ name: "x", text: "var x: number" }, { name: "y", text: "var y: number" }] }, + { marker: "2", exact: [{ name: "y", text: "var y: number" }] }, +); diff --git a/tests/cases/fourslash/completionInTypeOf1.ts b/tests/cases/fourslash/completionInTypeOf1.ts index 87d267cee2f..87d7e99e135 100644 --- a/tests/cases/fourslash/completionInTypeOf1.ts +++ b/tests/cases/fourslash/completionInTypeOf1.ts @@ -5,8 +5,5 @@ ////} ////var x: typeof m1c./*1*/; -goTo.marker('1'); - // No completion because m1c is not an instantiated module. -verify.not.completionListContains('I'); -verify.not.completionListContains('foo'); \ No newline at end of file +verify.completions({ marker: "1", exact: undefined }); diff --git a/tests/cases/fourslash/completionInTypeOf2.ts b/tests/cases/fourslash/completionInTypeOf2.ts index e242c9db0db..a76b2e853d1 100644 --- a/tests/cases/fourslash/completionInTypeOf2.ts +++ b/tests/cases/fourslash/completionInTypeOf2.ts @@ -5,6 +5,4 @@ ////} ////var x: typeof m1c./*1*/; -goTo.marker('1'); -verify.completionListContains('C'); -verify.not.completionListContains('foo'); +verify.completions({ marker: "1", exact: "C" }); diff --git a/tests/cases/fourslash/completionInfoWithExplicitTypeArguments.ts b/tests/cases/fourslash/completionInfoWithExplicitTypeArguments.ts index 6951614298e..3fc5052fcff 100644 --- a/tests/cases/fourslash/completionInfoWithExplicitTypeArguments.ts +++ b/tests/cases/fourslash/completionInfoWithExplicitTypeArguments.ts @@ -11,12 +11,4 @@ ////declare function g(x: keyof T, y: number): void; ////g("/*g*/"); -goTo.marker("f"); -verify.completionListCount(2); -verify.completionListContains("x"); -verify.completionListContains("y"); - -goTo.marker("g"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListCount(2); +verify.completions({ marker: test.markers(), exact: ["x", "y"] }); diff --git a/tests/cases/fourslash/completionInsideFunctionContainsArguments.ts b/tests/cases/fourslash/completionInsideFunctionContainsArguments.ts index 903253b1a09..0b0a6c0d52f 100644 --- a/tests/cases/fourslash/completionInsideFunctionContainsArguments.ts +++ b/tests/cases/fourslash/completionInsideFunctionContainsArguments.ts @@ -10,13 +10,7 @@ ////} ////let g = () => /*5*/ -goTo.marker('1'); -verify.completionListContains("arguments"); -goTo.marker('2'); -verify.not.completionListContains("arguments"); -goTo.marker('3'); -verify.completionListContains("arguments"); -goTo.marker('4'); -verify.completionListContains("arguments"); -goTo.marker('5'); -verify.not.completionListContains("arguments"); \ No newline at end of file +verify.completions( + { marker: ["1", "3", "4"], includes: "arguments" }, + { marker: ["2", "5"], excludes: "arguments" }, +); diff --git a/tests/cases/fourslash/completionListAfterAnyType.ts b/tests/cases/fourslash/completionListAfterAnyType.ts index f7222675a0f..6eebc090e83 100644 --- a/tests/cases/fourslash/completionListAfterAnyType.ts +++ b/tests/cases/fourslash/completionListAfterAnyType.ts @@ -3,11 +3,9 @@ //// declare class myString { //// charAt(pos: number): string; //// } -//// +//// //// function bar(a: myString) { //// var x: any = a./**/ //// } -goTo.marker(); -verify.completionListContains("charAt"); -verify.completionListCount(1); +verify.completions({ marker: "", exact: "charAt" }); diff --git a/tests/cases/fourslash/completionListAfterClassExtends.ts b/tests/cases/fourslash/completionListAfterClassExtends.ts index 15a3e261768..a9892c3eae6 100644 --- a/tests/cases/fourslash/completionListAfterClassExtends.ts +++ b/tests/cases/fourslash/completionListAfterClassExtends.ts @@ -10,7 +10,4 @@ ////function Blah(x: Bar.Bleah) { ////} -goTo.marker(); -verify.completionListContains("Bar"); -verify.completionListContains("Bleah"); -verify.completionListContains("Foo"); \ No newline at end of file +verify.completions({ marker: "", includes: ["Bar", "Bleah", "Foo"] }); diff --git a/tests/cases/fourslash/completionListAfterFunction.ts b/tests/cases/fourslash/completionListAfterFunction.ts index 140c5e2e363..1898534c9c0 100644 --- a/tests/cases/fourslash/completionListAfterFunction.ts +++ b/tests/cases/fourslash/completionListAfterFunction.ts @@ -12,14 +12,9 @@ ////// inside the function ////function f4(d: number) { /*4*/} -goTo.marker("1"); -verify.not.completionListContains("a"); - -goTo.marker("2"); -verify.completionListContains("b"); - -goTo.marker("3"); -verify.not.completionListContains("c"); - -goTo.marker("4"); -verify.completionListContains("d"); +verify.completions( + { marker: "1", excludes: "a" }, + { marker: "2", includes: "b" }, + { marker: "3", excludes: "c" }, + { marker: "4", includes: "d" }, +); diff --git a/tests/cases/fourslash/completionListAfterFunction2.ts b/tests/cases/fourslash/completionListAfterFunction2.ts index 0dfbd4fb461..7abd3dc4dab 100644 --- a/tests/cases/fourslash/completionListAfterFunction2.ts +++ b/tests/cases/fourslash/completionListAfterFunction2.ts @@ -5,10 +5,9 @@ //// ////declare var f1: (b: number, b2: /*2*/) => void; -goTo.marker("1"); -verify.not.completionListContains("a"); - -goTo.marker("2"); -verify.not.completionListContains("b"); +verify.completions( + { marker: "1", excludes: "a" }, + { marker: "2", excludes: "b" }, +); edit.insert("typeof "); -verify.completionListContains("b"); +verify.completions({ includes: "b" }); diff --git a/tests/cases/fourslash/completionListAfterFunction3.ts b/tests/cases/fourslash/completionListAfterFunction3.ts index 575351ea648..4bc7ae08a89 100644 --- a/tests/cases/fourslash/completionListAfterFunction3.ts +++ b/tests/cases/fourslash/completionListAfterFunction3.ts @@ -5,8 +5,7 @@ //// ////var x2 = (b: number) => {/*2*/ }; -goTo.marker("1"); -verify.not.completionListContains("a"); - -goTo.marker("2"); -verify.completionListContains("b"); +verify.completions( + { marker: "1", excludes: "a" }, + { marker: "2", includes: "b" }, +); diff --git a/tests/cases/fourslash/completionListAfterInvalidCharacter.ts b/tests/cases/fourslash/completionListAfterInvalidCharacter.ts index ece28e5e3a0..b3f22375613 100644 --- a/tests/cases/fourslash/completionListAfterInvalidCharacter.ts +++ b/tests/cases/fourslash/completionListAfterInvalidCharacter.ts @@ -4,8 +4,7 @@ ////module testModule { //// export var foo = 1; ////} -////@ +////@ ////testModule./**/ -goTo.marker(); -verify.completionListContains("foo"); +verify.completions({ marker: "", exact: "foo" }); diff --git a/tests/cases/fourslash/completionListAfterNumericLiteral.ts b/tests/cases/fourslash/completionListAfterNumericLiteral.ts index 549c048a635..4ef879cc485 100644 --- a/tests/cases/fourslash/completionListAfterNumericLiteral.ts +++ b/tests/cases/fourslash/completionListAfterNumericLiteral.ts @@ -1,43 +1,30 @@ /// // @Filename: f1.ts -////0./*dotOnNumberExrpressions1*/ +////0./*dotOnNumberExpressions1*/ // @Filename: f2.ts -////0.0./*dotOnNumberExrpressions2*/ +////0.0./*dotOnNumberExpressions2*/ // @Filename: f3.ts -////0.0.0./*dotOnNumberExrpressions3*/ +////0.0.0./*dotOnNumberExpressions3*/ // @Filename: f4.ts -////0./** comment *//*dotOnNumberExrpressions4*/ +////0./** comment *//*dotOnNumberExpressions4*/ // @Filename: f5.ts -////(0)./*validDotOnNumberExrpressions1*/ +////(0)./*validDotOnNumberExpressions1*/ // @Filename: f6.ts -////(0.)./*validDotOnNumberExrpressions2*/ +////(0.)./*validDotOnNumberExpressions2*/ // @Filename: f7.ts -////(0.0)./*validDotOnNumberExrpressions3*/ +////(0.0)./*validDotOnNumberExpressions3*/ -goTo.marker("dotOnNumberExrpressions1"); -verify.completionListIsEmpty(); - -goTo.marker("dotOnNumberExrpressions2"); -verify.completionListContains("toExponential"); - -goTo.marker("dotOnNumberExrpressions3"); -verify.completionListContains("toExponential"); - -goTo.marker("dotOnNumberExrpressions4"); -verify.completionListIsEmpty(); - -goTo.marker("validDotOnNumberExrpressions1"); -verify.completionListContains("toExponential"); - -goTo.marker("validDotOnNumberExrpressions2"); -verify.completionListContains("toExponential"); - -goTo.marker("validDotOnNumberExrpressions3"); -verify.completionListContains("toExponential"); +verify.completions( + { marker: ["dotOnNumberExpressions1", "dotOnNumberExpressions4"], exact: undefined }, + { + marker: ["dotOnNumberExpressions2", "dotOnNumberExpressions3", "validDotOnNumberExpressions1", "validDotOnNumberExpressions2", "validDotOnNumberExpressions3"], + includes: "toExponential" + }, +); diff --git a/tests/cases/fourslash/completionListAfterNumericLiteral1.ts b/tests/cases/fourslash/completionListAfterNumericLiteral1.ts index cf8b5d41e98..1541989c9c8 100644 --- a/tests/cases/fourslash/completionListAfterNumericLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterNumericLiteral1.ts @@ -2,5 +2,4 @@ ////5../**/ -goTo.marker(); -verify.completionListContains("toFixed"); \ No newline at end of file +verify.completions({ marker: "", exact: ["toString", "toFixed", "toExponential", "toPrecision", "valueOf", "toLocaleString"] }); diff --git a/tests/cases/fourslash/completionListAfterObjectLiteral1.ts b/tests/cases/fourslash/completionListAfterObjectLiteral1.ts index 7296ce057b4..1b6d2807933 100644 --- a/tests/cases/fourslash/completionListAfterObjectLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterObjectLiteral1.ts @@ -2,6 +2,4 @@ ////var v = { x: 4, y: 3 }./**/ -goTo.marker(); -verify.not.completionListContains('a'); -verify.completionListContains('x'); \ No newline at end of file +verify.completions({ marker: "", exact: ["x", "y"] }); diff --git a/tests/cases/fourslash/completionListAfterPropertyName.ts b/tests/cases/fourslash/completionListAfterPropertyName.ts index c83b16c9741..652526f3af7 100644 --- a/tests/cases/fourslash/completionListAfterPropertyName.ts +++ b/tests/cases/fourslash/completionListAfterPropertyName.ts @@ -70,19 +70,29 @@ //// constructor(public a, /*afterConstructorParameterComma*/ ////} -for (const marker of ["afterPropertyName", - "inMethodParameter", "atMethodParameter", "afterMethodParameter", - "afterMethodParameterBeforeComma", "afterMethodParameterComma", - "afterConstructorParameter", "afterConstructorParameterBeforeComma"]) { - - goTo.marker(marker); - verify.completionListIsEmpty(); -} - -for (const marker of ["inConstructorParameter", "inConstructorParameterAfterModifier", - "atConstructorParameter", "atConstructorParameterModifier", "atConstructorParameterAfterModifier", - "afterConstructorParameterComma"]) { - goTo.marker(marker); - verify.completionListContainsConstructorParameterKeywords(); - verify.completionListCount(verify.allowedConstructorParameterKeywords.length); -} \ No newline at end of file +verify.completions( + { + marker:[ + "afterPropertyName", + "inMethodParameter", + "atMethodParameter", + "afterMethodParameter", + "afterMethodParameterBeforeComma", + "afterMethodParameterComma", + "afterConstructorParameter", + ], + exact: undefined, + }, + { + marker: [ + "inConstructorParameter", + "inConstructorParameterAfterModifier", + "atConstructorParameter", + "atConstructorParameterModifier", + "atConstructorParameterAfterModifier", + "afterConstructorParameterComma", + ], + exact: completion.constructorParameterKeywords, + isNewIdentifierLocation: true, + }, +); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts index 759a3f9c2a4..8572229531a 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral01.ts @@ -3,6 +3,4 @@ ////let v = 100; /////a/./**/ -goTo.marker(); -verify.not.completionListContains('v'); -verify.completionListContains('compile'); \ No newline at end of file +verify.completions({ marker: "", exact: ["exec", "test", "source", "global", "ignoreCase", "multiline", "lastIndex", "compile"] }); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral02.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral02.ts index 2719d747d58..e791f6d386a 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral02.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral02.ts @@ -5,6 +5,4 @@ // Should get nothing at the marker since it's // going to be considered part of the regex flags. - -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral03.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral03.ts index 7c0e4d51446..2e6c5f7c86f 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral03.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral03.ts @@ -7,5 +7,4 @@ // Should not be blocked since there is a // newline separating us from the regex flags. -goTo.marker(); -verify.completionListContains("v"); \ No newline at end of file +verify.completions({ marker: "", includes: "v" }); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral04.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral04.ts index 06f31b8175b..877ae3b62aa 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral04.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral04.ts @@ -6,5 +6,4 @@ // Should not be blocked since there is a // space separating us from the regex flags. -goTo.marker(); -verify.completionListContains("v"); \ No newline at end of file +verify.completions({ marker: "", includes: "v" }); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral05.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral05.ts index 7ac0d1cd71c..4032912481a 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral05.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral05.ts @@ -5,6 +5,4 @@ // Should get nothing at the marker since it's // going to be considered part of the regex flags. - -goTo.marker(); -verify.completionListIsEmpty() \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts index 465c676c714..22fdf36adbb 100644 --- a/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts +++ b/tests/cases/fourslash/completionListAfterRegularExpressionLiteral1.ts @@ -2,6 +2,4 @@ /////a/./**/ -goTo.marker(); -verify.not.completionListContains('alert'); -verify.completionListContains('compile'); \ No newline at end of file +verify.completions({ marker: "", exact: ["exec", "test", "source", "global", "ignoreCase", "multiline", "lastIndex", "compile"] }); diff --git a/tests/cases/fourslash/completionListAfterSlash.ts b/tests/cases/fourslash/completionListAfterSlash.ts index f9a0b69afdf..b1ae2330b7b 100644 --- a/tests/cases/fourslash/completionListAfterSlash.ts +++ b/tests/cases/fourslash/completionListAfterSlash.ts @@ -3,6 +3,5 @@ ////var a = 0; ////a/./**/ -goTo.marker(); // should not crash -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAfterSpreadOperator01.ts b/tests/cases/fourslash/completionListAfterSpreadOperator01.ts index 48a50124daf..903953d5096 100644 --- a/tests/cases/fourslash/completionListAfterSpreadOperator01.ts +++ b/tests/cases/fourslash/completionListAfterSpreadOperator01.ts @@ -3,5 +3,4 @@ ////let v = [1,2,3,4]; ////let x = [.../**/ -goTo.marker(); -verify.completionListContains("v"); \ No newline at end of file +verify.completions({ marker: "", includes: "v" }); diff --git a/tests/cases/fourslash/completionListAfterStringLiteralTypeWithNoSubstitutionTemplateLiteral.ts b/tests/cases/fourslash/completionListAfterStringLiteralTypeWithNoSubstitutionTemplateLiteral.ts index c5deac5123e..d44b1d04bbe 100644 --- a/tests/cases/fourslash/completionListAfterStringLiteralTypeWithNoSubstitutionTemplateLiteral.ts +++ b/tests/cases/fourslash/completionListAfterStringLiteralTypeWithNoSubstitutionTemplateLiteral.ts @@ -3,6 +3,4 @@ ////let count: 'one' | 'two'; ////count = `/**/` -goTo.marker(); -verify.completionListContains('one'); -verify.completionListContains('two'); +verify.completions({ marker: "", exact: ["one", "two"] }); diff --git a/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts b/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts index b57e7b84b53..e742c722d3e 100644 --- a/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts +++ b/tests/cases/fourslash/completionListAndMemberListOnCommentedDot.ts @@ -13,5 +13,4 @@ //////Test for comment //////c./**/ -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAndMemberListOnCommentedLine.ts b/tests/cases/fourslash/completionListAndMemberListOnCommentedLine.ts index 96eac09b6ff..7d1543d3e65 100644 --- a/tests/cases/fourslash/completionListAndMemberListOnCommentedLine.ts +++ b/tests/cases/fourslash/completionListAndMemberListOnCommentedLine.ts @@ -3,5 +3,4 @@ ////// /**/ ////var -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts b/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts index a40c68e8b15..715897abd15 100644 --- a/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts +++ b/tests/cases/fourslash/completionListAndMemberListOnCommentedWhiteSpace.ts @@ -13,6 +13,4 @@ //////Test for comment //////c. /**/ -goTo.marker(); -verify.completionListIsEmpty(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtBeginningOfFile01.ts b/tests/cases/fourslash/completionListAtBeginningOfFile01.ts index f811fec4c67..f6e0676d976 100644 --- a/tests/cases/fourslash/completionListAtBeginningOfFile01.ts +++ b/tests/cases/fourslash/completionListAtBeginningOfFile01.ts @@ -6,8 +6,4 @@ //// A, B, C ////} -goTo.marker("1"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); -verify.completionListContains("E"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["x", "y", "z", "E"] }); diff --git a/tests/cases/fourslash/completionListAtBeginningOfIdentifierInArrowFunction01.ts b/tests/cases/fourslash/completionListAtBeginningOfIdentifierInArrowFunction01.ts index 0562a5a4bd3..ebcbfc754f4 100644 --- a/tests/cases/fourslash/completionListAtBeginningOfIdentifierInArrowFunction01.ts +++ b/tests/cases/fourslash/completionListAtBeginningOfIdentifierInArrowFunction01.ts @@ -2,5 +2,4 @@ ////xyz => /*1*/x -goTo.marker("1"); -verify.completionListContains("xyz"); \ No newline at end of file +verify.completions({ marker: "1", includes: "xyz" }); diff --git a/tests/cases/fourslash/completionListAtDeclarationOfParameterType.ts b/tests/cases/fourslash/completionListAtDeclarationOfParameterType.ts index 94de51cc9a3..708bd9fcd64 100644 --- a/tests/cases/fourslash/completionListAtDeclarationOfParameterType.ts +++ b/tests/cases/fourslash/completionListAtDeclarationOfParameterType.ts @@ -10,5 +10,4 @@ ////function Blah(x: /**/Bar.Bleah) { ////} -goTo.marker(); -verify.completionListContains("Bar"); \ No newline at end of file +verify.completions({ marker: "", includes: "Bar" }); diff --git a/tests/cases/fourslash/completionListAtEOF.ts b/tests/cases/fourslash/completionListAtEOF.ts index e1b210281cb..6871d906176 100644 --- a/tests/cases/fourslash/completionListAtEOF.ts +++ b/tests/cases/fourslash/completionListAtEOF.ts @@ -3,10 +3,10 @@ ////var a; goTo.eof(); -verify.completionListContains("a"); +verify.completions({ includes: "a" }); edit.insertLine(""); -verify.completionListContains("a"); +verify.completions({ includes: "a" }); edit.insertLine(""); -verify.completionListContains("a"); +verify.completions({ includes: "a" }); diff --git a/tests/cases/fourslash/completionListAtEOF1.ts b/tests/cases/fourslash/completionListAtEOF1.ts index 3a7cfe95316..693ad936eb2 100644 --- a/tests/cases/fourslash/completionListAtEOF1.ts +++ b/tests/cases/fourslash/completionListAtEOF1.ts @@ -3,4 +3,4 @@ //// if(0 === ''. goTo.eof(); -verify.completionListContains("charAt"); +verify.completions({ includes: "charAt" }); diff --git a/tests/cases/fourslash/completionListAtEOF2.ts b/tests/cases/fourslash/completionListAtEOF2.ts index 8ba6a9d8e65..01f05b3b61f 100644 --- a/tests/cases/fourslash/completionListAtEOF2.ts +++ b/tests/cases/fourslash/completionListAtEOF2.ts @@ -8,4 +8,4 @@ ////var p = x/*1*/ -goTo.marker("1"); -verify.completionListContains("xyz"); \ No newline at end of file +verify.completions({ marker: "1", includes: "xyz" }); diff --git a/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction02.ts b/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction02.ts index 32a11f9b151..73cd0c29be9 100644 --- a/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction02.ts +++ b/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction02.ts @@ -2,9 +2,8 @@ ////(d, defaultIsAnInvalidParameterName) => d/*1*/ -goTo.marker("1"); -verify.completionListContains("d"); -verify.completionListContains("defaultIsAnInvalidParameterName"); - -// This should probably stop working in the future. -verify.completionListContains("default", "default", /*documentation*/ undefined, "keyword"); \ No newline at end of file +verify.completions({ + marker: "1", + // TODO: should not include 'default' keyword at an expression location + includes: ["d", "defaultIsAnInvalidParameterName", "default"] +}); diff --git a/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction03.ts b/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction03.ts index 15acdc20456..0487107d3af 100644 --- a/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction03.ts +++ b/tests/cases/fourslash/completionListAtEndOfWordInArrowFunction03.ts @@ -2,8 +2,11 @@ ////(d, defaultIsAnInvalidParameterName) => default/*1*/ -goTo.marker("1"); -verify.completionListContains("defaultIsAnInvalidParameterName"); - -// This should probably stop working in the future. -verify.completionListContains("default", "default", /*documentation*/ undefined, "keyword"); \ No newline at end of file +verify.completions({ + marker: "1", + includes: [ + "defaultIsAnInvalidParameterName", + // This should probably stop working in the future. + { name: "default", text: "default", kind: "keyword" }, + ], +}); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_Generics.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_Generics.ts index 784fc8c499c..fce92a33fc8 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_Generics.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_Generics.ts @@ -11,4 +11,4 @@ ////function A verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_catch.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_catch.ts index bfbfa1bb160..4a7b35f840c 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_catch.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_catch.ts @@ -6,4 +6,4 @@ //// try {} catch(a/*catchVariable2*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_classes.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_classes.ts index 5d96c565719..189c475aa20 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_classes.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_classes.ts @@ -6,4 +6,4 @@ ////class a/*className2*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_destructuring.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_destructuring.ts index d2ecdf29426..27c7f9a4dae 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_destructuring.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_destructuring.ts @@ -16,4 +16,4 @@ //// function func2({ a, b/*parameter2*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers.ts index f0818108301..fc4b9b44417 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers.ts @@ -4,4 +4,4 @@ ////enum a { /*enumValueName1*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers2.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers2.ts index 11aa276bb5a..56ba378043e 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers2.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enumMembers2.ts @@ -3,4 +3,4 @@ ////var aa = 1; ////enum a { foo, /*enumValueName3*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enums.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enums.ts index c740218e27e..e17e37a6a7e 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enums.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_enums.ts @@ -8,4 +8,4 @@ ////var x = 0; enum /*enumName4*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_functions.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_functions.ts index 2f55f9527bc..14e5b6a55de 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_functions.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_functions.ts @@ -6,4 +6,4 @@ ////function a/*functionName2*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_interfaces.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_interfaces.ts index d4be268eb7d..bff0e4dd088 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_interfaces.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_interfaces.ts @@ -6,4 +6,4 @@ ////interface a/*interfaceName2*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_parameters.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_parameters.ts index c59b08dd70a..d69645a55c9 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_parameters.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_parameters.ts @@ -10,30 +10,31 @@ ////function testFunction(a, b/*parameterName4*/ -////class bar5{ constructor(public /*constructorParamter1*/ +////class bar5{ constructor(public /*constructorParameter1*/ -////class bar6{ constructor(public a/*constructorParamter2*/ +////class bar6{ constructor(public a/*constructorParameter2*/ -////class bar7{ constructor(protected a/*constructorParamter3*/ +////class bar7{ constructor(protected a/*constructorParameter3*/ -////class bar8{ constructor(private a/*constructorParamter4*/ +////class bar8{ constructor(private a/*constructorParameter4*/ -////class bar9{ constructor(.../*constructorParamter5*/ +////class bar9{ constructor(.../*constructorParameter5*/ -////class bar10{ constructor(...a/*constructorParamter6*/ +////class bar10{ constructor(...a/*constructorParameter6*/ -for (let i = 1; i <= 4; i++) { - goTo.marker("parameterName" + i.toString()); - verify.completionListIsEmpty(); -} - -for (let i = 1; i <= 4; i++) { - goTo.marker("constructorParamter" + i.toString()); - verify.completionListContainsConstructorParameterKeywords(); - verify.completionListCount(verify.allowedConstructorParameterKeywords.length); -} - -for (let i = 5; i <= 6; i++) { - goTo.marker("constructorParamter" + i.toString()); - verify.completionListIsEmpty(); -} +verify.completions( + { + marker: [1,2,3,4].map(i => `parameterName${i}`), + exact: undefined, + }, + { + marker: [1,2,3,4].map(i => `constructorParameter${i}`), + exact: completion.constructorParameterKeywords, + isNewIdentifierLocation: true, + }, + { + marker: [5, 6].map(i => `constructorParameter${i}`), + exact: undefined, + isNewIdentifierLocation: true, + }, +); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_properties.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_properties.ts index 3ba0df0c31d..dd57b22a9d6 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_properties.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_properties.ts @@ -30,7 +30,4 @@ //// private a/*property7*/ ////} -goTo.eachMarker(() => { - verify.not.completionListIsEmpty(); - verify.completionListAllowsNewIdentifier(); -}); \ No newline at end of file +verify.completions({ marker: test.markers(), exact: completion.classElementKeywords, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts index 9a2c9ba664a..fb49509b248 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts @@ -11,4 +11,4 @@ ////var a2, a/*varName4*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListAtInvalidLocations.ts b/tests/cases/fourslash/completionListAtInvalidLocations.ts index 171f63825f2..0185807a7e9 100644 --- a/tests/cases/fourslash/completionListAtInvalidLocations.ts +++ b/tests/cases/fourslash/completionListAtInvalidLocations.ts @@ -21,4 +21,7 @@ //// foo; //// var v10 = /reg/*inRegExp1*/ex/; -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions( + { marker: ["openString1", "openString2", "openString3"], exact: [] }, + { marker: ["inComment1", "inComment2", "inComment3", "inComment4", "inTypeAlias", "inComment5", "inRegExp1"], exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListAtNodeBoundry.ts b/tests/cases/fourslash/completionListAtNodeBoundary.ts similarity index 85% rename from tests/cases/fourslash/completionListAtNodeBoundry.ts rename to tests/cases/fourslash/completionListAtNodeBoundary.ts index 40c151e0ef4..5d321399c93 100644 --- a/tests/cases/fourslash/completionListAtNodeBoundry.ts +++ b/tests/cases/fourslash/completionListAtNodeBoundary.ts @@ -17,6 +17,4 @@ ////var a: string[]; ////var e = a.map(x => x./**/); - -goTo.marker(); -verify.completionListContains("charAt"); +verify.completions({ marker: "", includes: "charAt" }); diff --git a/tests/cases/fourslash/completionListBeforeKeyword.ts b/tests/cases/fourslash/completionListBeforeKeyword.ts index 01efe29764a..d52a311759b 100644 --- a/tests/cases/fourslash/completionListBeforeKeyword.ts +++ b/tests/cases/fourslash/completionListBeforeKeyword.ts @@ -16,11 +16,4 @@ //// export class Test3 {} ////} - -goTo.marker("TypeReference"); -verify.completionListContains("C1"); -verify.completionListContains("C2"); - -goTo.marker("ValueReference"); -verify.completionListContains("C1"); -verify.completionListContains("C2"); \ No newline at end of file +verify.completions({ marker: test.markers(), exact: ["C1", "C2"] }); diff --git a/tests/cases/fourslash/completionListBeforeNewScope01.ts b/tests/cases/fourslash/completionListBeforeNewScope01.ts index 79159744b81..4da7b6d9a41 100644 --- a/tests/cases/fourslash/completionListBeforeNewScope01.ts +++ b/tests/cases/fourslash/completionListBeforeNewScope01.ts @@ -6,6 +6,4 @@ //// let party = Math.random() < 0.99; ////} -goTo.marker("1"); -verify.not.completionListContains("param"); -verify.not.completionListContains("party"); \ No newline at end of file +verify.completions({ marker: "1", excludes: ["param", "party"] }); diff --git a/tests/cases/fourslash/completionListBeforeNewScope02.ts b/tests/cases/fourslash/completionListBeforeNewScope02.ts index 9fb1182b56e..4eccb6a10a9 100644 --- a/tests/cases/fourslash/completionListBeforeNewScope02.ts +++ b/tests/cases/fourslash/completionListBeforeNewScope02.ts @@ -6,5 +6,4 @@ //// let aaaaaa = 10; ////} -goTo.marker("1"); -verify.not.completionListContains("aaaaa"); \ No newline at end of file +verify.completions({ marker: "1", excludes: "aaaaaa" }); diff --git a/tests/cases/fourslash/completionListBuilderLocations_Modules.ts b/tests/cases/fourslash/completionListBuilderLocations_Modules.ts index 0552e540a7e..a98d65e255d 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_Modules.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_Modules.ts @@ -5,8 +5,7 @@ ////module A./*moduleName2*/ -goTo.marker("moduleName1"); -verify.not.completionListIsEmpty(); - -goTo.marker("moduleName2"); -verify.completionListIsEmpty(); +verify.completions( + { marker: "moduleName1", exact: completion.globals, isNewIdentifierLocation: true }, + { marker: "moduleName2", exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListBuilderLocations_VariableDeclarations.ts b/tests/cases/fourslash/completionListBuilderLocations_VariableDeclarations.ts index 2562b840995..af119f40be5 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_VariableDeclarations.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_VariableDeclarations.ts @@ -11,7 +11,7 @@ //// var y : any = "", x = (a/*var5*/ ////class C{} -////var y = new C( +////var y = new C(/*var6*/ //// class C{} //// var y = new C(0, /*var7*/ @@ -26,4 +26,8 @@ ////var y = 10; y=/*var12*/ -goTo.eachMarker(() => verify.completionListAllowsNewIdentifier()); +verify.completions({ + marker: test.markers(), + exact: completion.globalsPlus(["x", "y", "C"]), + isNewIdentifierLocation: true +}); diff --git a/tests/cases/fourslash/completionListBuilderLocations_parameters.ts b/tests/cases/fourslash/completionListBuilderLocations_parameters.ts index 607ca0d9819..09d8d8956e9 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_parameters.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_parameters.ts @@ -2,19 +2,20 @@ ////var aa = 1; -////class bar1{ constructor(/*constructorParamter1*/ +////class bar1{ constructor(/*1*/ -////class bar2{ constructor(a/*constructorParamter2*/ +////class bar2{ constructor(a/*2*/ -////class bar3{ constructor(a, /*constructorParamter3*/ +////class bar3{ constructor(a, /*3*/ -////class bar4{ constructor(a, b/*constructorParamter4*/ +////class bar4{ constructor(a, b/*4*/ -////class bar6{ constructor(public a, /*constructorParamter5*/ +////class bar6{ constructor(public a, /*5*/ -////class bar7{ constructor(private a, /*constructorParamter6*/ +////class bar7{ constructor(private a, /*6*/ -goTo.eachMarker(() => { - verify.not.completionListIsEmpty(); - verify.completionListAllowsNewIdentifier(); -}); \ No newline at end of file +verify.completions({ + marker: test.markers(), + exact: completion.constructorParameterKeywords, + isNewIdentifierLocation: true +}); diff --git a/tests/cases/fourslash/completionListBuilderLocations_properties.ts b/tests/cases/fourslash/completionListBuilderLocations_properties.ts index 2cdc3b7e7ba..d0ba2198c8a 100644 --- a/tests/cases/fourslash/completionListBuilderLocations_properties.ts +++ b/tests/cases/fourslash/completionListBuilderLocations_properties.ts @@ -10,4 +10,4 @@ //// public static a/*property2*/ ////} -goTo.eachMarker(() => verify.completionListContainsClassElementKeywords()); +verify.completions({ marker: test.markers(), exact: completion.classElementKeywords, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListCladule.ts b/tests/cases/fourslash/completionListCladule.ts index 6d9e9145b66..1040446f4d0 100644 --- a/tests/cases/fourslash/completionListCladule.ts +++ b/tests/cases/fourslash/completionListCladule.ts @@ -14,15 +14,12 @@ goTo.marker("c1"); edit.insert("."); -verify.completionListContains("x"); -verify.completionListContains("prototype"); -verify.completionListContains("staticMethod"); +verify.completions({ includes: ["x", "prototype", "staticMethod"] }); goTo.marker("c2"); edit.insert("."); -verify.completionListIsEmpty(); +verify.completions({ exact: undefined }); goTo.marker("c3"); edit.insert("."); -verify.completionListContains("doStuff"); -verify.completionListCount(1); +verify.completions({ exact: "doStuff" }); diff --git a/tests/cases/fourslash/completionListClassMembers.ts b/tests/cases/fourslash/completionListClassMembers.ts index 2bf65cc7c0c..6a51ce7e71d 100644 --- a/tests/cases/fourslash/completionListClassMembers.ts +++ b/tests/cases/fourslash/completionListClassMembers.ts @@ -23,48 +23,21 @@ ////var c = new Class(); ////c./*instanceMembersOutsideClassScope*/privateProperty; - -goTo.marker("staticsInsideClassScope"); -verify.completionListContains("privateStaticProperty"); -verify.completionListContains("privateStaticMethod"); -verify.completionListContains("publicStaticProperty"); -verify.completionListContains("publicStaticMethod"); -// No instance properties -verify.not.completionListContains("privateProperty"); -verify.not.completionListContains("privateInstanceMethod"); -// constructors should have a 'prototype' member -verify.completionListContains("prototype"); - -goTo.marker("instanceMembersInsideClassScope"); -verify.completionListContains("privateProperty"); -verify.completionListContains("privateInstanceMethod"); -verify.completionListContains("publicProperty"); -verify.completionListContains("publicInstanceMethod"); -// No statics -verify.not.completionListContains("privateStaticProperty"); -verify.not.completionListContains("privateStaticMethod"); - - -goTo.marker("staticsOutsideClassScope"); -// No privates -verify.not.completionListContains("privateStaticProperty"); -verify.not.completionListContains("privateStaticMethod"); -// Only publics -verify.completionListContains("publicStaticProperty"); -verify.completionListContains("publicStaticMethod"); -// No instance properties -verify.not.completionListContains("publicProperty"); -verify.not.completionListContains("publicInstanceMethod"); -// constructors should have a 'prototype' member -verify.completionListContains("prototype"); - -goTo.marker("instanceMembersOutsideClassScope"); -// No privates -verify.not.completionListContains("privateProperty"); -verify.not.completionListContains("privateInstanceMethod"); -// Only publics -verify.completionListContains("publicProperty"); -verify.completionListContains("publicInstanceMethod"); -// No statics -verify.not.completionListContains("publicStaticProperty"); -verify.not.completionListContains("publicStaticMethod"); \ No newline at end of file +verify.completions( + { + marker: "staticsInsideClassScope", + exact: ["prototype", "privateStaticProperty", "publicStaticProperty", "privateStaticMethod", "publicStaticMethod", ...completion.functionMembers], + }, + { + marker: "instanceMembersInsideClassScope", + exact: ["privateInstanceMethod", "publicInstanceMethod", "privateProperty", "publicProperty"], + }, + { + marker: "staticsOutsideClassScope", + exact: ["prototype", "publicStaticProperty", "publicStaticMethod", ...completion.functionMembers], + }, + { + marker: "instanceMembersOutsideClassScope", + exact: ["publicInstanceMethod", "publicProperty"], + }, +); diff --git a/tests/cases/fourslash/completionListClassMembersWithSuperClassFromUnknownNamespace.ts b/tests/cases/fourslash/completionListClassMembersWithSuperClassFromUnknownNamespace.ts index 8e6aab7394b..3776ea2c584 100644 --- a/tests/cases/fourslash/completionListClassMembersWithSuperClassFromUnknownNamespace.ts +++ b/tests/cases/fourslash/completionListClassMembersWithSuperClassFromUnknownNamespace.ts @@ -4,6 +4,4 @@ //// /**/ ////} -goTo.marker(""); -verify.completionListContainsClassElementKeywords(); -verify.completionListCount(verify.allowedClassElementKeywords.length); \ No newline at end of file +verify.completions({ marker: "", includes: completion.classElementKeywords, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListEnumMembers.ts b/tests/cases/fourslash/completionListEnumMembers.ts index 134fdd304f1..42029ae3216 100644 --- a/tests/cases/fourslash/completionListEnumMembers.ts +++ b/tests/cases/fourslash/completionListEnumMembers.ts @@ -9,16 +9,7 @@ ////var t :Foo./*typeReference*/ba; ////Foo.bar./*enumValueReference*/; -goTo.marker('valueReference'); -verify.completionListContains("bar"); -verify.completionListContains("baz"); -verify.completionListCount(2); - - -goTo.marker('typeReference'); -verify.completionListCount(2); - -goTo.marker('enumValueReference'); -verify.completionListContains("toString"); -verify.completionListContains("toFixed"); -verify.completionListCount(6); +verify.completions( + { marker: ["valueReference", "typeReference"], exact: ["bar", "baz"] }, + { marker: "enumValueReference", exact: ["toString", "toFixed", "toExponential", "toPrecision", "valueOf", "toLocaleString"] }, +); diff --git a/tests/cases/fourslash/completionListEnumValues.ts b/tests/cases/fourslash/completionListEnumValues.ts index 0b0bf0f9676..b684bdad49a 100644 --- a/tests/cases/fourslash/completionListEnumValues.ts +++ b/tests/cases/fourslash/completionListEnumValues.ts @@ -13,20 +13,9 @@ ////function foo(): Colors { return null; } ////foo()./*callOfEnumReturnType*/ -goTo.marker("enumVariable"); -// Should only have the enum's own members, and nothing else -verify.completionListContains("Red"); -verify.completionListContains("Green"); -verify.completionListCount(2); - - -goTo.marker("variableOfEnumType"); -// Should have number members, and not enum members -verify.completionListContains("toString"); -verify.not.completionListContains("Red"); - - -goTo.marker("callOfEnumReturnType"); -// Should have number members, and not enum members -verify.completionListContains("toString"); -verify.not.completionListContains("Red"); +verify.completions( + // Should only have the enum's own members, and nothing else + { marker: "enumVariable", exact: ["Red", "Green"] }, + // Should have number members, and not enum members + { marker: ["variableOfEnumType", "callOfEnumReturnType"], exact: ["toString", "toFixed", "toExponential", "toPrecision", "valueOf", "toLocaleString"] }, +); diff --git a/tests/cases/fourslash/completionListErrorRecovery.ts b/tests/cases/fourslash/completionListErrorRecovery.ts index d5917d43aeb..69eb8004f47 100644 --- a/tests/cases/fourslash/completionListErrorRecovery.ts +++ b/tests/cases/fourslash/completionListErrorRecovery.ts @@ -5,6 +5,5 @@ ////Foo./**/; /////*1*/var bar; -goTo.marker(); -verify.completionListContains("fun"); -verify.not.errorExistsAfterMarker("1"); \ No newline at end of file +verify.completions({ marker: "", includes: "fun" }); +verify.not.errorExistsAfterMarker("1"); diff --git a/tests/cases/fourslash/completionListForDerivedType1.ts b/tests/cases/fourslash/completionListForDerivedType1.ts index 0d771441dae..ef9b28503d1 100644 --- a/tests/cases/fourslash/completionListForDerivedType1.ts +++ b/tests/cases/fourslash/completionListForDerivedType1.ts @@ -8,14 +8,13 @@ ////} ////var f: IFoo; ////var f2: IFoo2; -////f./*1*/ // completion here shows bar with return type is any +////f./*1*/; // completion here shows bar with return type is any ////f2./*2*/ // here bar has return type any, but bar2 is Foo2 -goTo.marker('1'); -verify.completionListContains('bar', '(method) IFoo.bar(): IFoo'); -verify.not.completionListContains('bar2'); -edit.insert('bar();'); // just to make the file valid before checking next completion location - -goTo.marker('2'); -verify.completionListContains('bar', '(method) IFoo.bar(): IFoo'); -verify.completionListContains('bar2', '(method) IFoo2.bar2(): IFoo2'); \ No newline at end of file +verify.completions( + { marker: "1", exact: [{ name: "bar", text: "(method) IFoo.bar(): IFoo" }] }, + { + marker: "2", + exact: [{ name: "bar2", text: "(method) IFoo2.bar2(): IFoo2" }, { name: "bar", text: "(method) IFoo.bar(): IFoo" }] + }, +); diff --git a/tests/cases/fourslash/completionListForExportEquals.ts b/tests/cases/fourslash/completionListForExportEquals.ts index 28b20177c57..54161ea840c 100644 --- a/tests/cases/fourslash/completionListForExportEquals.ts +++ b/tests/cases/fourslash/completionListForExportEquals.ts @@ -13,4 +13,4 @@ // @Filename: /a.ts ////import { /**/ } from "foo"; -verify.completionsAt("", ["Static", "foo"]); +verify.completions({ marker: "", exact: ["Static", "foo"] }); diff --git a/tests/cases/fourslash/completionListForExportEquals2.ts b/tests/cases/fourslash/completionListForExportEquals2.ts index a7b0772d55e..cf890b47ab1 100644 --- a/tests/cases/fourslash/completionListForExportEquals2.ts +++ b/tests/cases/fourslash/completionListForExportEquals2.ts @@ -11,4 +11,4 @@ // @Filename: /a.ts ////import { /**/ } from "foo"; -verify.completionsAt("", ["Static"]); +verify.completions({ marker: "", exact: "Static" }); diff --git a/tests/cases/fourslash/completionListForGenericInstance1.ts b/tests/cases/fourslash/completionListForGenericInstance1.ts index 5f323c12691..718b90ca65c 100644 --- a/tests/cases/fourslash/completionListForGenericInstance1.ts +++ b/tests/cases/fourslash/completionListForGenericInstance1.ts @@ -6,5 +6,4 @@ ////var i: Iterator; ////i/**/ -goTo.marker(); -verify.completionListContains('i', 'var i: Iterator'); +verify.completions({ marker: "", includes: { name: "i", text: "var i: Iterator" } }); diff --git a/tests/cases/fourslash/completionListForNonExportedMemberInAmbientModuleWithExportAssignment1.ts b/tests/cases/fourslash/completionListForNonExportedMemberInAmbientModuleWithExportAssignment1.ts index 6bc2eaf886a..3887d991e4b 100644 --- a/tests/cases/fourslash/completionListForNonExportedMemberInAmbientModuleWithExportAssignment1.ts +++ b/tests/cases/fourslash/completionListForNonExportedMemberInAmbientModuleWithExportAssignment1.ts @@ -9,5 +9,4 @@ //// import test = require("completionListForNonExportedMemberInAmbientModuleWithExportAssignment1_file0"); //// test./**/ -goTo.marker(); -verify.not.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListForObjectSpread.ts b/tests/cases/fourslash/completionListForObjectSpread.ts index 1fc9a7795e6..703a2e52153 100644 --- a/tests/cases/fourslash/completionListForObjectSpread.ts +++ b/tests/cases/fourslash/completionListForObjectSpread.ts @@ -18,18 +18,16 @@ //// { a: 7, ...undefined } ////spreadNull./*3*/a; ////spreadUndefined./*4*/a; -goTo.marker('1'); -verify.completionListContains('a', '(property) a: number'); -verify.completionListContains('b', '(property) b: string'); -verify.completionListCount(2); -goTo.marker('2'); -verify.completionListContains('a', '(property) a: number'); -verify.completionListContains('b', '(property) b: boolean'); -verify.completionListContains('c', '(property) c: number'); -verify.completionListCount(3); -goTo.marker('3'); -verify.completionListContains('a', '(property) a: number'); -verify.completionListCount(1); -goTo.marker('4'); -verify.completionListContains('a', '(property) a: number'); -verify.completionListCount(1); + +const a: FourSlashInterface.ExpectedCompletionEntry = { name: "a", text: "(property) a: number" }; +verify.completions( + { + marker: "1", + exact: [a, { name: "b", text: "(property) b: string" }], + }, + { + marker: "2", + exact: [a, { name: "b", text: "(property) b: boolean" }, { name: "c", text: "(property) c: number" }], + }, + { marker: ["3", "4"], exact: a }, +); diff --git a/tests/cases/fourslash/completionListForRest.ts b/tests/cases/fourslash/completionListForRest.ts index 8ea1b7a2a9d..af2d3b5f3cf 100644 --- a/tests/cases/fourslash/completionListForRest.ts +++ b/tests/cases/fourslash/completionListForRest.ts @@ -7,7 +7,8 @@ ////let t: Gen; ////var { x, ...rest } = t; ////rest./*1*/x; -goTo.marker('1'); -verify.completionListContains('parent', '(property) Gen.parent: Gen'); -verify.completionListContains('millenial', '(property) Gen.millenial: string'); -verify.completionListCount(2); + +verify.completions({ + marker: "1", + exact: [{ name: "parent", text: "(property) Gen.parent: Gen" }, { name: "millenial", text: "(property) Gen.millenial: string" }], +}); diff --git a/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts b/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts index 2b10757bbef..7b364b69ec9 100644 --- a/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts +++ b/tests/cases/fourslash/completionListForShorthandPropertyAssignment.ts @@ -2,6 +2,4 @@ //// var person: {name:string; id: number} = { n/**/ -goTo.marker(); -verify.completionListContains('name'); -verify.completionListContains('id'); \ No newline at end of file +verify.completions({ marker: "", exact: ["name", "id"] }); diff --git a/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts b/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts index 2b10757bbef..7b364b69ec9 100644 --- a/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts +++ b/tests/cases/fourslash/completionListForShorthandPropertyAssignment2.ts @@ -2,6 +2,4 @@ //// var person: {name:string; id: number} = { n/**/ -goTo.marker(); -verify.completionListContains('name'); -verify.completionListContains('id'); \ No newline at end of file +verify.completions({ marker: "", exact: ["name", "id"] }); diff --git a/tests/cases/fourslash/completionListForTransitivelyExportedMembers01.ts b/tests/cases/fourslash/completionListForTransitivelyExportedMembers01.ts index c9fe659cd91..90f5cceac34 100644 --- a/tests/cases/fourslash/completionListForTransitivelyExportedMembers01.ts +++ b/tests/cases/fourslash/completionListForTransitivelyExportedMembers01.ts @@ -31,9 +31,4 @@ ////import * as c from "./C"; ////var x = c./**/ -goTo.marker(); -verify.completionListContains("C1"); -verify.completionListContains("Inner"); -verify.completionListContains("bVar"); -verify.completionListContains("cVar"); -verify.not.completionListContains("__export"); \ No newline at end of file +verify.completions({ marker: "", exact: ["cVar", "C1", "Inner", "bVar"] }); diff --git a/tests/cases/fourslash/completionListForTransitivelyExportedMembers02.ts b/tests/cases/fourslash/completionListForTransitivelyExportedMembers02.ts index 6f2e2f490b1..e2335c4b36f 100644 --- a/tests/cases/fourslash/completionListForTransitivelyExportedMembers02.ts +++ b/tests/cases/fourslash/completionListForTransitivelyExportedMembers02.ts @@ -32,8 +32,4 @@ ////import * as c from "./C"; ////var x = c.Inner./**/ -goTo.marker(); -verify.completionListContains("varVar"); -verify.completionListContains("letVar"); -verify.completionListContains("constVar"); -verify.not.completionListContains("__export"); \ No newline at end of file +verify.completions({ marker: "", exact: ["varVar", "letVar", "constVar"] }); diff --git a/tests/cases/fourslash/completionListForTransitivelyExportedMembers03.ts b/tests/cases/fourslash/completionListForTransitivelyExportedMembers03.ts index ae92a706e50..4a878081d2e 100644 --- a/tests/cases/fourslash/completionListForTransitivelyExportedMembers03.ts +++ b/tests/cases/fourslash/completionListForTransitivelyExportedMembers03.ts @@ -32,9 +32,4 @@ ////import * as c from "./C"; ////var x: c./**/ -goTo.marker(); -verify.completionListContains("I1"); -verify.completionListContains("I2"); -verify.completionListContains("I1_OR_I2"); -verify.completionListContains("C1"); -verify.not.completionListContains("__export"); \ No newline at end of file +verify.completions({ marker: "", includes: ["I1", "I2", "I1_OR_I2", "C1"] }); diff --git a/tests/cases/fourslash/completionListForTransitivelyExportedMembers04.ts b/tests/cases/fourslash/completionListForTransitivelyExportedMembers04.ts index 44f2bf224ad..f6052fe030c 100644 --- a/tests/cases/fourslash/completionListForTransitivelyExportedMembers04.ts +++ b/tests/cases/fourslash/completionListForTransitivelyExportedMembers04.ts @@ -32,6 +32,4 @@ ////import * as c from "C"; ////var x: c.Inner./**/ -goTo.marker(); -verify.completionListContains("I3"); -verify.not.completionListContains("__export"); \ No newline at end of file +verify.completions({ marker: "", exact: "I3" }); diff --git a/tests/cases/fourslash/completionListForUnicodeEscapeName.ts b/tests/cases/fourslash/completionListForUnicodeEscapeName.ts index 9ada3e35961..7c18e6c82a0 100644 --- a/tests/cases/fourslash/completionListForUnicodeEscapeName.ts +++ b/tests/cases/fourslash/completionListForUnicodeEscapeName.ts @@ -1,26 +1,12 @@ /// ////function \u0042 () { /*0*/ } -////export default function \u0043 () { /*1*/ } +////export default function \u0043 () {} ////class \u0041 { /*2*/ } /////*3*/ -goTo.marker("0"); -verify.completionListContains("B"); -verify.completionListContains("\u0042"); - -goTo.marker("2"); -verify.not.completionListContains("C"); -verify.not.completionListContains("\u0043"); - -goTo.marker("2"); -verify.not.completionListContains("A"); -verify.not.completionListContains("\u0041"); - -goTo.marker("3"); -verify.completionListContains("B"); -verify.completionListContains("\u0042"); -verify.completionListContains("A"); -verify.completionListContains("\u0041"); -verify.completionListContains("C"); -verify.completionListContains("\u0043"); +verify.completions( + { marker: "0", includes: ["B", "\u0042"] }, + { marker: "2", excludes: ["C", "\u0043", "A", "\u0041"], isNewIdentifierLocation: true }, + { marker: "3", includes: ["B", "\u0042", "A", "\u0041", "C", "\u0043"] }, +); diff --git a/tests/cases/fourslash/completionListFunctionExpression.ts b/tests/cases/fourslash/completionListFunctionExpression.ts index b861ff2e023..4b7f75dc6e0 100644 --- a/tests/cases/fourslash/completionListFunctionExpression.ts +++ b/tests/cases/fourslash/completionListFunctionExpression.ts @@ -15,7 +15,7 @@ goTo.marker("local"); edit.insertLine(""); -verify.completionListContains("xmlEvent"); - -goTo.marker("this"); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions( + { includes: "xmlEvent" }, + { marker: "this", exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListFunctionMembers.ts b/tests/cases/fourslash/completionListFunctionMembers.ts index 1a10fea1d8d..f53b66b1c03 100644 --- a/tests/cases/fourslash/completionListFunctionMembers.ts +++ b/tests/cases/fourslash/completionListFunctionMembers.ts @@ -7,5 +7,4 @@ //// ////fnc1./**/ -goTo.marker(); -verify.completionListContains('arguments', '(property) Function.arguments: any'); \ No newline at end of file +verify.completions({ marker: "", exact: completion.functionMembersWithPrototype }); diff --git a/tests/cases/fourslash/completionListGenericConstraints.ts b/tests/cases/fourslash/completionListGenericConstraints.ts index 10058ccbafa..cb0965e6288 100644 --- a/tests/cases/fourslash/completionListGenericConstraints.ts +++ b/tests/cases/fourslash/completionListGenericConstraints.ts @@ -32,7 +32,7 @@ //// ////class CallableWrapper { //// public call(value: T) { -//// value./*callableMembers*/ +//// value./*callableMembers*/ //// } ////} ////// Only public members of a constraint should be shown @@ -47,31 +47,13 @@ //// ////class BaseWrapper { //// public test(value: T) { -//// value./*publicOnlyMemebers*/ +//// value./*publicOnlyMembers*/ //// } ////} -goTo.marker("objectMembers"); -verify.completionListContains("hasOwnProperty"); -verify.completionListContains("isPrototypeOf"); -verify.completionListContains("toString"); - -goTo.marker("interfaceMembers"); -verify.completionListContains("bar11"); -verify.completionListContains("bar12"); -verify.completionListContains("bar21"); -verify.completionListContains("bar22"); - -goTo.marker("callableMembers"); -verify.completionListContains("name"); -verify.completionListContains("apply"); -verify.completionListContains("call"); -verify.completionListContains("bind"); - -goTo.marker("publicOnlyMemebers"); -verify.completionListContains("publicProperty"); -verify.completionListContains("publicMethod"); -verify.not.completionListContains("privateProperty"); -verify.not.completionListContains("privateMethod"); -verify.not.completionListContains("publicStaticMethod"); -verify.not.completionListContains("privateStaticMethod"); \ No newline at end of file +verify.completions( + { marker: "objectMembers", exact: ["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"] }, + { marker: "interfaceMembers", exact: ["bar21", "bar22", "bar11", "bar12"] }, + { marker: "callableMembers", exact: ["name", ...completion.functionMembersWithPrototype] }, + { marker: "publicOnlyMembers", exact: ["publicProperty", "publicMethod"] }, +); diff --git a/tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts b/tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts index 42be3a51618..179fc02aa59 100644 --- a/tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts +++ b/tests/cases/fourslash/completionListImplementingInterfaceFunctions.ts @@ -15,7 +15,4 @@ //// /*1*/ ////} -goTo.marker("0"); -verify.not.completionListContains("a"); -goTo.marker("1"); -verify.not.completionListContains("a"); +verify.completions({ marker: ["0", "1"], exact: "b" }); diff --git a/tests/cases/fourslash/completionListInArrowFunctionInUnclosedCallSite01.ts b/tests/cases/fourslash/completionListInArrowFunctionInUnclosedCallSite01.ts index 633dc00a941..0dde6f85990 100644 --- a/tests/cases/fourslash/completionListInArrowFunctionInUnclosedCallSite01.ts +++ b/tests/cases/fourslash/completionListInArrowFunctionInUnclosedCallSite01.ts @@ -4,8 +4,8 @@ ////function getAllFiles(rootFileNames: string[]) { //// var processedFiles = rootFileNames.map(fileName => foo(/*1*/ -goTo.marker("1"); -verify.completionListContains("fileName"); -verify.completionListContains("rootFileNames"); -verify.completionListContains("getAllFiles"); -verify.completionListContains("foo"); \ No newline at end of file +verify.completions({ + marker: "1", + includes: ["fileName", "rootFileNames", "getAllFiles", "foo"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionListInClassExpressionWithTypeParameter.ts b/tests/cases/fourslash/completionListInClassExpressionWithTypeParameter.ts index 47f030bf907..7a4a42f90db 100644 --- a/tests/cases/fourslash/completionListInClassExpressionWithTypeParameter.ts +++ b/tests/cases/fourslash/completionListInClassExpressionWithTypeParameter.ts @@ -8,10 +8,7 @@ //// prop: Ty/*1*/ //// } -goTo.marker("0"); -verify.not.completionListContains("TypeParam", "(type parameter) TypeParam in myClass", /*documentation*/ undefined, "type parameter"); -goTo.marker("0Type"); -verify.completionListContains("TypeParam", "(type parameter) TypeParam in myClass", /*documentation*/ undefined, "type parameter"); - -goTo.marker("1"); -verify.completionListContains("TypeParam", "(type parameter) TypeParam in myClass", /*documentation*/ undefined, "type parameter"); \ No newline at end of file +verify.completions( + { marker: "0", excludes: "TypeParam" }, + { marker: ["0Type", "1"], includes: { name: "TypeParam", text: "(type parameter) TypeParam in myClass", kind: "type parameter" } }, +); diff --git a/tests/cases/fourslash/completionListInClosedFunction01.ts b/tests/cases/fourslash/completionListInClosedFunction01.ts index 608d0c761cf..af1175e4695 100644 --- a/tests/cases/fourslash/completionListInClosedFunction01.ts +++ b/tests/cases/fourslash/completionListInClosedFunction01.ts @@ -4,9 +4,4 @@ //// /*1*/ ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["x", "y", "z"] }); diff --git a/tests/cases/fourslash/completionListInClosedFunction02.ts b/tests/cases/fourslash/completionListInClosedFunction02.ts index 89428df12f8..bfda6646fd7 100644 --- a/tests/cases/fourslash/completionListInClosedFunction02.ts +++ b/tests/cases/fourslash/completionListInClosedFunction02.ts @@ -5,14 +5,8 @@ //// } ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); - -verify.completionListContains("bar"); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); // questionable \ No newline at end of file +verify.completions({ + marker: "1", + // Note: `c: typeof c` would be a compile error + includes: ["foo", "x", "y", "z", "bar", "a", "b", "c"], +}); diff --git a/tests/cases/fourslash/completionListInClosedFunction03.ts b/tests/cases/fourslash/completionListInClosedFunction03.ts index ce43ec33b0d..3ee7cd43d24 100644 --- a/tests/cases/fourslash/completionListInClosedFunction03.ts +++ b/tests/cases/fourslash/completionListInClosedFunction03.ts @@ -2,18 +2,12 @@ ////function foo(x: string, y: number, z: boolean) { //// function bar(a: number, b: string, c: typeof x = /*1*/) { -//// +//// //// } ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); - -verify.completionListContains("bar"); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); // questionable \ No newline at end of file +verify.completions({ + marker: "1", + // Note: `c = c` would be a compile error + includes: ["foo", "x", "y", "z", "bar", "a", "b", "c"], +}); diff --git a/tests/cases/fourslash/completionListInClosedFunction04.ts b/tests/cases/fourslash/completionListInClosedFunction04.ts index 47ae9da2c9e..225cbbb1a20 100644 --- a/tests/cases/fourslash/completionListInClosedFunction04.ts +++ b/tests/cases/fourslash/completionListInClosedFunction04.ts @@ -2,18 +2,12 @@ ////function foo(x: string, y: number, z: boolean) { //// function bar(a: number, b: string = /*1*/, c: typeof x = "hello") { -//// +//// //// } ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); - -verify.completionListContains("bar"); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); // definitely questionable \ No newline at end of file +verify.completions({ + marker: "1", + // Note: `b = b` or `b = c` would be a compile error + includes: ["foo", "x", "y", "z", "bar", "a", "b", "c"], +}); diff --git a/tests/cases/fourslash/completionListInClosedFunction05.ts b/tests/cases/fourslash/completionListInClosedFunction05.ts index 3252904ee19..11c16009349 100644 --- a/tests/cases/fourslash/completionListInClosedFunction05.ts +++ b/tests/cases/fourslash/completionListInClosedFunction05.ts @@ -6,16 +6,9 @@ //// } ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); - -verify.completionListContains("bar"); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); - -verify.completionListContains("v"); // questionable \ No newline at end of file +verify.completions({ + marker: "1", + // Note: `v = v` would be a compile error + includes: ["foo", "x", "y", "z", "bar", "a", "b", "c", "v"], + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionListInClosedFunction06.ts b/tests/cases/fourslash/completionListInClosedFunction06.ts index 76c58f87174..f9c9cc4c8df 100644 --- a/tests/cases/fourslash/completionListInClosedFunction06.ts +++ b/tests/cases/fourslash/completionListInClosedFunction06.ts @@ -9,6 +9,4 @@ //// } ////} -goTo.marker("1"); - -verify.completionListContains("MyType"); \ No newline at end of file +verify.completions({ marker: "1", includes: "MyType", excludes: "x" }); diff --git a/tests/cases/fourslash/completionListInClosedFunction07.ts b/tests/cases/fourslash/completionListInClosedFunction07.ts index 8c0b5e68872..0c911c8b61e 100644 --- a/tests/cases/fourslash/completionListInClosedFunction07.ts +++ b/tests/cases/fourslash/completionListInClosedFunction07.ts @@ -9,17 +9,8 @@ //// } ////} -goTo.marker("1"); - -verify.completionListContains("foo"); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.completionListContains("z"); - -verify.completionListContains("bar"); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); - -verify.completionListContains("v"); -verify.completionListContains("p"); \ No newline at end of file +verify.completions({ + marker: "1", + includes: ["foo", "x", "y", "z", "bar", "a", "b", "c", "v", "p"], + excludes: "MyType", +}); diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts index 856d94492e6..1c754267851 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature01.ts @@ -7,12 +7,8 @@ //// ////declare function foo(obj: I): { str: T/*1*/ } -goTo.marker("1"); - -verify.completionListContains("I"); -verify.completionListContains("TString"); -verify.completionListContains("TNumber"); - -// Ideally the following shouldn't show up since they're not types. -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); \ No newline at end of file +verify.completions({ + marker: "1", + includes: ["I", "TString", "TNumber"], + excludes: ["foo", "obj"], // not types +}); diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts index 0472a9c04fa..5b0af2dd491 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature02.ts @@ -7,12 +7,4 @@ //// ////declare function foo(obj: I): { str: TStr/*1*/ } -goTo.marker("1"); - -verify.completionListContains("I"); -verify.completionListContains("TString"); -verify.completionListContains("TNumber"); // REVIEW: Is this intended behavior? - -// Ideally the following shouldn't show up since they're not types. -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["I", "TString", "TNumber"], excludes: ["foo", "obj"] }); diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts index 1dc34dcffd4..eb49f7e2340 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature03.ts @@ -7,12 +7,8 @@ //// ////declare function foo(obj: I): { str: TString/*1*/ } -goTo.marker("1"); - -verify.completionListContains("I"); -verify.completionListContains("TString"); -verify.completionListContains("TNumber"); // REVIEW: Is this intended behavior? - -// Ideally the following shouldn't show up since they're not types. -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); \ No newline at end of file +verify.completions({ + marker: "1", + includes: ["I", "TString", "TNumber"], + excludes: ["foo", "obj"], // not types +}); diff --git a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts index 8674124f05f..2f07107e057 100644 --- a/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts +++ b/tests/cases/fourslash/completionListInClosedObjectTypeLiteralInSignature04.ts @@ -7,4 +7,4 @@ //// ////declare function foo(obj: I): { /*1*/ } -verify.completionsAt("1", ["readonly"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "1", exact: "readonly", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInComments.ts b/tests/cases/fourslash/completionListInComments.ts index dadb1ba46f4..fd9c5bcb02c 100644 --- a/tests/cases/fourslash/completionListInComments.ts +++ b/tests/cases/fourslash/completionListInComments.ts @@ -3,6 +3,5 @@ ////var foo = ''; ////( // f/**/ -goTo.marker(); // Completion list should not be available within comments -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListInComments2.ts b/tests/cases/fourslash/completionListInComments2.ts index d9855306fcf..8eb1272ba64 100644 --- a/tests/cases/fourslash/completionListInComments2.ts +++ b/tests/cases/fourslash/completionListInComments2.ts @@ -2,6 +2,5 @@ //// // */{| "name" : "1" |} -goTo.marker("1"); // Completion list should not be available within comments -verify.completionListIsEmpty(); +verify.completions({ marker: "1", exact: undefined }); diff --git a/tests/cases/fourslash/completionListInComments3.ts b/tests/cases/fourslash/completionListInComments3.ts index 2f20a969ba1..a874ab8e953 100644 --- a/tests/cases/fourslash/completionListInComments3.ts +++ b/tests/cases/fourslash/completionListInComments3.ts @@ -12,20 +12,7 @@ /////* {| "name": "6" |} -goTo.marker("1"); -verify.completionListIsEmpty(); - -goTo.marker("2"); -verify.completionListIsEmpty(); - -goTo.marker("3"); -verify.completionListIsEmpty(); - -goTo.marker("4"); -verify.not.completionListIsEmpty(); - -goTo.marker("5"); -verify.not.completionListIsEmpty(); - -goTo.marker("6"); -verify.completionListIsEmpty(); +verify.completions( + { marker: ["1", "2", "3", "6"], exact: undefined }, + { marker: ["4", "5"], exact: completion.globals }, +); diff --git a/tests/cases/fourslash/completionListInContextuallyTypedArgument.ts b/tests/cases/fourslash/completionListInContextuallyTypedArgument.ts index 69a35bed0e3..7a1d1f936c0 100644 --- a/tests/cases/fourslash/completionListInContextuallyTypedArgument.ts +++ b/tests/cases/fourslash/completionListInContextuallyTypedArgument.ts @@ -17,11 +17,4 @@ //// e./*2*/ ////} ); - -goTo.marker("1"); -verify.completionListContains('x1'); -verify.completionListContains('y1'); - -goTo.marker("2"); -verify.completionListContains('x1'); -verify.completionListContains('y1'); \ No newline at end of file +verify.completions({ marker: ["1", "2"], exact: ["x1", "y1"] }); diff --git a/tests/cases/fourslash/completionListInEmptyFile.ts b/tests/cases/fourslash/completionListInEmptyFile.ts index fc176061358..99f895eb20c 100644 --- a/tests/cases/fourslash/completionListInEmptyFile.ts +++ b/tests/cases/fourslash/completionListInEmptyFile.ts @@ -3,5 +3,4 @@ ////var a = 0; /////**/ -goTo.marker(); -verify.completionListContains("a"); +verify.completions({ marker: "", includes: "a" }); diff --git a/tests/cases/fourslash/completionListInExportClause01.ts b/tests/cases/fourslash/completionListInExportClause01.ts index 741a1ac333c..d11d395b5b0 100644 --- a/tests/cases/fourslash/completionListInExportClause01.ts +++ b/tests/cases/fourslash/completionListInExportClause01.ts @@ -12,29 +12,10 @@ ////export {bar as /*5*/, /*6*/ from "./m1" ////export {foo, bar, baz as b,/*7*/} from "./m1" -function verifyCompletionAtMarker(marker: string, showBuilder: boolean, ...completions: string[]) { - goTo.marker(marker); - if (completions.length) { - for (let completion of completions) { - verify.completionListContains(completion); - } - } - else { - verify.completionListIsEmpty(); - } - - if (showBuilder) { - verify.completionListAllowsNewIdentifier(); - } - else { - verify.not.completionListAllowsNewIdentifier(); - } -} - -verifyCompletionAtMarker("1", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("2", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("3", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("4", /*showBuilder*/ false, "bar", "baz"); -verifyCompletionAtMarker("5", /*showBuilder*/ true); -verifyCompletionAtMarker("6", /*showBuilder*/ false, "foo", "baz"); -verifyCompletionAtMarker("7", /*showBuilder*/ false); \ No newline at end of file +verify.completions( + { marker: ["1", "2", "3"], exact: ["bar", "baz", "foo"] }, + { marker: "4", exact: ["bar", "baz"] }, + { marker: "5", exact: undefined, isNewIdentifierLocation: true }, + { marker: "6", exact: ["baz", "foo"] }, + { marker: "7", exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListInExportClause02.ts b/tests/cases/fourslash/completionListInExportClause02.ts index 4b40976f521..7ded96ef0ae 100644 --- a/tests/cases/fourslash/completionListInExportClause02.ts +++ b/tests/cases/fourslash/completionListInExportClause02.ts @@ -8,7 +8,4 @@ //// export { /**/ } from "M1" ////} -goTo.marker(); -verify.completionListContains("V"); -verify.not.completionListContains("W"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: "V" }); diff --git a/tests/cases/fourslash/completionListInExportClause03.ts b/tests/cases/fourslash/completionListInExportClause03.ts index 426c85d02ea..f731833ac02 100644 --- a/tests/cases/fourslash/completionListInExportClause03.ts +++ b/tests/cases/fourslash/completionListInExportClause03.ts @@ -10,7 +10,4 @@ ////} // Ensure we don't filter out the current item. -goTo.marker(); -verify.completionListContains("abc"); -verify.completionListContains("def"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["abc", "def"] }); diff --git a/tests/cases/fourslash/completionListInExtendsClause.ts b/tests/cases/fourslash/completionListInExtendsClause.ts index 79451e4fd57..f5b1ce4384e 100644 --- a/tests/cases/fourslash/completionListInExtendsClause.ts +++ b/tests/cases/fourslash/completionListInExtendsClause.ts @@ -17,14 +17,8 @@ ////interface test3 extends IFoo./*3*/ {} ////interface test4 implements Foo./*4*/ {} -goTo.marker("1"); -verify.not.completionListIsEmpty(); -goTo.marker("2"); -verify.completionListIsEmpty(); - -goTo.marker("3"); -verify.completionListIsEmpty(); - -goTo.marker("4"); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions( + { marker: "1", exact: ["prototype", "staticMethod", ...completion.functionMembers] }, + { marker: ["2", "3", "4"], exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts b/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts index 7a065fd364d..3c59425e17f 100644 --- a/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts +++ b/tests/cases/fourslash/completionListInExtendsClauseAtEOF.ts @@ -5,6 +5,4 @@ ////} ////class Bar extends mod./**/ -goTo.marker(); -verify.completionListContains("Foo"); -verify.completionListCount(1); \ No newline at end of file +verify.completions({ marker: "", includes: "Foo" }); diff --git a/tests/cases/fourslash/completionListInFatArrow.ts b/tests/cases/fourslash/completionListInFatArrow.ts index 140fa176675..8aac72fec39 100644 --- a/tests/cases/fourslash/completionListInFatArrow.ts +++ b/tests/cases/fourslash/completionListInFatArrow.ts @@ -8,4 +8,4 @@ goTo.marker(); edit.insert('it'); -verify.completionListContains('items'); \ No newline at end of file +verify.completions({ includes: "items" }); diff --git a/tests/cases/fourslash/completionListInFunctionDeclaration.ts b/tests/cases/fourslash/completionListInFunctionDeclaration.ts index 87107da897c..3ba4b7d4775 100644 --- a/tests/cases/fourslash/completionListInFunctionDeclaration.ts +++ b/tests/cases/fourslash/completionListInFunctionDeclaration.ts @@ -3,15 +3,14 @@ ////var a = 0; ////function foo(/**/ -goTo.marker(); -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: undefined }); edit.insert("a"); // foo(a| -verify.completionListIsEmpty(); +verify.completions({ exact: undefined }); edit.insert(" , "); // foo(a ,| -verify.completionListIsEmpty(); +verify.completions({ exact: undefined }); edit.insert("b"); // foo(a ,b| -verify.completionListIsEmpty(); +verify.completions({ exact: undefined }); edit.insert(":"); // foo(a ,b:| <- type ref -verify.not.completionListIsEmpty(); +verify.completions({ exact: completion.globalTypes }); edit.insert("number, "); // foo(a ,b:number,| -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ exact: undefined }); diff --git a/tests/cases/fourslash/completionListInFunctionExpression.ts b/tests/cases/fourslash/completionListInFunctionExpression.ts index bba9eb09c3a..60e96745754 100644 --- a/tests/cases/fourslash/completionListInFunctionExpression.ts +++ b/tests/cases/fourslash/completionListInFunctionExpression.ts @@ -6,19 +6,18 @@ //// foo./*memberCompletion*/toString; ////}/*editDeclaration*/ -goTo.marker("requestCompletion"); -verify.completionListContains("foo"); +function check() { + verify.completions( + { marker: "requestCompletion", includes: "foo" }, + { marker: "memberCompletion", includes: "toExponential" }, + ); +} -goTo.marker("memberCompletion"); -verify.completionListContains("toExponential"); +check(); // Now change the decl by adding a semicolon goTo.marker("editDeclaration"); edit.insert(";"); // foo should still be there -goTo.marker("requestCompletion"); -verify.completionListContains("foo"); - -goTo.marker("memberCompletion"); -verify.completionListContains("toExponential"); +check(); diff --git a/tests/cases/fourslash/completionListInImportClause01.ts b/tests/cases/fourslash/completionListInImportClause01.ts index fb2beadc566..026d4360633 100644 --- a/tests/cases/fourslash/completionListInImportClause01.ts +++ b/tests/cases/fourslash/completionListInImportClause01.ts @@ -13,29 +13,10 @@ ////import {bar as /*5*/, /*6*/ from "m1" ////import {foo, bar, baz as b,/*7*/} from "m1" -function verifyCompletionAtMarker(marker: string, showBuilder: boolean, ...completions: string[]) { - goTo.marker(marker); - if (completions.length) { - for (let completion of completions) { - verify.completionListContains(completion); - } - } - else { - verify.completionListIsEmpty(); - } - - if (showBuilder) { - verify.completionListAllowsNewIdentifier(); - } - else { - verify.not.completionListAllowsNewIdentifier(); - } -} - -verifyCompletionAtMarker("1", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("2", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("3", /*showBuilder*/ false, "foo", "bar", "baz"); -verifyCompletionAtMarker("4", /*showBuilder*/ false, "bar", "baz"); -verifyCompletionAtMarker("5", /*showBuilder*/ true); -verifyCompletionAtMarker("6", /*showBuilder*/ false, "foo", "baz"); -verifyCompletionAtMarker("7", /*showBuilder*/ false); \ No newline at end of file +verify.completions( + { marker: ["1", "2", "3"], exact: ["bar", "baz", "foo"] }, + { marker: "4", exact: ["bar", "baz"] }, + { marker: "5", exact: undefined, isNewIdentifierLocation: true }, + { marker: "6", exact: ["baz", "foo"] }, + { marker: "7", exact: undefined }, +); diff --git a/tests/cases/fourslash/completionListInImportClause02.ts b/tests/cases/fourslash/completionListInImportClause02.ts index 9cf216f4578..0bc840eed54 100644 --- a/tests/cases/fourslash/completionListInImportClause02.ts +++ b/tests/cases/fourslash/completionListInImportClause02.ts @@ -8,6 +8,4 @@ //// import { /**/ } from "M1" ////} -goTo.marker(); -verify.completionListContains("V"); -verify.not.completionListAllowsNewIdentifier(); +verify.completions({ marker: "", exact: "V" }); diff --git a/tests/cases/fourslash/completionListInImportClause03.ts b/tests/cases/fourslash/completionListInImportClause03.ts index 7461c83022b..db1d7f84a53 100644 --- a/tests/cases/fourslash/completionListInImportClause03.ts +++ b/tests/cases/fourslash/completionListInImportClause03.ts @@ -10,7 +10,4 @@ ////} // Ensure we don't filter out the current item. -goTo.marker(); -verify.completionListContains("abc"); -verify.completionListContains("def"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["abc", "def"] }); diff --git a/tests/cases/fourslash/completionListInImportClause04.ts b/tests/cases/fourslash/completionListInImportClause04.ts index 60ec5790120..321a38d8546 100644 --- a/tests/cases/fourslash/completionListInImportClause04.ts +++ b/tests/cases/fourslash/completionListInImportClause04.ts @@ -11,7 +11,7 @@ // @Filename: app.ts ////import {/*1*/} from './foo'; -verify.completionsAt("1", ["prototype", "prop1", "prop2"]); +verify.completions({ marker: "1", exact: ["prototype", "prop1", "prop2"] }); verify.noErrors(); goTo.marker('2'); verify.noErrors(); diff --git a/tests/cases/fourslash/completionListInImportClause05.ts b/tests/cases/fourslash/completionListInImportClause05.ts index 00b72737769..115e53fd5c0 100644 --- a/tests/cases/fourslash/completionListInImportClause05.ts +++ b/tests/cases/fourslash/completionListInImportClause05.ts @@ -12,4 +12,4 @@ // NOTE: The node_modules folder is in "/", rather than ".", because it requires // less scaffolding to mock. In particular, "/" is where we look for type roots. -verify.completionsAt("1", ["@e/f", "@a/b", "@c/d"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "1", exact: ["@e/f", "@a/b", "@c/d"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInImportClause06.ts b/tests/cases/fourslash/completionListInImportClause06.ts index 3dfcea3cdbf..e16039f633b 100644 --- a/tests/cases/fourslash/completionListInImportClause06.ts +++ b/tests/cases/fourslash/completionListInImportClause06.ts @@ -12,4 +12,4 @@ ////export declare let x: number; // Confirm that entries are de-dup'd. -verify.completionsAt("1", ["@a/b"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "1", exact: "@a/b", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInIndexSignature01.ts b/tests/cases/fourslash/completionListInIndexSignature01.ts index aaf97fee1a5..01032017b71 100644 --- a/tests/cases/fourslash/completionListInIndexSignature01.ts +++ b/tests/cases/fourslash/completionListInIndexSignature01.ts @@ -14,4 +14,9 @@ //// [x/*5*/yz: number]: boolean; //// [/*6*/ -goTo.eachMarker(() => verify.completionListAllowsNewIdentifier()); +const exact = completion.globalsPlus(["C"]); +verify.completions( + { marker: ["1", "2", "3", "6"], exact, isNewIdentifierLocation: true }, + { marker: "4", exact: ["str", ...exact], isNewIdentifierLocation: true }, + { marker: "5", exact: ["xyz", ...exact], isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionListInIndexSignature02.ts b/tests/cases/fourslash/completionListInIndexSignature02.ts index ce1f8b38e24..c7b725d4f7c 100644 --- a/tests/cases/fourslash/completionListInIndexSignature02.ts +++ b/tests/cases/fourslash/completionListInIndexSignature02.ts @@ -13,4 +13,8 @@ ////type T = { //// [xyz: /*5*/ -goTo.eachMarker(() => verify.not.completionListAllowsNewIdentifier()); +const exact = completion.globalTypesPlus(["I", "C"]); +verify.completions( + { marker: ["1", "2"], exact: ["T", ...exact] }, + { marker: ["3", "4", "5"], exact: completion.globalTypesPlus(["I", "C", "T"]) }, +); diff --git a/tests/cases/fourslash/completionListInMiddleOfIdentifierInArrowFunction01.ts b/tests/cases/fourslash/completionListInMiddleOfIdentifierInArrowFunction01.ts index c48e36c91c8..1d06df28a0b 100644 --- a/tests/cases/fourslash/completionListInMiddleOfIdentifierInArrowFunction01.ts +++ b/tests/cases/fourslash/completionListInMiddleOfIdentifierInArrowFunction01.ts @@ -2,5 +2,4 @@ ////xyz => x/*1*/y -goTo.marker("1"); -verify.completionListContains("xyz"); \ No newline at end of file +verify.completions({ marker: "1", includes: "xyz" }); diff --git a/tests/cases/fourslash/completionListInNamedClassExpression.ts b/tests/cases/fourslash/completionListInNamedClassExpression.ts index 8ca6806ce7f..466342ab630 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpression.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpression.ts @@ -7,8 +7,11 @@ //// /*1*/ //// } -goTo.marker("0"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); - -goTo.marker("1"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); \ No newline at end of file +verify.completions( + { marker: "0", includes: { name: "myClass", text: "(local class) myClass", kind: "local class" } }, + { + marker: "1", + exact: ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"], + isNewIdentifierLocation: true, + }, +); diff --git a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts index fd347d58037..ac6d9f1d17d 100644 --- a/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts +++ b/tests/cases/fourslash/completionListInNamedClassExpressionWithShadowing.ts @@ -15,26 +15,9 @@ //// /*5*/ //// } -goTo.marker("0"); -verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); - -goTo.marker("1"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); - -goTo.marker("2"); -verify.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); -verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); - -goTo.marker("3"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); -verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); - -goTo.marker("4"); -verify.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); - -goTo.marker("5"); -verify.not.completionListContains("myClass", "class myClass", /*documentation*/ undefined, "class"); -verify.not.completionListContains("myClass", "(local class) myClass", /*documentation*/ undefined, "local class"); +verify.completions( + { marker: "0", excludes: "myClass", isNewIdentifierLocation: true }, + { marker: ["1", "4"], includes: { name: "myClass", text: "class myClass", kind: "class" } }, + { marker: "2", includes: { name: "myClass", text: "(local class) myClass", kind: "local class" } }, + { marker: ["3", "5"], excludes: "myClass", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionListInNamedFunctionExpression.ts b/tests/cases/fourslash/completionListInNamedFunctionExpression.ts index d136ea45e9e..47973ddf8d2 100644 --- a/tests/cases/fourslash/completionListInNamedFunctionExpression.ts +++ b/tests/cases/fourslash/completionListInNamedFunctionExpression.ts @@ -14,14 +14,7 @@ /////*globalScope*/ ////fo/*referenceInGlobalScope*/o; -goTo.marker("globalScope"); -verify.completionListContains("foo"); - -goTo.marker("insideFunctionDeclaration"); -verify.completionListContains("foo"); - -goTo.marker("insideFunctionExpression"); -verify.completionListContains("foo"); +verify.completions({ marker: ["globalScope", "insideFunctionDeclaration", "insideFunctionExpression"], includes: "foo" }); verify.quickInfos({ referenceInsideFunctionExpression: "(local function) foo(): number", diff --git a/tests/cases/fourslash/completionListInNamedFunctionExpression1.ts b/tests/cases/fourslash/completionListInNamedFunctionExpression1.ts index bb64e04b93b..b8162894c0b 100644 --- a/tests/cases/fourslash/completionListInNamedFunctionExpression1.ts +++ b/tests/cases/fourslash/completionListInNamedFunctionExpression1.ts @@ -4,5 +4,4 @@ //// /*1*/ //// } -goTo.marker("1"); -verify.completionListContains("foo", "(local function) foo(): void", /*documentation*/ undefined, "local function"); \ No newline at end of file +verify.completions({ marker: "1", includes: { name: "foo", text: "(local function) foo(): void", kind: "local function" } }); diff --git a/tests/cases/fourslash/completionListInNamedFunctionExpressionWithShadowing.ts b/tests/cases/fourslash/completionListInNamedFunctionExpressionWithShadowing.ts index 14965253e84..d73c8ed3720 100644 --- a/tests/cases/fourslash/completionListInNamedFunctionExpressionWithShadowing.ts +++ b/tests/cases/fourslash/completionListInNamedFunctionExpressionWithShadowing.ts @@ -9,14 +9,7 @@ //// /*2*/ //// } -goTo.marker("0"); -verify.completionListContains("foo", "function foo(): void", /*documentation*/ undefined, "function"); -verify.not.completionListContains("foo", "(local function) foo(): void", /*documentation*/ undefined, "local function");; - -goTo.marker("1"); -verify.completionListContains("foo", "(local function) foo(): void", /*documentation*/ undefined, "local function"); -verify.not.completionListContains("foo", "function foo(): void", /*documentation*/ undefined, "function");; - -goTo.marker("2"); -verify.completionListContains("foo", "function foo(): void", /*documentation*/ undefined, "function") -verify.not.completionListContains("foo", "(local function) foo(): void", /*documentation*/ undefined, "local function");; \ No newline at end of file +verify.completions( + { marker: ["0", "2"], includes: { name: "foo", text: "function foo(): void", kind: "function" } }, + { marker: "1", includes: { name: "foo", text: "(local function) foo(): void", kind: "local function" } }, +); diff --git a/tests/cases/fourslash/completionListInNamespaceImportName01.ts b/tests/cases/fourslash/completionListInNamespaceImportName01.ts index ac1c0e13e07..10b502f8966 100644 --- a/tests/cases/fourslash/completionListInNamespaceImportName01.ts +++ b/tests/cases/fourslash/completionListInNamespaceImportName01.ts @@ -6,6 +6,4 @@ // @Filename: m2.ts ////import * as /**/ from "m1" -goTo.marker(); -verify.completionListIsEmpty(); -verify.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern01.ts b/tests/cases/fourslash/completionListInObjectBindingPattern01.ts index 99188457e6f..dc4adaa8d98 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern01.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern01.ts @@ -8,7 +8,4 @@ ////var foo: I; ////var { /**/ } = foo; -goTo.marker(); -verify.completionListContains("property1"); -verify.completionListContains("property2"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["property1", "property2"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern02.ts b/tests/cases/fourslash/completionListInObjectBindingPattern02.ts index 0cd86c8d1a6..33881d6978b 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern02.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern02.ts @@ -8,7 +8,4 @@ ////var foo: I; ////var { property1, /**/ } = foo; -goTo.marker(); -verify.completionListContains("property2"); -verify.not.completionListContains("property1"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: "property2" }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern03.ts b/tests/cases/fourslash/completionListInObjectBindingPattern03.ts index 72da68168bd..895f03a186d 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern03.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern03.ts @@ -8,6 +8,4 @@ ////var foo: I; ////var { property1: /**/ } = foo; -goTo.marker(); -verify.completionListAllowsNewIdentifier(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern04.ts b/tests/cases/fourslash/completionListInObjectBindingPattern04.ts index e6057ec0fae..2e093274f9b 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern04.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern04.ts @@ -8,7 +8,4 @@ ////var foo: I; ////var { prope/**/ } = foo; -goTo.marker(); -verify.completionListContains("property1"); -verify.completionListContains("property2"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["property1", "property2"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern05.ts b/tests/cases/fourslash/completionListInObjectBindingPattern05.ts index d0876ed6a34..e3a75457db8 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern05.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern05.ts @@ -8,6 +8,4 @@ ////var foo: I; ////var { property1/**/ } = foo; -goTo.marker(); -verify.completionListContains("property1"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["property1", "property2"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern06.ts b/tests/cases/fourslash/completionListInObjectBindingPattern06.ts index 8060c2bde78..d79659c5f6d 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern06.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern06.ts @@ -8,5 +8,4 @@ ////var foo: I; ////var { property1, property2, /**/ } = foo; -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern07.ts b/tests/cases/fourslash/completionListInObjectBindingPattern07.ts index 4db3fc383d4..6eff9015cbb 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern07.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern07.ts @@ -12,8 +12,4 @@ ////var foo: J; ////var { property1: { /**/ } } = foo; -goTo.marker(); -verify.completionListContains("propertyOfI_1"); -verify.completionListContains("propertyOfI_2"); -verify.not.completionListContains("property2"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["propertyOfI_1", "propertyOfI_2"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern08.ts b/tests/cases/fourslash/completionListInObjectBindingPattern08.ts index b062ca702a2..5d74383e187 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern08.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern08.ts @@ -12,8 +12,4 @@ ////var foo: J; ////var { property1: { propertyOfI_1, /**/ } } = foo; -goTo.marker(); -verify.completionListContains("propertyOfI_2"); -verify.not.completionListContains("propertyOfI_1"); -verify.not.completionListContains("property2"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: "propertyOfI_2" }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern09.ts b/tests/cases/fourslash/completionListInObjectBindingPattern09.ts index 61b31385b35..812f8946f1e 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern09.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern09.ts @@ -12,9 +12,4 @@ ////var foo: J; ////var { property1: { propertyOfI_1, }, /**/ } = foo; -goTo.marker(); -verify.completionListContains("property2"); -verify.not.completionListContains("property1"); -verify.not.completionListContains("propertyOfI_2"); -verify.not.completionListContains("propertyOfI_1"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["property2"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern10.ts b/tests/cases/fourslash/completionListInObjectBindingPattern10.ts index 836e12fd8a3..79776b13d3a 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern10.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern10.ts @@ -12,14 +12,7 @@ ////var foo: J[]; ////var [{ property1: { propertyOfI_1, }, /*1*/ }, { /*2*/ }] = foo; -goTo.marker("1"); -verify.completionListContains("property2"); -verify.not.completionListContains("property1"); -verify.not.completionListContains("propertyOfI_2"); -verify.not.completionListContains("propertyOfI_1"); -verify.not.completionListAllowsNewIdentifier(); - -goTo.marker("2"); -verify.completionListContains("property1"); -verify.completionListContains("property2"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions( + { marker: "1", exact: "property2" }, + { marker: "2", exact: ["property1", "property2"] }, +); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern11.ts b/tests/cases/fourslash/completionListInObjectBindingPattern11.ts index 57a32578026..ea1479f72b0 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern11.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern11.ts @@ -7,8 +7,4 @@ //// ////var { property1: prop1, /**/ }: I; -goTo.marker(""); -verify.completionListContains("property2"); -verify.not.completionListContains("property1"); -verify.not.completionListContains("prop1"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: "property2" }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern12.ts b/tests/cases/fourslash/completionListInObjectBindingPattern12.ts index 59af2da38d2..8941dda7f65 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern12.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern12.ts @@ -8,7 +8,4 @@ ////function f({ property1, /**/ }: I): void { ////} -goTo.marker(""); -verify.completionListContains("property2"); -verify.not.completionListContains("property1"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", includes: "property2", excludes: "property1" }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern13.ts b/tests/cases/fourslash/completionListInObjectBindingPattern13.ts index 8081d2ee23b..d1223a731bf 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern13.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern13.ts @@ -13,8 +13,4 @@ //// ////let { /**/ }: I | J = { x: 10 }; -goTo.marker(); -verify.completionListContains("x"); -verify.completionListContains("y"); -verify.not.completionListContains("z"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["x", "y"] }); diff --git a/tests/cases/fourslash/completionListInObjectBindingPattern14.ts b/tests/cases/fourslash/completionListInObjectBindingPattern14.ts index 425813a5543..4f1015d5237 100644 --- a/tests/cases/fourslash/completionListInObjectBindingPattern14.ts +++ b/tests/cases/fourslash/completionListInObjectBindingPattern14.ts @@ -5,5 +5,4 @@ //// protected bc; ////} -goTo.marker(); -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListInObjectLiteral.ts b/tests/cases/fourslash/completionListInObjectLiteral.ts index 4d0aca29f8d..b7125f27e1f 100644 --- a/tests/cases/fourslash/completionListInObjectLiteral.ts +++ b/tests/cases/fourslash/completionListInObjectLiteral.ts @@ -11,6 +11,4 @@ ////var t: thing; ////t.pos = { x: 4, y: 3 + t./**/ }; -goTo.marker(); -verify.not.completionListContains('x'); -verify.completionListContains('name'); \ No newline at end of file +verify.completions({ marker: "", exact: ["name", "pos"] }); diff --git a/tests/cases/fourslash/completionListInObjectLiteral2.ts b/tests/cases/fourslash/completionListInObjectLiteral2.ts index dad1d3bc249..34925d616a6 100644 --- a/tests/cases/fourslash/completionListInObjectLiteral2.ts +++ b/tests/cases/fourslash/completionListInObjectLiteral2.ts @@ -12,7 +12,7 @@ ////class Foo { //// public telemetryService: TelemetryService; // If telemetry service is of type 'any' (i.e. uncomment below line), the drop-down list works -//// public telemetryService2; +//// public telemetryService2; //// private test() { //// var onComplete = (searchResult: SearchResult) => { //// var hasResults = !searchResult.isEmpty(); // Drop-down list on searchResult fine here @@ -23,12 +23,4 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains('count'); -verify.completionListContains('isEmpty'); -verify.completionListContains('fileCount'); - -goTo.marker('2'); -verify.completionListContains('count'); -verify.completionListContains('isEmpty'); -verify.completionListContains('fileCount'); +verify.completions({ marker: test.markers(), exact: ["count", "isEmpty", "fileCount"] }); diff --git a/tests/cases/fourslash/completionListInObjectLiteral3.ts b/tests/cases/fourslash/completionListInObjectLiteral3.ts index f69a3c0e01f..7fa7de331be 100644 --- a/tests/cases/fourslash/completionListInObjectLiteral3.ts +++ b/tests/cases/fourslash/completionListInObjectLiteral3.ts @@ -8,8 +8,4 @@ //// /**/ ////} -goTo.marker() -verify.completionListContains('name'); -verify.completionListContains('children'); -verify.not.completionListContains('any'); -verify.not.completionListContains('number'); +verify.completions({ marker: "", exact: ["name", "children"] }); diff --git a/tests/cases/fourslash/completionListInObjectLiteral4.ts b/tests/cases/fourslash/completionListInObjectLiteral4.ts index 3094b4db6ad..57b13385049 100644 --- a/tests/cases/fourslash/completionListInObjectLiteral4.ts +++ b/tests/cases/fourslash/completionListInObjectLiteral4.ts @@ -20,7 +20,4 @@ ////funcE({ /*E*/ }); ////funcF({ /*F*/ }); -goTo.eachMarker(() => { - verify.completionListContains("hello"); - verify.completionListContains("world"); -}); +verify.completions({ marker: test.markers(), exact: ["hello", "world"] }); diff --git a/tests/cases/fourslash/completionListInObjectLiteralPropertyAssignment.ts b/tests/cases/fourslash/completionListInObjectLiteralPropertyAssignment.ts index 14ccd985577..eaa06242677 100644 --- a/tests/cases/fourslash/completionListInObjectLiteralPropertyAssignment.ts +++ b/tests/cases/fourslash/completionListInObjectLiteralPropertyAssignment.ts @@ -9,7 +9,4 @@ //// metadata: "/*1*/ ////} -goTo.marker('1'); - -verify.not.completionListContains("metadata"); -verify.not.completionListContains("wat"); \ No newline at end of file +verify.completions({ marker: "1", exact: [] }); diff --git a/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts b/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts index 94a1ba5c707..c72ac67194b 100644 --- a/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts +++ b/tests/cases/fourslash/completionListInObjectLiteralThatIsParameterOfFunctionCall.ts @@ -5,7 +5,4 @@ ////f({ //// /**/ -goTo.marker() -verify.completionListContains('xa'); -verify.completionListContains('xb'); -verify.completionListCount(2); \ No newline at end of file +verify.completions({ marker: "", exact: ["xa", "xb"] }); diff --git a/tests/cases/fourslash/completionListInScope.ts b/tests/cases/fourslash/completionListInScope.ts index 70f82b80f5f..00317438e91 100644 --- a/tests/cases/fourslash/completionListInScope.ts +++ b/tests/cases/fourslash/completionListInScope.ts @@ -2,7 +2,7 @@ ////module TestModule { //// var localVariable = ""; -//// export var exportedVaribale = 0; +//// export var exportedVariable = 0; //// //// function localFunction() { } //// export function exportedFunction() { } @@ -27,7 +27,7 @@ ////// Add some new items to the module ////module TestModule { //// var localVariable2 = ""; -//// export var exportedVaribale2 = 0; +//// export var exportedVariable2 = 0; //// //// function localFunction2() { } //// export function exportedFunction2() { } @@ -59,46 +59,53 @@ //// } ////} - -goTo.marker("valueReference"); -verify.completionListContains("localVariable"); -verify.completionListContains("exportedVaribale"); - -verify.completionListContains("localFunction"); -verify.completionListContains("exportedFunction"); - -verify.completionListContains("localClass"); -verify.completionListContains("exportedClass"); - -verify.completionListContains("localModule"); -verify.completionListContains("exportedModule"); - -verify.completionListContains("exportedVaribale2"); -verify.completionListContains("exportedFunction2"); -verify.completionListContains("exportedClass2"); -verify.completionListContains("exportedModule2"); - -goTo.marker("typeReference"); -verify.completionListContains("localInterface"); -verify.completionListContains("exportedInterface"); - -verify.completionListContains("localClass"); -verify.completionListContains("exportedClass"); - -verify.not.completionListContains("localModule"); -verify.not.completionListContains("exportedModule"); - -verify.completionListContains("exportedClass2"); -verify.not.completionListContains("exportedModule2"); - -goTo.marker("insideMethod"); -verify.not.completionListContains("property"); -verify.not.completionListContains("testMethod"); -verify.not.completionListContains("staticMethod"); - -verify.completionListContains("globalVar"); -verify.completionListContains("globalFunction"); - -verify.completionListContains("param"); -verify.completionListContains("localVar"); -verify.completionListContains("localFunction"); +verify.completions( + { + marker: "valueReference", + includes: [ + "localVariable", + "exportedVariable", + "localFunction", + "exportedFunction", + "localClass", + "exportedClass", + "localModule", + "exportedModule", + "exportedVariable2", + "exportedFunction2", + "exportedClass2", + "exportedModule2", + ], + isNewIdentifierLocation: true, // TODO: Should not be a new identifier location + }, + { + marker: "typeReference", + includes: [ + "localInterface", + "exportedInterface", + "localClass", + "exportedClass", + "exportedClass2", + ], + excludes: [ + "localModule", + "exportedModule", + "exportedModule2", + ], + }, + { + marker: "insideMethod", + includes: [ + "globalVar", + "globalFunction", + "param", + "localVar", + "localFunction", + ], + excludes: [ + "property", + "testMethod", + "staticMethod", + ], + }, +); diff --git a/tests/cases/fourslash/completionListInScope_doesNotIncludeAugmentations.ts b/tests/cases/fourslash/completionListInScope_doesNotIncludeAugmentations.ts index de70890c4c6..2432573314a 100644 --- a/tests/cases/fourslash/completionListInScope_doesNotIncludeAugmentations.ts +++ b/tests/cases/fourslash/completionListInScope_doesNotIncludeAugmentations.ts @@ -9,5 +9,4 @@ //// /////**/ -goTo.marker(); -verify.not.completionListContains("a"); +verify.completions({ marker: "", excludes: "a" }); diff --git a/tests/cases/fourslash/completionListInStringLiterals1.ts b/tests/cases/fourslash/completionListInStringLiterals1.ts index aabcc82eba5..2f6d59bf2d0 100644 --- a/tests/cases/fourslash/completionListInStringLiterals1.ts +++ b/tests/cases/fourslash/completionListInStringLiterals1.ts @@ -3,4 +3,4 @@ ////"/*1*/ /*2*/\/*3*/ //// /*4*/ \\/*5*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: [] }); diff --git a/tests/cases/fourslash/completionListInStringLiterals2.ts b/tests/cases/fourslash/completionListInStringLiterals2.ts index 4ffd5eb8a9b..c4e680c6387 100644 --- a/tests/cases/fourslash/completionListInStringLiterals2.ts +++ b/tests/cases/fourslash/completionListInStringLiterals2.ts @@ -4,4 +4,4 @@ //// /*4*/ \\\/*5*/ //// /*6*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: [] }); diff --git a/tests/cases/fourslash/completionListInTemplateLiteralParts1.ts b/tests/cases/fourslash/completionListInTemplateLiteralParts1.ts index 9de7b6a6a5b..509b08c80c2 100644 --- a/tests/cases/fourslash/completionListInTemplateLiteralParts1.ts +++ b/tests/cases/fourslash/completionListInTemplateLiteralParts1.ts @@ -4,4 +4,7 @@ //// /////*6*/`asdasd${/*7*/ 2 + 1.1 /*8*/} 12312 { -goTo.eachMarker(() => verify.completionListItemsCountIsGreaterThan(0)); +verify.completions( + { marker: ["1", "7"], exact: completion.globals, isNewIdentifierLocation: true }, + { marker: ["2", "3", "4", "5", "6", "8"], exact: completion.globals }, +); diff --git a/tests/cases/fourslash/completionListInTemplateLiteralPartsNegatives1.ts b/tests/cases/fourslash/completionListInTemplateLiteralPartsNegatives1.ts index 30af0678e7d..1c482cdc67d 100644 --- a/tests/cases/fourslash/completionListInTemplateLiteralPartsNegatives1.ts +++ b/tests/cases/fourslash/completionListInTemplateLiteralPartsNegatives1.ts @@ -4,4 +4,4 @@ //// ////`asdasd$/*7*/{ 2 + 1.1 }/*8*/ 12312 /*9*/{/*10*/ -goTo.eachMarker(() => verify.completionListIsEmpty()); +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/completionListInTypeParameterOfClassExpression1.ts b/tests/cases/fourslash/completionListInTypeParameterOfClassExpression1.ts index f8afcdc418c..290aa3a7ef6 100644 --- a/tests/cases/fourslash/completionListInTypeParameterOfClassExpression1.ts +++ b/tests/cases/fourslash/completionListInTypeParameterOfClassExpression1.ts @@ -2,17 +2,9 @@ ////var C0 = class D {} -////var C3 = class D{} -////var C5 = class D{} +////var C2 = class D{} +////var C4 = class D{} -goTo.marker("0"); -verify.completionListIsEmpty(); -goTo.marker("1"); -verify.completionListIsEmpty(); -goTo.marker("2"); -verify.completionListIsEmpty(); -goTo.marker("3"); -verify.completionListIsEmpty(); -goTo.marker("4"); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: ["0", "1", "2", "3"], exact: undefined }); +verify.completions({ marker: "4", exact: ["D", ...completion.globalsPlus(["C0", "C1", "C2", "C3", "C4"])] }); diff --git a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias1.ts b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias1.ts index 57931c7b6d1..b3ca601b6db 100644 --- a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias1.ts +++ b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias1.ts @@ -5,13 +5,8 @@ ////type List4 = /*2*/T[]; ////type List3 = /*3*/; -goTo.marker("0"); -verify.completionListIsEmpty(); -goTo.marker("1"); -verify.completionListIsEmpty(); -goTo.marker("2"); -verify.completionListContains("T"); -goTo.marker("3"); -verify.not.completionListIsEmpty(); -verify.not.completionListContains("T"); -verify.completionListContains("T1"); \ No newline at end of file +verify.completions( + { marker: ["0", "1"], exact: undefined }, + { marker: "2", includes: "T" }, + { marker: "3", includes: "T1", excludes: "T" }, +); diff --git a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias2.ts b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias2.ts index 44f7342029e..f4e184a8c0a 100644 --- a/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias2.ts +++ b/tests/cases/fourslash/completionListInTypeParameterOfTypeAlias2.ts @@ -5,15 +5,8 @@ ////type Map1 = /*2*/[]; ////type Map1 = = new a,/*1*/ -goTo.marker("1"); -verify.not.completionListContains("a"); -verify.not.completionListContains("b"); \ No newline at end of file +verify.completions({ marker: "1", excludes: ["a", "b"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedCommaExpression02.ts b/tests/cases/fourslash/completionListInUnclosedCommaExpression02.ts index e0ea3abbd38..44f579c653b 100644 --- a/tests/cases/fourslash/completionListInUnclosedCommaExpression02.ts +++ b/tests/cases/fourslash/completionListInUnclosedCommaExpression02.ts @@ -3,6 +3,4 @@ ////// should NOT see a and b ////foo((a, b) => (a,/*1*/ -goTo.marker("1"); -verify.completionListContains("a"); -verify.completionListContains("b"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["a", "b"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedDeleteExpression01.ts b/tests/cases/fourslash/completionListInUnclosedDeleteExpression01.ts index fdb67dfc335..28a850737ed 100644 --- a/tests/cases/fourslash/completionListInUnclosedDeleteExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedDeleteExpression01.ts @@ -3,5 +3,4 @@ ////var x; ////var y = delete /*1*/ -goTo.marker("1"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({marker: "1", includes: "x" }); diff --git a/tests/cases/fourslash/completionListInUnclosedDeleteExpression02.ts b/tests/cases/fourslash/completionListInUnclosedDeleteExpression02.ts index 3573c345285..d0145bb8977 100644 --- a/tests/cases/fourslash/completionListInUnclosedDeleteExpression02.ts +++ b/tests/cases/fourslash/completionListInUnclosedDeleteExpression02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => delete /*1*/ -goTo.marker("1"); -verify.completionListContains("x"); -verify.completionListContains("p"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["x", "p"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedElementAccessExpression01.ts b/tests/cases/fourslash/completionListInUnclosedElementAccessExpression01.ts index 59c4922671e..2c11029b9aa 100644 --- a/tests/cases/fourslash/completionListInUnclosedElementAccessExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedElementAccessExpression01.ts @@ -3,5 +3,4 @@ ////var x; ////var y = x[/*1*/ -goTo.marker("1"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: "x" }); diff --git a/tests/cases/fourslash/completionListInUnclosedElementAccessExpression02.ts b/tests/cases/fourslash/completionListInUnclosedElementAccessExpression02.ts index 1d6403cfa10..b9f7d411ac6 100644 --- a/tests/cases/fourslash/completionListInUnclosedElementAccessExpression02.ts +++ b/tests/cases/fourslash/completionListInUnclosedElementAccessExpression02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => x[/*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedForLoop01.ts b/tests/cases/fourslash/completionListInUnclosedForLoop01.ts index 35e5efdd304..83cb4bb5c58 100644 --- a/tests/cases/fourslash/completionListInUnclosedForLoop01.ts +++ b/tests/cases/fourslash/completionListInUnclosedForLoop01.ts @@ -2,5 +2,4 @@ ////for (let i = 0; /*1*/ -goTo.marker("1"); -verify.completionListContains("i"); \ No newline at end of file +verify.completions({ marker: "1", includes: "i" }); diff --git a/tests/cases/fourslash/completionListInUnclosedForLoop02.ts b/tests/cases/fourslash/completionListInUnclosedForLoop02.ts index e79f428b2b0..c749ad57dbc 100644 --- a/tests/cases/fourslash/completionListInUnclosedForLoop02.ts +++ b/tests/cases/fourslash/completionListInUnclosedForLoop02.ts @@ -2,5 +2,4 @@ ////for (let i = 0; i < 10; i++) /*1*/ -goTo.marker("1"); -verify.completionListContains("i"); \ No newline at end of file +verify.completions({ marker: "1", includes: "i" }); diff --git a/tests/cases/fourslash/completionListInUnclosedIndexSignature01.ts b/tests/cases/fourslash/completionListInUnclosedIndexSignature01.ts index 0667742d4cb..07afc0d7c38 100644 --- a/tests/cases/fourslash/completionListInUnclosedIndexSignature01.ts +++ b/tests/cases/fourslash/completionListInUnclosedIndexSignature01.ts @@ -5,6 +5,4 @@ //// [foo: string]: typeof /*1*/ ////} -goTo.marker("1"); -verify.completionListContains("foo"); -verify.completionListContains("C"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["foo", "C"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedIndexSignature02.ts b/tests/cases/fourslash/completionListInUnclosedIndexSignature02.ts index 54612d3efcf..57b3268aecc 100644 --- a/tests/cases/fourslash/completionListInUnclosedIndexSignature02.ts +++ b/tests/cases/fourslash/completionListInUnclosedIndexSignature02.ts @@ -5,9 +5,6 @@ //// [foo: /*1*/ ////} -goTo.marker("1"); -verify.completionListContains("C"); -verify.not.completionListContains("foo"); // ideally this shouldn't show up for a type +verify.completions({ marker: "1", includes: "C", excludes: "foo" }); edit.insert("typeof "); -verify.completionListContains("C"); -verify.completionListContains("foo"); \ No newline at end of file +verify.completions({ includes: ["C", "foo"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedIndexSignature03.ts b/tests/cases/fourslash/completionListInUnclosedIndexSignature03.ts index bb4ef808bff..f21b987e396 100644 --- a/tests/cases/fourslash/completionListInUnclosedIndexSignature03.ts +++ b/tests/cases/fourslash/completionListInUnclosedIndexSignature03.ts @@ -5,6 +5,4 @@ //// [foo: string]: { x: typeof /*1*/ ////} -goTo.marker("1"); -verify.completionListContains("foo"); -verify.completionListContains("C"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["foo", "C"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature01.ts b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature01.ts index ed4468b896a..3d2710e74e0 100644 --- a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature01.ts +++ b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature01.ts @@ -7,12 +7,8 @@ //// ////declare function foo(obj: I): { str: T/*1*/ -goTo.marker("1"); - -verify.completionListContains("I"); -verify.completionListContains("TString"); -verify.completionListContains("TNumber"); - -// Ideally the following shouldn't show up since they're not types. -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); +verify.completions({ + marker: "1", + includes: ["I", "TString", "TNumber"], + excludes: ["foo", "obj"], // not types +}); diff --git a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature03.ts b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature03.ts index 61fa0912007..da975ba18f6 100644 --- a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature03.ts +++ b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature03.ts @@ -7,12 +7,8 @@ //// ////declare function foo(obj: I): { str: TString/*1*/ -goTo.marker("1"); - -verify.completionListContains("I"); -verify.completionListContains("TString"); -verify.completionListContains("TNumber"); // REVIEW: Is this intended behavior? - -// Ideally the following shouldn't show up since they're not types. -verify.not.completionListContains("foo"); -verify.not.completionListContains("obj"); +verify.completions({ + marker: "1", + includes: ["I", "TString", "TNumber"], + excludes: ["foo", "obj"], // not types +}); diff --git a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts index 5a9731ca0e3..587db09d267 100644 --- a/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts +++ b/tests/cases/fourslash/completionListInUnclosedObjectTypeLiteralInSignature04.ts @@ -7,4 +7,4 @@ //// ////declare function foo(obj: I): { /*1*/ -verify.completionsAt("1", ["readonly"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "1", exact: "readonly", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedSpreadExpression01.ts b/tests/cases/fourslash/completionListInUnclosedSpreadExpression01.ts index b9cc01f0a66..a2ad320d483 100644 --- a/tests/cases/fourslash/completionListInUnclosedSpreadExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedSpreadExpression01.ts @@ -3,5 +3,4 @@ ////var x; ////var y = [1,2,.../*1*/ -goTo.marker("1"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: "x" }); diff --git a/tests/cases/fourslash/completionListInUnclosedSpreadExpression02.ts b/tests/cases/fourslash/completionListInUnclosedSpreadExpression02.ts index 40d90370232..94d2d67b380 100644 --- a/tests/cases/fourslash/completionListInUnclosedSpreadExpression02.ts +++ b/tests/cases/fourslash/completionListInUnclosedSpreadExpression02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => [1,2,.../*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedTaggedTemplate01.ts b/tests/cases/fourslash/completionListInUnclosedTaggedTemplate01.ts index 20e2a5d0663..6b0c3fd7eb1 100644 --- a/tests/cases/fourslash/completionListInUnclosedTaggedTemplate01.ts +++ b/tests/cases/fourslash/completionListInUnclosedTaggedTemplate01.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => x `abc ${ /*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedTaggedTemplate02.ts b/tests/cases/fourslash/completionListInUnclosedTaggedTemplate02.ts index d4bbd5992c6..dc5f17cbebe 100644 --- a/tests/cases/fourslash/completionListInUnclosedTaggedTemplate02.ts +++ b/tests/cases/fourslash/completionListInUnclosedTaggedTemplate02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => x `abc ${ 123 } ${ /*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedTemplate01.ts b/tests/cases/fourslash/completionListInUnclosedTemplate01.ts index c7b8f628170..6f9f99b2106 100644 --- a/tests/cases/fourslash/completionListInUnclosedTemplate01.ts +++ b/tests/cases/fourslash/completionListInUnclosedTemplate01.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => `abc ${ /*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedTemplate02.ts b/tests/cases/fourslash/completionListInUnclosedTemplate02.ts index 5fd5c94ee3e..6e53aff9b80 100644 --- a/tests/cases/fourslash/completionListInUnclosedTemplate02.ts +++ b/tests/cases/fourslash/completionListInUnclosedTemplate02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => `abc ${ 123 } ${ /*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListInUnclosedTypeArguments.ts b/tests/cases/fourslash/completionListInUnclosedTypeArguments.ts index 43458be9ff4..31397518ed8 100644 --- a/tests/cases/fourslash/completionListInUnclosedTypeArguments.ts +++ b/tests/cases/fourslash/completionListInUnclosedTypeArguments.ts @@ -11,32 +11,26 @@ ////f(); //// ////f2 -////f2 -////f2(); +////f2 +////f2 +////f2(); //// -////f2/*4x*/T/*5x*/y/*6x*/ ////f2<() =>/*1y*/T/*2y*/y/*3y*/, () =>/*4y*/T/*5y*/y/*6y*/ ////f2/*1z*/T/*2z*/y/*3z*/ - -goTo.eachMarker((marker) => { - const markerName = test.markerName(marker); - if (markerName.endsWith("TypeOnly")) { - verify.not.completionListContains("x"); - } - else { - verify.completionListContains("x"); - } - - if (markerName.endsWith("ValueOnly")) { - verify.not.completionListContains("Type"); - } - else { - verify.completionListContains("Type"); - } -}); \ No newline at end of file +goTo.eachMarker(marker => { + 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" : [], + isNewIdentifierLocation: marker.data && marker.data.newId || false, + }); +}); diff --git a/tests/cases/fourslash/completionListInUnclosedTypeOfExpression01.ts b/tests/cases/fourslash/completionListInUnclosedTypeOfExpression01.ts index 3da8b4fd616..079173b02e6 100644 --- a/tests/cases/fourslash/completionListInUnclosedTypeOfExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedTypeOfExpression01.ts @@ -3,5 +3,4 @@ ////var x; ////var y = typeof /*1*/ -goTo.marker("1"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: "x" }); diff --git a/tests/cases/fourslash/completionListInUnclosedTypeOfExpression02.ts b/tests/cases/fourslash/completionListInUnclosedTypeOfExpression02.ts index b1d347211ac..7f3e9b17ddb 100644 --- a/tests/cases/fourslash/completionListInUnclosedTypeOfExpression02.ts +++ b/tests/cases/fourslash/completionListInUnclosedTypeOfExpression02.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => typeof /*1*/ -goTo.marker("1"); -verify.completionListContains("x"); -verify.completionListContains("p"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["x", "p"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedVoidExpression01.ts b/tests/cases/fourslash/completionListInUnclosedVoidExpression01.ts index d1cfecbffec..a51b9b5f9f3 100644 --- a/tests/cases/fourslash/completionListInUnclosedVoidExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedVoidExpression01.ts @@ -3,6 +3,4 @@ ////var x; ////var y = (p) => void /*1*/ -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", includes: ["p", "x"] }); diff --git a/tests/cases/fourslash/completionListInUnclosedYieldExpression01.ts b/tests/cases/fourslash/completionListInUnclosedYieldExpression01.ts index 658b0de7dc8..89b50e7bff5 100644 --- a/tests/cases/fourslash/completionListInUnclosedYieldExpression01.ts +++ b/tests/cases/fourslash/completionListInUnclosedYieldExpression01.ts @@ -3,8 +3,5 @@ ////var x; ////var y = function* gen(p) { yield /*1*/ -goTo.marker("1"); // These tentatively don't work. -verify.not.completionListContains("p"); -verify.not.completionListContains("gen"); -verify.not.completionListContains("x"); \ No newline at end of file +verify.completions({ marker: "1", exact: undefined }); diff --git a/tests/cases/fourslash/completionListInsideTargetTypedFunction.ts b/tests/cases/fourslash/completionListInsideTargetTypedFunction.ts index 68d7f3081f7..2ab796f7d82 100644 --- a/tests/cases/fourslash/completionListInsideTargetTypedFunction.ts +++ b/tests/cases/fourslash/completionListInsideTargetTypedFunction.ts @@ -5,5 +5,4 @@ //// var foo: iFace = function (elem) { /**/ } ////} -goTo.marker(); -verify.completionListContains("elem", "(parameter) elem: string"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "elem", text: "(parameter) elem: string" } }); diff --git a/tests/cases/fourslash/completionListInstanceProtectedMembers.ts b/tests/cases/fourslash/completionListInstanceProtectedMembers.ts index 87207db733a..7e39a21bf5a 100644 --- a/tests/cases/fourslash/completionListInstanceProtectedMembers.ts +++ b/tests/cases/fourslash/completionListInstanceProtectedMembers.ts @@ -29,35 +29,14 @@ //// protected protectedOverriddenProperty; ////} - -// Same class, everything is visible -goTo.marker("1"); -verify.completionListContains('privateMethod'); -verify.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -goTo.marker("2"); -verify.completionListContains('privateMethod'); -verify.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -// Can not access protected properties overridden in subclass -goTo.marker("3"); -verify.completionListContains('privateMethod'); -verify.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); +verify.completions( + { + marker: ["1", "2"], + exact: ["privateMethod", "privateProperty", "protectedMethod", "protectedProperty", "publicMethod", "publicProperty", "protectedOverriddenMethod", "protectedOverriddenProperty", "test"], + }, + { + marker: "3", + // Can not access protected properties overridden in subclass + exact: ["privateMethod", "privateProperty", "protectedMethod", "protectedProperty", "publicMethod", "publicProperty", "test"], + }, +); diff --git a/tests/cases/fourslash/completionListInstanceProtectedMembers2.ts b/tests/cases/fourslash/completionListInstanceProtectedMembers2.ts index 0733cb4d7da..ebbfb95cb35 100644 --- a/tests/cases/fourslash/completionListInstanceProtectedMembers2.ts +++ b/tests/cases/fourslash/completionListInstanceProtectedMembers2.ts @@ -30,47 +30,29 @@ //// } ////} - -// Same class, everything is visible -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -// Can not access properties on super -goTo.marker("2"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.not.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); - -// Can not access protected properties through base class -goTo.marker("3"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); - -// Same class, everything is visible -goTo.marker("4"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); +verify.completions( + { + // Same class, everything is visible + marker: "1", + includes: ["protectedMethod", "protectedProperty", "publicMethod", "publicProperty", "protectedOverriddenMethod", "protectedOverriddenProperty"], + excludes: ["privateMethod", "privateProperty"], + }, + { + // Can not access properties on super + marker: "2", + includes: ["protectedMethod", "publicMethod", "protectedOverriddenMethod"], + excludes: ["privateMethod", "privateProperty", "protectedProperty", "publicProperty", "protectedOverriddenProperty"], + }, + { + // Can not access protected properties through base class + marker: "3", + includes: ["publicMethod", "publicProperty"], + excludes: ["privateMethod", "privateProperty", "protectedMethod", "protectedProperty", "protectedOverriddenMethod", "protectedOverriddenProperty"], + }, + { + // Same class, everything is visible + marker: "4", + includes: ["protectedMethod", "protectedProperty", "publicMethod", "publicProperty", "protectedOverriddenMethod", "protectedOverriddenProperty"], + excludes: ["privateMethod", "privateProperty"], + }, +); diff --git a/tests/cases/fourslash/completionListInstanceProtectedMembers3.ts b/tests/cases/fourslash/completionListInstanceProtectedMembers3.ts index 5454fa10ef0..6f87abf10f0 100644 --- a/tests/cases/fourslash/completionListInstanceProtectedMembers3.ts +++ b/tests/cases/fourslash/completionListInstanceProtectedMembers3.ts @@ -25,22 +25,4 @@ //// c./*2*/; // Only public properties are visible outside the class -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); - -goTo.marker("2"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); +verify.completions({ marker: ["1", "2"], exact: ["publicMethod", "publicProperty"] }); diff --git a/tests/cases/fourslash/completionListInstanceProtectedMembers4.ts b/tests/cases/fourslash/completionListInstanceProtectedMembers4.ts index b4f282d19fe..1ab01c0bff6 100644 --- a/tests/cases/fourslash/completionListInstanceProtectedMembers4.ts +++ b/tests/cases/fourslash/completionListInstanceProtectedMembers4.ts @@ -22,13 +22,4 @@ //// var c: C1; //// c./*1*/ - -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); +verify.completions({ marker: "1", exact: ["protectedOverriddenMethod", "protectedOverriddenProperty", "publicMethod", "publicProperty"] }); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames.ts b/tests/cases/fourslash/completionListInvalidMemberNames.ts index 3dc54274e83..2f124758d69 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames.ts @@ -14,18 +14,21 @@ ////x[|./*a*/|]; ////x["/*b*/"]; -verify.completionsAt("b", ["foo ", "bar", "break", "any", "#", "$", "b", "1b"]); - const replacementSpan = test.ranges()[0]; -verify.completionsAt("a", [ - { name: "foo ", insertText: '["foo "]', replacementSpan }, - "bar", - "break", - "any", - { name: "#", insertText: '["#"]', replacementSpan }, - "$", - "b", - { name: "1b", insertText: '["1b"]', replacementSpan }, -], { - includeInsertTextCompletions: true, -}); +verify.completions( + { marker: "b", exact: ["foo ", "bar", "break", "any", "#", "$", "b", "1b"] }, + { + marker: "a", + exact: [ + { name: "foo ", insertText: '["foo "]', replacementSpan }, + "bar", + "break", + "any", + { name: "#", insertText: '["#"]', replacementSpan }, + "$", + "b", + { name: "1b", insertText: '["1b"]', replacementSpan }, + ], + preferences: { includeInsertTextCompletions: true }, + }, +); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames2.ts b/tests/cases/fourslash/completionListInvalidMemberNames2.ts index 153ed3bdb5e..b7f18b7f71b 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames2.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames2.ts @@ -15,5 +15,4 @@ ////var _ : SomeInterface; ////_./**/ -goTo.marker(); -verify.not.completionListContains("[Symbol.hasInstance]"); +verify.completions({ marker: "", exact: completion.functionMembersWithPrototype }); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames_escapeQuote.ts b/tests/cases/fourslash/completionListInvalidMemberNames_escapeQuote.ts index e61c9bc874a..4ec5a611e43 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames_escapeQuote.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames_escapeQuote.ts @@ -4,9 +4,17 @@ ////x[|./**/|]; const replacementSpan = test.ranges()[0]; -verify.completionsAt("", [{ name: `"'`, insertText: `["\\"'"]`, replacementSpan }], { includeInsertTextCompletions: true }); - -verify.completionsAt("", [{ name: `"'`, insertText: `['"\\'']`, replacementSpan }], { - includeInsertTextCompletions: true, - quotePreference: "single", +verify.completions({ + marker: "", + exact: { name: `"'`, insertText: `["\\"'"]`, replacementSpan }, + preferences: { includeInsertTextCompletions: true }, +}); + +verify.completions({ + marker: "", + exact: { name: `"'`, insertText: `['"\\'']`, replacementSpan }, + preferences: { + includeInsertTextCompletions: true, + quotePreference: "single", + }, }); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames_startWithSpace.ts b/tests/cases/fourslash/completionListInvalidMemberNames_startWithSpace.ts index f86c8a5a813..be1310d9671 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames_startWithSpace.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames_startWithSpace.ts @@ -5,4 +5,8 @@ const replacementSpan = test.ranges()[0]; // No completion for " foo" because it starts with a space. See https://github.com/Microsoft/TypeScript/pull/20547 -verify.completionsAt("", [{ name: "foo ", insertText: '["foo "]', replacementSpan }], { includeInsertTextCompletions: true }); +verify.completions({ + marker: "", + exact: [{ name: "foo ", insertText: '["foo "]', replacementSpan }], + preferences: { includeInsertTextCompletions: true }, +}); diff --git a/tests/cases/fourslash/completionListInvalidMemberNames_withExistingIdentifier.ts b/tests/cases/fourslash/completionListInvalidMemberNames_withExistingIdentifier.ts index 3c06692293e..3e75bd26be0 100644 --- a/tests/cases/fourslash/completionListInvalidMemberNames_withExistingIdentifier.ts +++ b/tests/cases/fourslash/completionListInvalidMemberNames_withExistingIdentifier.ts @@ -6,5 +6,15 @@ ////unrelatedIdentifier; const [r0, r1] = test.ranges(); -verify.completionsAt("0", [{ name: "foo ", insertText: '["foo "]', replacementSpan: r0 }], { includeInsertTextCompletions: true }); -verify.completionsAt("1", [{ name: "foo ", insertText: '["foo "]', replacementSpan: r1 }], { includeInsertTextCompletions: true }); +verify.completions( + { + marker: "0", + exact: [{ name: "foo ", insertText: '["foo "]', replacementSpan: r0 }], + preferences: { includeInsertTextCompletions: true }, + }, + { + marker: "1", + exact: [{ name: "foo ", insertText: '["foo "]', replacementSpan: r1 }], + preferences: { includeInsertTextCompletions: true }, + }, +); diff --git a/tests/cases/fourslash/completionListIsGlobalCompletion.ts b/tests/cases/fourslash/completionListIsGlobalCompletion.ts index 121ab940d65..f8ee9430537 100644 --- a/tests/cases/fourslash/completionListIsGlobalCompletion.ts +++ b/tests/cases/fourslash/completionListIsGlobalCompletion.ts @@ -34,41 +34,19 @@ ////const z =
; // no globals in jsx attribute with syntax error ////const x = `/*14*/ ${/*15*/}`; // globals only in template expression ////var user = ; // globals only in JSX expression (but not in JSX expression strings) -goTo.marker("1"); -verify.completionListIsGlobal(false); -goTo.marker("2"); -verify.completionListIsGlobal(false); -goTo.marker("3"); -verify.completionListIsGlobal(false); -goTo.marker("4"); -verify.completionListIsGlobal(false); -goTo.marker("5"); -verify.completionListIsGlobal(true); -goTo.marker("6"); -verify.completionListIsGlobal(false); -goTo.marker("7"); -verify.completionListIsGlobal(true); -goTo.marker("8"); -verify.completionListIsGlobal(false); -goTo.marker("9"); -verify.completionListIsGlobal(false); -goTo.marker("10"); -verify.completionListIsGlobal(false); -goTo.marker("11"); -verify.completionListIsGlobal(true); -goTo.marker("12"); -verify.completionListIsGlobal(false); -goTo.marker("13"); -verify.completionListIsGlobal(false); -goTo.marker("14"); -verify.completionListIsGlobal(false); -goTo.marker("15"); -verify.completionListIsGlobal(true); -goTo.marker("16"); -verify.completionListIsGlobal(false); -goTo.marker("17"); -verify.completionListIsGlobal(false); -goTo.marker("18"); -verify.completionListIsGlobal(true); -goTo.marker("19"); -verify.completionListIsGlobal(false); \ No newline at end of file + +const x = ["test", "A", "B", "C", "y", "z", "x", "user"]; +const globals: ReadonlyArray = [...x, ...completion.globals] +verify.completions( + { marker: ["1", "3", "6", "8", "12", "14"], exact: undefined, isGlobalCompletion: false }, + { marker: "2", exact: ["a.ts", "file.ts"], isGlobalCompletion: false, isNewIdentifierLocation: true }, + { marker: ["4", "19"], exact: [], isGlobalCompletion: false }, + { marker: ["5", "11", "18"], exact: globals, isGlobalCompletion: true }, + { marker: "7", exact: completion.globalsInsideFunction(x), isGlobalCompletion: true }, + { marker: "9", exact: ["x", "y"], isGlobalCompletion: false }, + { marker: "10", exact: completion.classElementKeywords, isGlobalCompletion: false, isNewIdentifierLocation: true }, + { marker: "13", exact: globals, isGlobalCompletion: false }, + { marker: "15", exact: globals, isGlobalCompletion: true, isNewIdentifierLocation: true }, + { marker: "16", exact: [...x, ...completion.globalsVars, "undefined"], isGlobalCompletion: false }, + { marker: "17", exact: completion.globalKeywordsPlusUndefined, isGlobalCompletion: false }, +); diff --git a/tests/cases/fourslash/completionListKeywords.ts b/tests/cases/fourslash/completionListKeywords.ts index 8b9a8cc222c..660099d3188 100644 --- a/tests/cases/fourslash/completionListKeywords.ts +++ b/tests/cases/fourslash/completionListKeywords.ts @@ -1,42 +1,7 @@ /// -//// +// @noLib: true -verify.completions({ - includes: [ - "break", - "case", - "catch", - "class", - "continue", - "debugger", - "declare", - "default", - "delete", - "do", - "else", - "enum", - "export", - "extends", - "false", - "finally", - "for", - "function", - "if", - "instanceof", - "interface", - "module", - "new", - "return", - "super", - "switch", - "this", - "throw", - "true", - "try", - "typeof", - "var", - "while", - "with", - ], -}); +/////**/ + +verify.completions({ marker: "", exact: ["undefined", ...completion.statementKeywordsWithTypes] }); diff --git a/tests/cases/fourslash/completionListModuleMembers.ts b/tests/cases/fourslash/completionListModuleMembers.ts index 48278652fb5..9881fb3b7f7 100644 --- a/tests/cases/fourslash/completionListModuleMembers.ts +++ b/tests/cases/fourslash/completionListModuleMembers.ts @@ -21,40 +21,13 @@ //// ////interface TestInterface implements Module./*TypeReferenceInImplementsList*/ { } -function getVerify(isTypeLocation: boolean) { - return { - verifyValue: isTypeLocation ? verify.not : verify, - verifyType: isTypeLocation ? verify : verify.not, - verifyValueOrType: verify, - verifyNotValueOrType: verify.not, - }; -} - -function verifyModuleMembers(marker: string, isTypeLocation: boolean) { - goTo.marker(marker); - - const { verifyValue, verifyType, verifyValueOrType, verifyNotValueOrType } = getVerify(isTypeLocation); - - verifyValue.completionListContains("exportedVariable"); - verifyValue.completionListContains("exportedFunction"); - verifyValue.completionListContains("exportedModule"); - - verifyValueOrType.completionListContains("exportedClass"); - - // Include type declarations - verifyType.completionListContains("exportedInterface"); - - // No inner declarations - verifyNotValueOrType.completionListContains("innerVariable"); - verifyNotValueOrType.completionListContains("innerFunction"); - verifyNotValueOrType.completionListContains("innerClass"); - verifyNotValueOrType.completionListContains("innerModule"); - verifyNotValueOrType.completionListContains("innerInterface"); - - verifyNotValueOrType.completionListContains("exportedInnerModuleVariable"); -} - -verifyModuleMembers("ValueReference", /*isTypeLocation*/ false); -verifyModuleMembers("TypeReference", /*isTypeLocation*/ true); -verifyModuleMembers("TypeReferenceInExtendsList", /*isTypeLocation*/ false); -verifyModuleMembers("TypeReferenceInImplementsList", /*isTypeLocation*/ true); +verify.completions( + { + marker: ["ValueReference", "TypeReferenceInExtendsList"], + exact: ["exportedFunction", "exportedVariable", "exportedClass", "exportedModule"], + }, + { + marker: ["TypeReference", "TypeReferenceInImplementsList"], + exact: ["exportedClass", "exportedInterface"], + }, +); diff --git a/tests/cases/fourslash/completionListNewIdentifierBindingElement.ts b/tests/cases/fourslash/completionListNewIdentifierBindingElement.ts index 753d6c7d4d2..3513e33484f 100644 --- a/tests/cases/fourslash/completionListNewIdentifierBindingElement.ts +++ b/tests/cases/fourslash/completionListNewIdentifierBindingElement.ts @@ -2,5 +2,4 @@ ////var { x:html/*1*/ -goTo.marker("1"); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "1", exact: undefined }); diff --git a/tests/cases/fourslash/completionListNewIdentifierFunctionDeclaration.ts b/tests/cases/fourslash/completionListNewIdentifierFunctionDeclaration.ts index 1f8b24d1cf1..f6303f8441d 100644 --- a/tests/cases/fourslash/completionListNewIdentifierFunctionDeclaration.ts +++ b/tests/cases/fourslash/completionListNewIdentifierFunctionDeclaration.ts @@ -1,8 +1,11 @@ /// +// @noLib: true + ////function F(pref: (a/*1*/ -goTo.eachMarker(() => { - verify.not.completionListIsEmpty(); - verify.completionListAllowsNewIdentifier(); +verify.completions({ + marker: "1", + exact: completion.typeKeywords, + isNewIdentifierLocation: true, }); diff --git a/tests/cases/fourslash/completionListNewIdentifierVariableDeclaration.ts b/tests/cases/fourslash/completionListNewIdentifierVariableDeclaration.ts index cdebbaa1334..c9900cf86ac 100644 --- a/tests/cases/fourslash/completionListNewIdentifierVariableDeclaration.ts +++ b/tests/cases/fourslash/completionListNewIdentifierVariableDeclaration.ts @@ -2,6 +2,5 @@ ////var y : (s:string, list/*2*/ -goTo.marker("2"); -verify.completionListIsEmpty(); // Parameter name -verify.completionListAllowsNewIdentifier(); \ No newline at end of file +// Parameter name +verify.completions({ marker: "2", exact: undefined, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionListObjectMembers.ts b/tests/cases/fourslash/completionListObjectMembers.ts index ae773c1c3b4..ebf50ae18db 100644 --- a/tests/cases/fourslash/completionListObjectMembers.ts +++ b/tests/cases/fourslash/completionListObjectMembers.ts @@ -9,6 +9,7 @@ //// }; ////object./**/ -goTo.marker(); -verify.completionListContains("bar", '(property) bar: any'); -verify.completionListContains("foo", '(method) foo(bar: any): any'); +verify.completions({ + marker: "", + includes: [{ name: "bar", text: "(property) bar: any" }, { name: "foo", text: "(method) foo(bar: any): any" }], +}); diff --git a/tests/cases/fourslash/completionListOfGenericSymbol.ts b/tests/cases/fourslash/completionListOfGenericSymbol.ts new file mode 100644 index 00000000000..804b2c1d297 --- /dev/null +++ b/tests/cases/fourslash/completionListOfGenericSymbol.ts @@ -0,0 +1,24 @@ +/// + +// Ensure kind is set correctly on completions of a generic symbol + +////var a = [1,2,3]; +////a./**/ + +verify.completions({ + marker: "", + includes: [ + { + name: "length", + text: "(property) Array.length: number", + documentation: "Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.", + kind: "property", + }, + { + name: "toString", + text: "(method) Array.toString(): string", + documentation: "Returns a string representation of an array.", + kind: "method", + }, + ], +}); diff --git a/tests/cases/fourslash/completionListOfGnericSymbol.ts b/tests/cases/fourslash/completionListOfGnericSymbol.ts deleted file mode 100644 index 9251892db23..00000000000 --- a/tests/cases/fourslash/completionListOfGnericSymbol.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -// Ensure kind is set correctelly on completions of a generic symbol - -////var a = [1,2,3]; -////a./**/ - -goTo.marker(); -verify.completionListContains('length', "(property) Array.length: number", /*docComments*/ undefined, /*kind*/ "property"); -verify.completionListContains('toString', "(method) Array.toString(): string", /*docComments*/ undefined, /*kind*/ "method"); - diff --git a/tests/cases/fourslash/completionListOfSplitInterface.ts b/tests/cases/fourslash/completionListOfSplitInterface.ts index 9bc635d8f8b..df84dc96d1b 100644 --- a/tests/cases/fourslash/completionListOfSplitInterface.ts +++ b/tests/cases/fourslash/completionListOfSplitInterface.ts @@ -32,19 +32,7 @@ ////var ci1: I1; ////ci1./*2*/b; -goTo.marker('1'); -verify.completionListCount(6); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("c"); -verify.completionListContains("i1"); -verify.completionListContains("i2"); -verify.completionListContains("i3"); - -goTo.marker('2'); -verify.completionListCount(5); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListContains("b1"); -verify.completionListContains("i11"); -verify.completionListContains("i12"); +verify.completions( + { marker: "1", exact: ["i1", "i2", "i3", "a", "b", "c"] }, + { marker: "2", exact: ["i11", "i12", "a", "b", "b1"] }, +); diff --git a/tests/cases/fourslash/completionListOfUnion.ts b/tests/cases/fourslash/completionListOfUnion.ts index c323c83d054..740113099f7 100644 --- a/tests/cases/fourslash/completionListOfUnion.ts +++ b/tests/cases/fourslash/completionListOfUnion.ts @@ -9,12 +9,14 @@ ////function f(...args: Array) {} ////f({ /*f*/ }); -goTo.marker("x"); -verify.completionListCount(3); -verify.completionListContains("a", "(property) a: string | number"); -verify.completionListContains("b", "(property) b: number | boolean"); -verify.completionListContains("c", "(property) c: string"); - -goTo.marker("f"); -verify.completionListContains("a", "(property) I.a: number"); -// Also contains array members +verify.completions( + { + marker: "x", + exact: [ + { name: "a", text: "(property) a: string | number" }, + { name: "b", text: "(property) b: number | boolean" }, + { name: "c", text: "(property) c: string"} , + ], + }, + { marker: "f", includes: [{ name: "a", text: "(property) I.a: number" }] }, // Also contains array members +); diff --git a/tests/cases/fourslash/completionListOnAliasedModule.ts b/tests/cases/fourslash/completionListOnAliasedModule.ts index 7b533408bbd..753a52f0de4 100644 --- a/tests/cases/fourslash/completionListOnAliasedModule.ts +++ b/tests/cases/fourslash/completionListOnAliasedModule.ts @@ -9,6 +9,4 @@ ////import p = M.N; ////p./**/ -goTo.marker(); -verify.completionListContains('foo'); -verify.not.completionListContains('bar'); \ No newline at end of file +verify.completions({ marker: "", exact: "foo" }); diff --git a/tests/cases/fourslash/completionListOnAliases.ts b/tests/cases/fourslash/completionListOnAliases.ts index 0c5b7adcd50..7e2b7a07f72 100644 --- a/tests/cases/fourslash/completionListOnAliases.ts +++ b/tests/cases/fourslash/completionListOnAliases.ts @@ -8,8 +8,7 @@ //// x./*2*/ ////} -goTo.marker("1"); -verify.completionListContains("x", "(alias) namespace x\nimport x = M", undefined); - -goTo.marker("2"); -verify.completionListContains("value"); +verify.completions( + { marker: "1", includes: [{ name: "x", text: "(alias) namespace x\nimport x = M" }] }, + { marker: "2", exact: "value" }, +); diff --git a/tests/cases/fourslash/completionListOnAliases2.ts b/tests/cases/fourslash/completionListOnAliases2.ts index 5933fbe89d4..ffa1c212a8d 100644 --- a/tests/cases/fourslash/completionListOnAliases2.ts +++ b/tests/cases/fourslash/completionListOnAliases2.ts @@ -34,56 +34,18 @@ ////a./*7*/; ////var tmp2: a./*7Type*/; -function getVerify(isTypeLocation?: boolean) { - return { - verifyValue: isTypeLocation ? verify.not : verify, - verifyType: isTypeLocation ? verify : verify.not, - verifyValueOrType: verify - }; -} - -function verifyModuleM(marker: string) { - verifyModuleMWorker(marker, /*isTypeLocation*/ false); - verifyModuleMWorker(`${marker}Type`, /*isTypeLocation*/ true); -} - -function verifyModuleMWorker(marker: string, isTypeLocation: boolean): void { - goTo.marker(marker); - - const { verifyValue, verifyType, verifyValueOrType } = getVerify(isTypeLocation); - verifyType.completionListContains("I"); - verifyValueOrType.completionListContains("C"); - verifyValueOrType.completionListContains("E"); - verifyValue.completionListContains("N"); - verifyValue.completionListContains("V"); - verifyValue.completionListContains("F"); - verifyValueOrType.completionListContains("A"); -} - -// Module m -goTo.marker("1"); -verify.completionListContains("A"); -verifyModuleM("1"); - -// Class C -goTo.marker("2"); -verify.completionListContains("property"); - -// Enum E -goTo.marker("3"); -verify.completionListContains("value"); - -// Module N -goTo.marker("4"); -verify.completionListContains("v"); - -// var V -goTo.marker("5"); -verify.completionListContains("toFixed"); - -// function F -goTo.marker("6"); -verify.completionListContains("call"); - -// alias a -verifyModuleM("7"); \ No newline at end of file +verify.completions( + // Module m / alias a + { marker: ["1", "7"], exact: ["F", "C", "E", "N", "V", "A"] }, + { marker: ["1Type", "7Type"], exact: ["I", "C", "E", "A"] }, + // Class C + { marker: "2", exact: ["prototype", "property", ...completion.functionMembers] }, + // Enum E + { marker: "3", exact: "value" }, + // Module N + { marker: "4", exact: "v" }, + // var V + { marker: "5", includes: "toFixed" }, + // function F + { marker: "6", includes: "call" }, +); diff --git a/tests/cases/fourslash/completionListOnAliases3.ts b/tests/cases/fourslash/completionListOnAliases3.ts index 3eab00e2ed9..b3884a400a2 100644 --- a/tests/cases/fourslash/completionListOnAliases3.ts +++ b/tests/cases/fourslash/completionListOnAliases3.ts @@ -5,9 +5,7 @@ ////} ////declare module 'thing' { //// import x = require('foobar'); -//// var m: x./*1*/; +//// var m: x./*1*/; ////} -// Q does not show up in member list of x -goTo.marker("1"); -verify.completionListContains("Q"); +verify.completions({ marker: "1", exact: "Q" }); diff --git a/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts b/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts index cec7bf87aec..aee8633d743 100644 --- a/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts +++ b/tests/cases/fourslash/completionListOnFunctionCallWithOptionalArgument.ts @@ -3,5 +3,4 @@ //// declare function Foo(arg1?: Function): { q: number }; //// Foo(function () { } )./**/; -goTo.marker(); -verify.completionListContains('q'); +verify.completions({ marker: "", exact: "q" }); diff --git a/tests/cases/fourslash/completionListOnMethodParameterName.ts b/tests/cases/fourslash/completionListOnMethodParameterName.ts index e02167850af..4de92beea96 100644 --- a/tests/cases/fourslash/completionListOnMethodParameterName.ts +++ b/tests/cases/fourslash/completionListOnMethodParameterName.ts @@ -5,6 +5,5 @@ //// } ////} -goTo.marker(); // Completion list shouldn't be present in argument name position -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/completionListOnParam.ts b/tests/cases/fourslash/completionListOnParam.ts index ad2bbcde1b8..7f2da15814f 100644 --- a/tests/cases/fourslash/completionListOnParam.ts +++ b/tests/cases/fourslash/completionListOnParam.ts @@ -8,5 +8,4 @@ //// public Foo(x: Bar./**/Blah, y: Bar.Blah) { } ////} -goTo.marker(); -verify.completionListContains('Blah'); \ No newline at end of file +verify.completions({ marker: "", exact: "Blah" }); diff --git a/tests/cases/fourslash/completionListOnParamInClass.ts b/tests/cases/fourslash/completionListOnParamInClass.ts index 44c1c22d5c8..4f0e8efeace 100644 --- a/tests/cases/fourslash/completionListOnParamInClass.ts +++ b/tests/cases/fourslash/completionListOnParamInClass.ts @@ -4,6 +4,4 @@ //// static getEncoding(buffer: buffer/**/Pointer ////} -goTo.marker(); -verify.not.completionListContains('parseInt'); -verify.completionListContains('encoder'); +verify.completions({ marker: "", includes: "encoder", excludes: "parseInt" }); diff --git a/tests/cases/fourslash/completionListOnParamOfGenericType1.ts b/tests/cases/fourslash/completionListOnParamOfGenericType1.ts index c55b48bf7e9..79fc9ee49ea 100644 --- a/tests/cases/fourslash/completionListOnParamOfGenericType1.ts +++ b/tests/cases/fourslash/completionListOnParamOfGenericType1.ts @@ -8,15 +8,9 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains('next'); -verify.completionListContains('prev'); -verify.completionListContains('pushEntry'); +const exact = ["next", "prev", "pushEntry"]; +verify.completions({ marker: "1", exact }); edit.insert('next.'); -verify.completionListContains('next'); -verify.completionListContains('prev'); -verify.completionListContains('pushEntry'); +verify.completions({ exact }); edit.insert('prev.'); -verify.completionListContains('next'); -verify.completionListContains('prev'); -verify.completionListContains('pushEntry'); +verify.completions({ exact }); diff --git a/tests/cases/fourslash/completionListOnPrivateVariableInModule.ts b/tests/cases/fourslash/completionListOnPrivateVariableInModule.ts index b22113b856f..849765e212d 100644 --- a/tests/cases/fourslash/completionListOnPrivateVariableInModule.ts +++ b/tests/cases/fourslash/completionListOnPrivateVariableInModule.ts @@ -2,5 +2,4 @@ //// module Foo { var testing = ""; test/**/ } -goTo.marker(); -verify.completionListContains('testing', 'var testing: string'); +verify.completions({ marker: "", includes: { name: "testing", text: "var testing: string" } }); diff --git a/tests/cases/fourslash/completionListOnSuper.ts b/tests/cases/fourslash/completionListOnSuper.ts index 2b3c0ef75fa..842c7d7db16 100644 --- a/tests/cases/fourslash/completionListOnSuper.ts +++ b/tests/cases/fourslash/completionListOnSuper.ts @@ -16,7 +16,4 @@ //// } ////} -goTo.marker(); -verify.completionListContains('foo'); -verify.completionListContains('bar'); -verify.completionListCount(2); +verify.completions({ marker: "", exact: ["foo", "bar"] }); diff --git a/tests/cases/fourslash/completionListOnVarBetweenModules.ts b/tests/cases/fourslash/completionListOnVarBetweenModules.ts index b0205e3428c..72bd4c74125 100644 --- a/tests/cases/fourslash/completionListOnVarBetweenModules.ts +++ b/tests/cases/fourslash/completionListOnVarBetweenModules.ts @@ -12,6 +12,4 @@ //// } ////} -goTo.marker(); -verify.completionListContains("C1"); -verify.completionListContains("C2"); +verify.completions({ marker: "", exact: ["C1", "C2"] }); diff --git a/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction01.ts b/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction01.ts index d775371796f..1dc4927bdfb 100644 --- a/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction01.ts +++ b/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction01.ts @@ -3,6 +3,4 @@ ////// no a or b /////*1*/(a, b) => { } -goTo.marker("1"); -verify.not.completionListContains("a"); -verify.not.completionListContains("b"); \ No newline at end of file +verify.completions({ marker: "1", excludes: ["a", "b"] }); diff --git a/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction02.ts b/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction02.ts index d9195ce5b97..badd1bc8d18 100644 --- a/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction02.ts +++ b/tests/cases/fourslash/completionListOutsideOfClosedArrowFunction02.ts @@ -3,6 +3,4 @@ ////// no a or b ////(a, b) => { }/*1*/ -goTo.marker("1"); -verify.not.completionListContains("a"); -verify.not.completionListContains("b"); \ No newline at end of file +verify.completions({ marker: "1", excludes: ["a", "b"] }); diff --git a/tests/cases/fourslash/completionListOutsideOfClosedFunctionDeclaration01.ts b/tests/cases/fourslash/completionListOutsideOfClosedFunctionDeclaration01.ts index 8b6077e0f8b..e45b58aa499 100644 --- a/tests/cases/fourslash/completionListOutsideOfClosedFunctionDeclaration01.ts +++ b/tests/cases/fourslash/completionListOutsideOfClosedFunctionDeclaration01.ts @@ -3,6 +3,4 @@ ////// no a or b /////*1*/function f (a, b) {} -goTo.marker("1"); -verify.not.completionListContains("a"); -verify.not.completionListContains("b"); \ No newline at end of file +verify.completions({ marker: "1", excludes: ["a", "b"] }); diff --git a/tests/cases/fourslash/completionListOutsideOfForLoop01.ts b/tests/cases/fourslash/completionListOutsideOfForLoop01.ts index 473a39a453d..bf01ab447a0 100644 --- a/tests/cases/fourslash/completionListOutsideOfForLoop01.ts +++ b/tests/cases/fourslash/completionListOutsideOfForLoop01.ts @@ -2,5 +2,4 @@ ////for (let i = 0; i < 10; i++) i;/*1*/ -goTo.marker("1"); -verify.not.completionListContains("i"); \ No newline at end of file +verify.completions({ marker: "1", excludes: "i" }); diff --git a/tests/cases/fourslash/completionListOutsideOfForLoop02.ts b/tests/cases/fourslash/completionListOutsideOfForLoop02.ts index b1186ac7cce..d4f11a6b973 100644 --- a/tests/cases/fourslash/completionListOutsideOfForLoop02.ts +++ b/tests/cases/fourslash/completionListOutsideOfForLoop02.ts @@ -2,5 +2,4 @@ ////for (let i = 0; i < 10; i++);/*1*/ -goTo.marker("1"); -verify.not.completionListContains("i"); \ No newline at end of file +verify.completions({ marker: "1", excludes: "i" }); diff --git a/tests/cases/fourslash/completionListPrivateMembers.ts b/tests/cases/fourslash/completionListPrivateMembers.ts index e5e494d521d..7ad87f4bccd 100644 --- a/tests/cases/fourslash/completionListPrivateMembers.ts +++ b/tests/cases/fourslash/completionListPrivateMembers.ts @@ -11,7 +11,4 @@ //// } ////} - -goTo.marker(); -verify.completionListContains("y"); -verify.not.completionListContains("x"); +verify.completions({ marker: "", exact: ["y", "foo"] }); diff --git a/tests/cases/fourslash/completionListPrivateMembers2.ts b/tests/cases/fourslash/completionListPrivateMembers2.ts index 1a04df1d823..b766823e0b9 100644 --- a/tests/cases/fourslash/completionListPrivateMembers2.ts +++ b/tests/cases/fourslash/completionListPrivateMembers2.ts @@ -8,10 +8,7 @@ ////var f:Foo; ////f./*2*/ -goTo.marker("1"); -verify.completionListContains("y"); -verify.completionListContains("x"); - -goTo.marker("2"); -verify.not.completionListContains("x"); -verify.not.completionListContains("y"); \ No newline at end of file +verify.completions( + { marker: "1", exact: ["y", "x", "method"] }, + { marker: "2", exact: "method" }, +); diff --git a/tests/cases/fourslash/completionListPrivateMembers3.ts b/tests/cases/fourslash/completionListPrivateMembers3.ts index 999ab8fa5e6..d333b677ea2 100644 --- a/tests/cases/fourslash/completionListPrivateMembers3.ts +++ b/tests/cases/fourslash/completionListPrivateMembers3.ts @@ -18,14 +18,4 @@ //// } ////} -goTo.marker("1"); -verify.completionListContains("p"); -verify.completionListCount(1); - -goTo.marker("2"); -verify.completionListContains("p"); -verify.completionListCount(1); - -goTo.marker("2"); -verify.completionListContains("p"); -verify.completionListCount(1); +verify.completions({ marker: ["1", "2", "3"], exact: "p" }); diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers2.ts b/tests/cases/fourslash/completionListStaticProtectedMembers2.ts index c6c64c5c6eb..aff0c075faa 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers2.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers2.ts @@ -26,45 +26,46 @@ //// } ////} - -// Same class, everything is visible -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -goTo.marker("2"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -goTo.marker("3"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); - -// only public and protected methods of the base class are accessible through super -goTo.marker("4"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.not.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); \ No newline at end of file +verify.completions( + { + // Same class, everything is visible + marker: ["1"], + exact: [ + "prototype", + "protectedMethod", + "protectedProperty", + "publicMethod", + "publicProperty", + "protectedOverriddenMethod", + "protectedOverriddenProperty", + ...completion.functionMembers, + ], + }, + { + marker: ["2", "3"], + exact: [ + "prototype", + "protectedOverriddenMethod", + "protectedOverriddenProperty", + "test", + "protectedMethod", + "protectedProperty", + "publicMethod", + "publicProperty", + ...completion.functionMembers, + ], + }, + { + // only public and protected methods of the base class are accessible through super + marker: "4", + exact: [ + "protectedMethod", + "publicMethod", + "protectedOverriddenMethod", + "apply", + "call", + "bind", + "toString", + ], + }, +); diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers3.ts b/tests/cases/fourslash/completionListStaticProtectedMembers3.ts index 0cb916c181f..57cf38dcb4f 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers3.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers3.ts @@ -22,24 +22,8 @@ ////Base./*1*/; ////C3./*2*/; - // Only public properties are visible outside the class -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); - -goTo.marker("2"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.not.completionListContains('protectedOverriddenMethod'); -verify.not.completionListContains('protectedOverriddenProperty'); \ No newline at end of file +verify.completions({ + marker: ["1", "2"], + exact: ["prototype", "publicMethod", "publicProperty", ...completion.functionMembers], +}); diff --git a/tests/cases/fourslash/completionListStaticProtectedMembers4.ts b/tests/cases/fourslash/completionListStaticProtectedMembers4.ts index 14c460d6873..a34a3cda3ac 100644 --- a/tests/cases/fourslash/completionListStaticProtectedMembers4.ts +++ b/tests/cases/fourslash/completionListStaticProtectedMembers4.ts @@ -26,24 +26,29 @@ ////} //// Derived./*2*/ -// Sub class, everything but private is visible -goTo.marker("1"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.completionListContains('protectedMethod'); -verify.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); +const publicCompletions: ReadonlyArray = ["publicMethod", "publicProperty", ...completion.functionMembers]; -// Can see protected methods elevated to public -goTo.marker("2"); -verify.not.completionListContains('privateMethod'); -verify.not.completionListContains('privateProperty'); -verify.not.completionListContains('protectedMethod'); -verify.not.completionListContains('protectedProperty'); -verify.completionListContains('publicMethod'); -verify.completionListContains('publicProperty'); -verify.completionListContains('protectedOverriddenMethod'); -verify.completionListContains('protectedOverriddenProperty'); +verify.completions( + { + // Sub class, everything but private is visible + marker: "1", + exact: [ + "prototype", + "protectedOverriddenMethod", + "protectedOverriddenProperty", + "protectedMethod", + "protectedProperty", + ...publicCompletions + ], + }, + { + // Can see protected methods elevated to public + marker: "2", + exact: [ + "prototype", + "protectedOverriddenMethod", + "protectedOverriddenProperty", + ...publicCompletions, + ], + }, +); diff --git a/tests/cases/fourslash/completionListWithLabel.ts b/tests/cases/fourslash/completionListWithLabel.ts index 1efc0ebb5fa..dcf5cc1f776 100644 --- a/tests/cases/fourslash/completionListWithLabel.ts +++ b/tests/cases/fourslash/completionListWithLabel.ts @@ -13,32 +13,8 @@ //// break; /*8*/ ////} -goTo.marker("1"); -verify.completionListContains("label"); - -goTo.marker("2"); -verify.completionListContains("label"); -verify.not.completionListContains("testlabel"); - -goTo.marker("3"); -verify.completionListContains("label"); -verify.completionListContains("testlabel"); - -goTo.marker("4"); -verify.completionListContains("label"); -verify.completionListContains("testlabel"); - -goTo.marker("5"); -verify.completionListContains("testlabel"); -verify.completionListContains("label"); - -goTo.marker("6"); -verify.completionListContains("testlabel"); -verify.completionListContains("label"); - -goTo.marker("7"); -verify.completionListContains("label"); -verify.not.completionListContains("testlabel"); - -goTo.marker("8"); -verify.not.completionListContains("label"); +verify.completions( + { marker: ["1", "2", "7"], exact: "label" }, + { marker: ["3", "4", "5", "6"], exact: ["testlabel", "label"] }, + { marker: "8", excludes: ["label"] }, +); diff --git a/tests/cases/fourslash/completionListWithMeanings.ts b/tests/cases/fourslash/completionListWithMeanings.ts index 61dc95adca8..8c3498ebda5 100644 --- a/tests/cases/fourslash/completionListWithMeanings.ts +++ b/tests/cases/fourslash/completionListWithMeanings.ts @@ -1,5 +1,7 @@ /// +// @noLib: true + ////namespace m { export interface point2 { } } ////namespace m2 { export var zz = 10; } ////namespace m3 { export var zz2 = 10; export interface point3 { } } @@ -13,58 +15,29 @@ ////var kk: m3.point3/*membertypeExpr*/ = m3.zz2/*membervalueExpr*/; ////var zz = { x: 4, y: 3 }; -const markers = test.markerNames(); - -function getVerifyBasedOnMarker(marker: string, meaning: string) { - return marker.indexOf(meaning) === 0 ? verify : verify.not; -} - -function verifyCompletions(verify: FourSlashInterface.verifyNegatable, completions: CompletionInfo[]) { - for (const info of completions) { - verify.completionListContains(info[0], info[1]); - } -} - -type CompletionInfo = [string, string]; -function verifyCompletionsExistForMeaning(marker: string, meaning: string, completions: CompletionInfo[]) { - verifyCompletions(getVerifyBasedOnMarker(marker, meaning), completions); -} - -function verifyCompletionsDoNotExistForMeaning(marker: string, meaning: string, completions: CompletionInfo[]) { - verifyCompletions(getVerifyBasedOnMarker(marker, meaning) === verify.not ? verify : verify.not, completions); -} - -const values: CompletionInfo[] = [ - ["xx", "var xx: number"], - ["tt", "var tt: number"], - ["yy", "var yy: point"], - ["zz", "var zz: point"], - ["m2", "namespace m2"], // With no type side, allowed only in value +const values: ReadonlyArray = [ + { name: "m2", text: "namespace m2" }, // With no type side, allowed only in value + { name: "m3", text: "namespace m3" }, + { name: "xx", text: "var xx: number" }, + { name: "tt", text: "var tt: number" }, + { name: "yy", text: "var yy: point" }, + { name: "kk", text: "var kk: m3.point3" }, + { name: "zz", text: "var zz: point" }, + "undefined", + ...completion.statementKeywordsWithTypes, ]; -const types: CompletionInfo[] = [ - ["point", "interface point"], - ["m", "namespace m"], // Uninstantiated namespace only allowed at type locations +const types: ReadonlyArray = [ + { name: "m", text: "namespace m" }, + { name: "m3", text: "namespace m3" }, + { name: "point", text: "interface point" }, + ...completion.typeKeywords, ]; -const namespaces: CompletionInfo[] = [ - ["m3", "namespace m3"], // Has both type and values, allowed in all locations -]; - -const membervalues: CompletionInfo[] = [ - ["zz2", "var m3.zz2: number"], -]; - - -const membertypes: CompletionInfo[] = [ - ["point3", "interface m3.point3"], -]; - -for (const marker of markers) { - goTo.marker(marker); - verifyCompletionsExistForMeaning(marker, "value", values); - verifyCompletionsExistForMeaning(marker, "type", types); - verifyCompletionsExistForMeaning(marker, "membervalue", membervalues); - verifyCompletionsExistForMeaning(marker, "membertype", membertypes); - verifyCompletionsDoNotExistForMeaning(marker, "member", namespaces); -} \ No newline at end of file +verify.completions( + { marker: "valueExpr", exact: values, isNewIdentifierLocation: true }, + { marker: "typeExpr", exact: types, }, + { marker: "valueExprInObjectLiteral", exact: values }, + { marker: "membertypeExpr", exact: [{ name: "point3", text: "interface m3.point3" }] }, + { marker: "membervalueExpr", exact: [{ name: "zz2", text: "var m3.zz2: number" }] }, +); diff --git a/tests/cases/fourslash/completionListWithModulesFromModule.ts b/tests/cases/fourslash/completionListWithModulesFromModule.ts index 462faa5ebf5..d08e26a8d50 100644 --- a/tests/cases/fourslash/completionListWithModulesFromModule.ts +++ b/tests/cases/fourslash/completionListWithModulesFromModule.ts @@ -1,5 +1,7 @@ /// +// @noLib: true + ////namespace mod1 { //// var mod1var = 1; //// function mod1fn() { @@ -248,118 +250,55 @@ //// ////var shwvar = 1; -function sharedNegativeVerify() -{ - verify.not.completionListContains('sfvar'); - verify.not.completionListContains('sffn'); - verify.not.completionListContains('scvar'); - verify.not.completionListContains('scfn'); - verify.not.completionListContains('scpfn'); - verify.not.completionListContains('scpvar'); - verify.not.completionListContains('scsvar'); - verify.not.completionListContains('scsfn'); - verify.not.completionListContains('sivar'); - verify.not.completionListContains('sifn'); - verify.not.completionListContains('mod1exvar'); - verify.not.completionListContains('mod2eexvar'); -} +const commonValues: ReadonlyArray = + [1, 2, 3, 4, 5].map(n => ({ name: `mod${n}`, text: `namespace mod${n}` })); +const commonTypes: ReadonlyArray = + [1, 2, 4].map(n => ({ name: `mod${n}`, text: `namespace mod${n}` })); -function goToMarkAndVerifyShadow() -{ - sharedNegativeVerify(); - verify.not.completionListContains('mod2var'); - verify.not.completionListContains('mod2fn'); - verify.not.completionListContains('mod2cls'); - verify.not.completionListContains('mod2int'); - verify.not.completionListContains('mod2mod'); - verify.not.completionListContains('mod2evar'); - verify.not.completionListContains('mod2efn'); - verify.not.completionListContains('mod2ecls'); - verify.not.completionListContains('mod2eint'); - verify.not.completionListContains('mod2emod'); -} - -function getVerify(isTypeLocation?: boolean) { - return { - verifyValue: isTypeLocation ? verify.not : verify, - verifyType: isTypeLocation ? verify : verify.not, - verifyValueOrType: verify - }; -} - -function typeLocationVerify(valueMarker: string, verify: (typeMarker: string) => void) { - verify(valueMarker + "Type"); - return valueMarker; -} -// from a shadow namespace with no export -verifyShadowNamespaceWithNoExport(); -function verifyShadowNamespaceWithNoExport(marker?: string) { - const { verifyValue, verifyType, verifyValueOrType } = getVerify(!!marker); - if (!marker) { - marker = typeLocationVerify('shadowNamespaceWithNoExport', verifyShadowNamespaceWithNoExport); +verify.completions( + { + marker: ["shadowNamespaceWithNoExport", "shadowNamespaceWithExport"], + exact: [ + { name: "shwfn", text: "function shwfn(shadow: any): void" }, + { name: "shwvar", text: "var shwvar: string" }, + { name: "shwcls", text: "class shwcls" }, + "tmp", + ...commonValues, + "undefined", + ...completion.statementKeywordsWithTypes, + ], + }, { + marker: ["shadowNamespaceWithNoExportType", "shadowNamespaceWithExportType"], + exact: [ + { name: "shwcls", text: "class shwcls" }, + { name: "shwint", text: "interface shwint" }, + ...commonTypes, + ...completion.typeKeywords, + ] + }, + { + marker: "namespaceWithImport", + exact: [ + "Mod1", + "iMod1", + "tmp", + { name: "shwfn", text: "function shwfn(): void" }, + ...commonValues, + { name: "shwcls", text: "class shwcls" }, + { name: "shwvar", text: "var shwvar: number" }, + "undefined", + ...completion.statementKeywordsWithTypes, + ], + }, + { + marker: "namespaceWithImportType", + exact: [ + "Mod1", + "iMod1", + ...commonTypes, + { name: "shwcls", text: "class shwcls" }, + { name: "shwint", text: "interface shwint" }, + ...completion.typeKeywords, + ], } - goTo.marker(marker); - - verifyValue.completionListContains('shwvar', 'var shwvar: string'); - verifyValue.completionListContains('shwfn', 'function shwfn(shadow: any): void'); - verifyValueOrType.completionListContains('shwcls', 'class shwcls'); - verifyType.completionListContains('shwint', 'interface shwint'); - - goToMarkAndVerifyShadow(); -} - -// from a shadow namespace with export -verifyShadowNamespaceWithNoExport(); -function verifyShadowNamespaceWithExport(marker?: string) { - const { verifyValue, verifyType, verifyValueOrType } = getVerify(!!marker); - if (!marker) { - marker = typeLocationVerify('shadowNamespaceWithExport', verifyShadowNamespaceWithExport); - } - goTo.marker(marker); - verifyValue.completionListContains('shwvar', 'var mod4.shwvar: string'); - verifyValue.completionListContains('shwfn', 'function mod4.shwfn(shadow: any): void'); - verifyValueOrType.completionListContains('shwcls', 'class mod4.shwcls'); - verifyType.completionListContains('shwint', 'interface mod4.shwint'); - goToMarkAndVerifyShadow(); -} - -// from a namespace with import -verifyShadowNamespaceWithNoExport(); -function verifyNamespaceWithImport(marker?: string) { - const { verifyValue, verifyType, verifyValueOrType } = getVerify(!!marker); - if (!marker) { - marker = typeLocationVerify('namespaceWithImport', verifyNamespaceWithImport); - } - goTo.marker(marker); - - verifyValue.completionListContains('mod1', 'namespace mod1'); - verifyValue.completionListContains('mod2', 'namespace mod2'); - verifyValue.completionListContains('mod3', 'namespace mod3'); - verifyValue.completionListContains('shwvar', 'var shwvar: number'); - verifyValue.completionListContains('shwfn', 'function shwfn(): void'); - verifyValueOrType.completionListContains('shwcls', 'class shwcls'); - verifyType.completionListContains('shwint', 'interface shwint'); - - sharedNegativeVerify(); - - verify.not.completionListContains('mod1var'); - verify.not.completionListContains('mod1fn'); - verify.not.completionListContains('mod1cls'); - verify.not.completionListContains('mod1int'); - verify.not.completionListContains('mod1mod'); - verify.not.completionListContains('mod1evar'); - verify.not.completionListContains('mod1efn'); - verify.not.completionListContains('mod1ecls'); - verify.not.completionListContains('mod1eint'); - verify.not.completionListContains('mod1emod'); - verify.not.completionListContains('mX'); - verify.not.completionListContains('mFunc'); - verify.not.completionListContains('mClass'); - verify.not.completionListContains('mInt'); - verify.not.completionListContains('mMod'); - verify.not.completionListContains('meX'); - verify.not.completionListContains('meFunc'); - verify.not.completionListContains('meClass'); - verify.not.completionListContains('meInt'); - verify.not.completionListContains('meMod'); -} \ No newline at end of file +); diff --git a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts index 682ef9b453e..d1bc6233f72 100644 --- a/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts +++ b/tests/cases/fourslash/completionListWithModulesInsideModuleScope.ts @@ -1,5 +1,7 @@ /// +// @noLib: true + ////namespace mod1 { //// var mod1var = 1; //// function mod1fn() { @@ -229,146 +231,177 @@ //// ////var shwvar = 1; -interface GotoMarkVerifyOptions { - isClassScope?: boolean; - isTypeLocation?: boolean; - insideMod1?: boolean; +interface VerifyGeneralOptions { + readonly isClassScope?: boolean; + readonly isTypeLocation?: boolean; + readonly insideMod1?: boolean; + readonly isNewIdentifierLocation?: boolean; + readonly moreIncludes?: ReadonlyArray; + readonly moreExcludes?: ReadonlyArray; } -function getVerify(isTypeLocation: boolean) { - return { - verifyValue: isTypeLocation ? verify.not : verify, - verifyType: isTypeLocation ? verify : verify.not, - verifyValueOrType: verify, - verifyNotValueOrType: verify.not, - }; -} - -function goToMarkAndGeneralVerify(marker: string, { isClassScope, isTypeLocation, insideMod1 }: GotoMarkVerifyOptions = {}) { - goTo.marker(marker); - +function verifyGeneral(marker: string, { isClassScope, isTypeLocation, insideMod1, isNewIdentifierLocation, moreIncludes, moreExcludes }: VerifyGeneralOptions = {}) { const mod1Dot = insideMod1 ? "" : "mod1."; - const verifyValueInModule = isClassScope || isTypeLocation ? verify.not : verify; - const verifyValueOrTypeInModule = isClassScope ? verify.not : verify; - const verifyTypeInModule = isTypeLocation ? verify : verify.not; - verifyValueInModule.completionListContains('mod1var', 'var mod1var: number'); - verifyValueInModule.completionListContains('mod1fn', 'function mod1fn(): void'); - verifyValueInModule.completionListContains('mod1evar', `var ${mod1Dot}mod1evar: number`); - verifyValueInModule.completionListContains('mod1efn', `function ${mod1Dot}mod1efn(): void`); - verifyValueInModule.completionListContains('mod1eexvar', `var mod1.mod1eexvar: number`); - verifyValueInModule.completionListContains('mod3', 'namespace mod3'); - verifyValueInModule.completionListContains('shwvar', 'var shwvar: number'); - verifyValueInModule.completionListContains('shwfn', 'function shwfn(): void'); - verifyTypeInModule.completionListContains('mod1int', 'interface mod1int'); - verifyTypeInModule.completionListContains('mod1eint', `interface ${mod1Dot}mod1eint`); - verifyTypeInModule.completionListContains('shwint', 'interface shwint'); + const valueInModule: ReadonlyArray = [ + { name: "mod1var", text: "var mod1var: number" }, + { name: "mod1fn", text: "function mod1fn(): void" }, + { name: "mod1evar", text: `var ${mod1Dot}mod1evar: number` }, + { name: "mod1efn", text: `function ${mod1Dot}mod1efn(): void` }, + { name: "mod1eexvar", text: `var mod1.mod1eexvar: number` }, + { name: "mod3", text: "namespace mod3" }, + { name: "shwvar", text: "var shwvar: number" }, + { name: "shwfn", text: "function shwfn(): void" }, + ]; + const typeInModule: ReadonlyArray = [ + { name: "mod1int", text: "interface mod1int" }, + { name: "mod1eint", text: `interface ${mod1Dot}mod1eint` }, + { name: "shwint", text: "interface shwint" }, + ]; + const valueOrTypeInModule: ReadonlyArray = [ + { name: "mod1cls", text: "class mod1cls" }, + { name: "mod1mod", text: "namespace mod1mod" }, + { name: "mod1ecls", text: `class ${mod1Dot}mod1ecls` }, + { name: "mod1emod", text: `namespace ${mod1Dot}mod1emod` }, + { name: "mod2", text: "namespace mod2" }, + { name: "shwcls", text: "class shwcls" }, + ]; - verifyValueOrTypeInModule.completionListContains('mod1cls', 'class mod1cls'); - verifyValueOrTypeInModule.completionListContains('mod1mod', 'namespace mod1mod'); - verifyValueOrTypeInModule.completionListContains('mod1ecls', `class ${mod1Dot}mod1ecls`); - verifyValueOrTypeInModule.completionListContains('mod1emod', `namespace ${mod1Dot}mod1emod`); - verifyValueOrTypeInModule.completionListContains('mod2', 'namespace mod2'); - verifyValueOrTypeInModule.completionListContains('shwcls', 'class shwcls'); - - verify.not.completionListContains('mod2var'); - verify.not.completionListContains('mod2fn'); - verify.not.completionListContains('mod2cls'); - verify.not.completionListContains('mod2int'); - verify.not.completionListContains('mod2mod'); - verify.not.completionListContains('mod2evar'); - verify.not.completionListContains('mod2efn'); - verify.not.completionListContains('mod2ecls'); - verify.not.completionListContains('mod2eint'); - verify.not.completionListContains('mod2emod'); - verify.not.completionListContains('sfvar'); - verify.not.completionListContains('sffn'); - verify.not.completionListContains('scvar'); - verify.not.completionListContains('scfn'); - verify.not.completionListContains('scpfn'); - verify.not.completionListContains('scpvar'); - verify.not.completionListContains('scsvar'); - verify.not.completionListContains('scsfn'); - verify.not.completionListContains('sivar'); - verify.not.completionListContains('sifn'); - verify.not.completionListContains('mod1exvar'); - verify.not.completionListContains('mod2eexvar'); + verify.completions({ + marker, + includes: [ + ...(isClassScope || isTypeLocation ? [] : valueInModule), + ...(isClassScope ? [] : valueOrTypeInModule), + ...(isTypeLocation ? typeInModule : []), + ...(moreIncludes || []), + ], + excludes: [ + "mod2var", + "mod2fn", + "mod2cls", + "mod2int", + "mod2mod", + "mod2evar", + "mod2efn", + "mod2ecls", + "mod2eint", + "mod2emod", + "sfvar", + "sffn", + "scvar", + "scfn", + "scpfn", + "scpvar", + "scsvar", + "scsfn", + "sivar", + "sifn", + "mod1exvar", + "mod2eexvar", + ...(moreExcludes || []), + ], + isNewIdentifierLocation, + }); } // from mod1 -goToMarkAndGeneralVerify('mod1', { insideMod1: true }); +verifyGeneral('mod1', { insideMod1: true }); // from mod1 in type position -goToMarkAndGeneralVerify('mod1Type', { isTypeLocation: true, insideMod1: true }); +verifyGeneral('mod1Type', { isTypeLocation: true, insideMod1: true }); // from function in mod1 -goToMarkAndGeneralVerify('function', { insideMod1: true }); -verify.completionListContains('bar', '(local var) bar: number'); -verify.completionListContains('foob', '(local function) foob(): void'); +verifyGeneral('function', { + insideMod1: true, + moreIncludes: [ + { name: "bar", text: "(local var) bar: number" }, + { name: "foob", text: "(local function) foob(): void" }, + ], +}); // from class in mod1 -goToMarkAndGeneralVerify('class', { isClassScope: true }); -//verify.not.completionListContains('ceFunc'); -//verify.not.completionListContains('ceVar'); +verifyGeneral('class', { + isClassScope: true, + isNewIdentifierLocation: true, + moreExcludes: ["ceFunc", "ceVar"], +}); // from interface in mod1 -verify.completionsAt("interface", ["readonly"], { isNewIdentifierLocation: true }); +verify.completions({ + marker: "interface", + exact: "readonly", + isNewIdentifierLocation: true, +}); // from namespace in mod1 verifyNamespaceInMod1('namespace'); verifyNamespaceInMod1('namespaceType', /*isTypeLocation*/ true); function verifyNamespaceInMod1(marker: string, isTypeLocation?: boolean) { - goToMarkAndGeneralVerify(marker, { isTypeLocation, insideMod1: true }); + verifyGeneral(marker, { isTypeLocation, insideMod1: true }); - const { verifyValue, verifyType, verifyValueOrType, verifyNotValueOrType } = getVerify(isTypeLocation); - - verifyValue.completionListContains('m1X', 'var m1X: number'); - verifyValue.completionListContains('m1Func', 'function m1Func(): void'); - verifyValue.completionListContains('m1eX', 'var m1eX: number'); - verifyValue.completionListContains('m1eFunc', 'function m1eFunc(): void'); - - verifyType.completionListContains('m1Int', 'interface m1Int'); - verifyType.completionListContains('m1eInt', 'interface m1eInt'); - - verifyValueOrType.completionListContains('m1Class', 'class m1Class'); - verifyValueOrType.completionListContains('m1eClass', 'class m1eClass'); - - verifyNotValueOrType.completionListContains('m1Mod', 'namespace m1Mod'); - verifyNotValueOrType.completionListContains('m1eMod', 'namespace m1eMod'); + const values: ReadonlyArray = [ + { name: "m1X", text: "var m1X: number" }, + { name: "m1Func", text: "function m1Func(): void" }, + { name: "m1eX", text: "var m1eX: number" }, + { name: "m1eFunc", text: "function m1eFunc(): void" }, + ]; + const types: ReadonlyArray = [ + { name: "m1Int", text: "interface m1Int" }, + { name: "m1eInt", text: "interface m1eInt" }, + ]; + verify.completions({ + includes: [ + ...(isTypeLocation ? types : values), + { name: "m1Class", text: "class m1Class" }, + { name: "m1eClass", text: "class m1eClass" }, + ], + excludes: ["m1Mod", "m1eMod"], + }); } // from exported function in mod1 -goToMarkAndGeneralVerify('exportedFunction', { insideMod1: true }); -verify.completionListContains('bar', '(local var) bar: number'); -verify.completionListContains('foob', '(local function) foob(): void'); +verifyGeneral('exportedFunction', { + insideMod1: true, + moreIncludes: [ + { name: "bar", text: "(local var) bar: number" }, + { name: "foob", text: "(local function) foob(): void" }, + ], +}); // from exported class in mod1 -goToMarkAndGeneralVerify('exportedClass', { isClassScope: true }); -verify.not.completionListContains('ceFunc'); -verify.not.completionListContains('ceVar'); +verifyGeneral('exportedClass', { + isClassScope: true, + isNewIdentifierLocation: true, + moreExcludes: ["ceFunc", "ceVar"], +}); // from exported interface in mod1 -verify.completionsAt("exportedInterface", ["readonly"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "exportedInterface", exact: ["readonly"], isNewIdentifierLocation: true }); // from exported namespace in mod1 verifyExportedNamespace('exportedNamespace'); verifyExportedNamespace('exportedNamespaceType', /*isTypeLocation*/ true); function verifyExportedNamespace(marker: string, isTypeLocation?: boolean) { - goToMarkAndGeneralVerify(marker, { isTypeLocation, insideMod1: true }); - const { verifyValue, verifyType, verifyValueOrType, verifyNotValueOrType } = getVerify(isTypeLocation); - verifyValue.completionListContains('mX', 'var mX: number'); - verifyValue.completionListContains('mFunc', 'function mFunc(): void'); - verifyValue.completionListContains('meX', 'var meX: number'); - verifyValue.completionListContains('meFunc', 'function meFunc(): void'); - - verifyType.completionListContains('mInt', 'interface mInt'); - verifyType.completionListContains('meInt', 'interface meInt'); - - verifyValueOrType.completionListContains('mClass', 'class mClass'); - verifyValueOrType.completionListContains('meClass', 'class meClass'); - - verifyNotValueOrType.completionListContains('mMod', 'namespace mMod'); - verifyNotValueOrType.completionListContains('meMod', 'namespace meMod'); + const values: ReadonlyArray = [ + { name: "mX", text: "var mX: number" }, + { name: "mFunc", text: "function mFunc(): void" }, + { name: "meX", text: "var meX: number" }, + { name: "meFunc", text: "function meFunc(): void" }, + ]; + const types: ReadonlyArray = [ + { name: "mInt", text: "interface mInt" }, + { name: "meInt", text: "interface meInt" }, + ]; + verifyGeneral(marker, { + isTypeLocation, + insideMod1: true, + moreIncludes: [ + ...(isTypeLocation ? types : values), + { name: "mClass", text: "class mClass" }, + { name: "meClass", text: "class meClass" }, + ], + moreExcludes: ["mMod", "meMod"], + }); } // from extended namespace @@ -376,44 +409,50 @@ verifyExtendedNamespace('extendedNamespace'); verifyExtendedNamespace('extendedNamespaceType', /*isTypeLocation*/ true); function verifyExtendedNamespace(marker: string, isTypeLocation?: boolean) { - goTo.marker(marker); - const { verifyValue, verifyType, verifyValueOrType, verifyNotValueOrType } = getVerify(isTypeLocation); + const values: ReadonlyArray = [ + { name: "mod1evar", text: "var mod1.mod1evar: number" }, + { name: "mod1efn", text: "function mod1.mod1efn(): void" }, + { name: "mod1eexvar", text: "var mod1eexvar: number" }, + { name: "mod3", text: "namespace mod3" }, + { name: "shwvar", text: "var shwvar: number" }, + { name: "shwfn", text: "function shwfn(): void" }, + ]; + const types: ReadonlyArray = [ + { name: "mod1eint", text: "interface mod1.mod1eint" }, + { name: "shwint", text: "interface shwint" }, + ]; - verifyValue.completionListContains('mod1evar', 'var mod1.mod1evar: number'); - verifyValue.completionListContains('mod1efn', 'function mod1.mod1efn(): void'); - verifyValue.completionListContains('mod1eexvar', 'var mod1eexvar: number'); - verifyValue.completionListContains('mod3', 'namespace mod3'); - verifyValue.completionListContains('shwvar', 'var shwvar: number'); - verifyValue.completionListContains('shwfn', 'function shwfn(): void'); - - verifyType.completionListContains('mod1eint', 'interface mod1.mod1eint'); - verifyType.completionListContains('shwint', 'interface shwint'); - - verifyValueOrType.completionListContains('mod1ecls', 'class mod1.mod1ecls'); - verifyValueOrType.completionListContains('mod1emod', 'namespace mod1.mod1emod'); - verifyValueOrType.completionListContains('mod2', 'namespace mod2'); - verifyValueOrType.completionListContains('shwcls', 'class shwcls'); - - - verify.not.completionListContains('mod2var'); - verify.not.completionListContains('mod2fn'); - verify.not.completionListContains('mod2cls'); - verify.not.completionListContains('mod2int'); - verify.not.completionListContains('mod2mod'); - verify.not.completionListContains('mod2evar'); - verify.not.completionListContains('mod2efn'); - verify.not.completionListContains('mod2ecls'); - verify.not.completionListContains('mod2eint'); - verify.not.completionListContains('mod2emod'); - verify.not.completionListContains('sfvar'); - verify.not.completionListContains('sffn'); - verify.not.completionListContains('scvar'); - verify.not.completionListContains('scfn'); - verify.not.completionListContains('scpfn'); - verify.not.completionListContains('scpvar'); - verify.not.completionListContains('scsvar'); - verify.not.completionListContains('scsfn'); - verify.not.completionListContains('sivar'); - verify.not.completionListContains('sifn'); - verify.not.completionListContains('mod2eexvar'); + verify.completions({ + marker, + includes: [ + ...(isTypeLocation ? types : values), + { name: "mod1ecls", text: "class mod1.mod1ecls" }, + { name: "mod1emod", text: "namespace mod1.mod1emod" }, + { name: "mod2", text: "namespace mod2" }, + { name: "shwcls", text: "class shwcls" }, + ], + excludes: [ + "mod2var", + "mod2fn", + "mod2cls", + "mod2int", + "mod2mod", + "mod2evar", + "mod2efn", + "mod2ecls", + "mod2eint", + "mod2emod", + "sfvar", + "sffn", + "scvar", + "scfn", + "scpfn", + "scpvar", + "scsvar", + "scsfn", + "sivar", + "sifn", + "mod2eexvar", + ], + }); } diff --git a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope.ts b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope.ts index c72159b0027..8b9a13fc5b2 100644 --- a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope.ts +++ b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope.ts @@ -219,73 +219,44 @@ ////var shwvar = 1; /////*global*/ -function verifyNotContainFunctionMembers() -{ - verify.not.completionListContains('sfvar'); - verify.not.completionListContains('sffn'); -} - -function verifyNotContainClassMembers() -{ - verify.not.completionListContains('scvar'); - verify.not.completionListContains('scfn'); - verify.not.completionListContains('scpfn'); - verify.not.completionListContains('scpvar'); - verify.not.completionListContains('scsvar'); - verify.not.completionListContains('scsfn'); -} - -function verifyNotContainInterfaceMembers() -{ - verify.not.completionListContains('sivar'); - verify.not.completionListContains('sifn'); -} - -function goToMarkAndGeneralVerify(marker: string) -{ - goTo.marker(marker); - - verify.not.completionListContains('mod1var'); - verify.not.completionListContains('mod1fn'); - verify.not.completionListContains('mod1cls'); - verify.not.completionListContains('mod1int'); - verify.not.completionListContains('mod1mod'); - verify.not.completionListContains('mod1evar'); - verify.not.completionListContains('mod1efn'); - verify.not.completionListContains('mod1ecls'); - verify.not.completionListContains('mod1eint'); - verify.not.completionListContains('mod1emod'); - verify.not.completionListContains('mod1eexvar'); -} - -// from global scope -goToMarkAndGeneralVerify('global'); -verify.completionListContains('mod1', 'namespace mod1'); -verify.completionListContains('mod2', 'namespace mod2'); -verify.completionListContains('mod3', 'namespace mod3'); -verify.completionListContains('shwvar', 'var shwvar: number'); -verify.completionListContains('shwfn', 'function shwfn(): void'); -verify.completionListContains('shwcls', 'class shwcls'); -verify.not.completionListContains('shwint', 'interface shwint'); - -verifyNotContainFunctionMembers(); -verifyNotContainClassMembers(); -verifyNotContainInterfaceMembers(); - -// from function scope -goToMarkAndGeneralVerify('function'); -verify.completionListContains('sfvar', '(local var) sfvar: number'); -verify.completionListContains('sffn', '(local function) sffn(): void'); - -verifyNotContainClassMembers(); -verifyNotContainInterfaceMembers(); - -// from class scope -goToMarkAndGeneralVerify('class'); -verifyNotContainFunctionMembers(); -verifyNotContainInterfaceMembers(); - -// from interface scope -goToMarkAndGeneralVerify('interface'); -verifyNotContainClassMembers(); -verifyNotContainFunctionMembers(); \ No newline at end of file +const commonExcludes: ReadonlyArray = [ + "mod1var", "mod1fn", "mod1cls", "mod1int", "mod1mod", "mod1evar", "mod1efn", "mod1ecls", "mod1eint", "mod1emod", "mod1eexvar", + "scvar", "scfn", "scpfn", "scpvar", "scsvar", "scsfn", + "sivar", "sifn", +]; +verify.completions( + // from global scope + { + marker: "global", + includes: [ + { name: "mod1", text: "namespace mod1" }, + { name: "mod2", text: "namespace mod2" }, + { name: "mod3", text: "namespace mod3" }, + { name: "shwvar", text: "var shwvar: number" }, + { name: "shwfn", text: "function shwfn(): void" }, + { name: "shwcls", text: "class shwcls" }, + ], + excludes: [...commonExcludes, "shwint", "sfvar", "sffn"], + }, + // from function scope + { + marker: "function", + includes: [ + { name: "sfvar", text: "(local var) sfvar: number" }, + { name: "sffn", text: "(local function) sffn(): void" }, + ], + excludes: commonExcludes, + }, + // from class scope + { + marker: "class", + exact: completion.classElementKeywords, + isNewIdentifierLocation: true, + }, + // from interface scope + { + marker: "interface", + exact: ["readonly"], + isNewIdentifierLocation: true, + } +); diff --git a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts index c8aa1933def..7d015de28b3 100644 --- a/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts +++ b/tests/cases/fourslash/completionListWithModulesOutsideModuleScope2.ts @@ -1,4 +1,4 @@ -/// +/// ////module mod1 { //// var mod1var = 1; @@ -231,76 +231,50 @@ //// x: /*objectLiteral*/ ////} -goTo.marker('extendedClass'); - -verify.not.completionListContains('mod1'); -verify.not.completionListContains('mod2'); -verify.not.completionListContains('mod3'); -verify.not.completionListContains('shwvar', 'var shwvar: number'); -verify.not.completionListContains('shwfn', 'function shwfn(): void'); -verify.not.completionListContains('shwcls', 'class shwcls'); -verify.not.completionListContains('shwint', 'interface shwint'); - -verify.not.completionListContains('mod2var'); -verify.not.completionListContains('mod2fn'); -verify.not.completionListContains('mod2cls'); -verify.not.completionListContains('mod2int'); -verify.not.completionListContains('mod2mod'); -verify.not.completionListContains('mod2evar'); -verify.not.completionListContains('mod2efn'); -verify.not.completionListContains('mod2ecls'); -verify.not.completionListContains('mod2eint'); -verify.not.completionListContains('mod2emod'); -verify.not.completionListContains('sfvar'); -verify.not.completionListContains('sffn'); -verify.not.completionListContains('scvar'); -verify.not.completionListContains('scfn'); -verify.completionListContains('scpfn'); -verify.completionListContains('scpvar'); -verify.not.completionListContains('scsvar'); -verify.not.completionListContains('scsfn'); -verify.not.completionListContains('sivar'); -verify.not.completionListContains('sifn'); -verify.not.completionListContains('mod1exvar'); -verify.not.completionListContains('mod2eexvar'); - -function goToMarkerAndVerify(marker: string) -{ - goTo.marker(marker); - - verify.completionListContains('mod1'); - verify.completionListContains('mod2'); - verify.completionListContains('mod3'); - verify.completionListContains('shwvar', 'var shwvar: number'); - verify.completionListContains('shwfn', 'function shwfn(): void'); - verify.completionListContains('shwcls', 'class shwcls'); - verify.not.completionListContains('shwint', 'interface shwint'); - - verify.not.completionListContains('mod2var'); - verify.not.completionListContains('mod2fn'); - verify.not.completionListContains('mod2cls'); - verify.not.completionListContains('mod2int'); - verify.not.completionListContains('mod2mod'); - verify.not.completionListContains('mod2evar'); - verify.not.completionListContains('mod2efn'); - verify.not.completionListContains('mod2ecls'); - verify.not.completionListContains('mod2eint'); - verify.not.completionListContains('mod2emod'); - verify.not.completionListContains('sfvar'); - verify.not.completionListContains('sffn'); - verify.not.completionListContains('scvar'); - verify.not.completionListContains('scfn'); - verify.not.completionListContains('scpfn'); - verify.not.completionListContains('scpvar'); - verify.not.completionListContains('scsvar'); - verify.not.completionListContains('scsfn'); - verify.not.completionListContains('sivar'); - verify.not.completionListContains('sifn'); - verify.not.completionListContains('mod1exvar'); - verify.not.completionListContains('mod2eexvar'); -} - -goToMarkerAndVerify('objectLiteral'); - -goTo.marker('localVar'); -verify.completionListContains('shwvar', '(local var) shwvar: string'); \ No newline at end of file +verify.completions( + { + marker: "extendedClass", + exact: ["scpfn", "scpvar", ...completion.classElementKeywords], + isNewIdentifierLocation: true, + }, + { + marker: "objectLiteral", + includes: [ + "mod1", + "mod2", + "mod3", + { name: "shwvar", text: "var shwvar: number" }, + { name: "shwfn", text: "function shwfn(): void" }, + { name: "shwcls", text: "class shwcls" }, + ], + excludes: [ + "shwint", + "mod2var", + "mod2fn", + "mod2cls", + "mod2int", + "mod2mod", + "mod2evar", + "mod2efn", + "mod2ecls", + "mod2eint", + "mod2emod", + "sfvar", + "sffn", + "scvar", + "scfn", + "scpfn", + "scpvar", + "scsvar", + "scsfn", + "sivar", + "sifn", + "mod1exvar", + "mod2eexvar", + ] + }, + { + marker: "localVar", + includes: { name: "shwvar", text: "(local var) shwvar: string" }, + }, +); diff --git a/tests/cases/fourslash/completionListWithUnresolvedModule.ts b/tests/cases/fourslash/completionListWithUnresolvedModule.ts index 0950636efee..73c6c52a937 100644 --- a/tests/cases/fourslash/completionListWithUnresolvedModule.ts +++ b/tests/cases/fourslash/completionListWithUnresolvedModule.ts @@ -5,6 +5,4 @@ //// var n: num/**/ ////} -goTo.marker(); - -verify.completionListContains('number'); +verify.completions({ marker: "", includes: "number" }); diff --git a/tests/cases/fourslash/completionList_getExportsOfModule.ts b/tests/cases/fourslash/completionList_getExportsOfModule.ts index 160ac17d843..55e4b8d49f5 100644 --- a/tests/cases/fourslash/completionList_getExportsOfModule.ts +++ b/tests/cases/fourslash/completionList_getExportsOfModule.ts @@ -11,6 +11,5 @@ //// ////let y: /**/ -goTo.marker(); // This is just a dummy test to cause `getCompletionsAtPosition` to be called. -verify.not.completionListContains("x"); +verify.completions({ marker: "", excludes: "x" }); diff --git a/tests/cases/fourslash/completionOfInterfaceAndVar.ts b/tests/cases/fourslash/completionOfInterfaceAndVar.ts index be1a1546d0b..748078f2b4e 100644 --- a/tests/cases/fourslash/completionOfInterfaceAndVar.ts +++ b/tests/cases/fourslash/completionOfInterfaceAndVar.ts @@ -1,17 +1,23 @@ /// -////interface AnalyserNode { -////} -////declare var AnalyserNode: { -//// prototype: AnalyserNode; -//// new(): AnalyserNode; +////interface AnalyserNode { +////} +////declare var AnalyserNode: { +//// prototype: AnalyserNode; +//// new(): AnalyserNode; ////}; /////**/ -goTo.marker(); -verify.completionListContains("AnalyserNode", /*text*/ undefined, /*documentation*/ undefined, "var"); -verify.completionEntryDetailIs("AnalyserNode", `interface AnalyserNode +verify.completions({ + marker: "", + includes: { + name: "AnalyserNode", + text: +`interface AnalyserNode var AnalyserNode: { new (): AnalyserNode; prototype: AnalyserNode; -}`, /*documentation*/ undefined, "var") \ No newline at end of file +}`, + kind: "var", + }, +}); diff --git a/tests/cases/fourslash/completionWithConditionalOperatorMissingColon.ts b/tests/cases/fourslash/completionWithConditionalOperatorMissingColon.ts index 9ec879d5022..95efcebbbf8 100644 --- a/tests/cases/fourslash/completionWithConditionalOperatorMissingColon.ts +++ b/tests/cases/fourslash/completionWithConditionalOperatorMissingColon.ts @@ -1,6 +1,5 @@ -/// -////1 ? fun/*1*/ -////function func () {} - -goTo.marker("1"); -verify.completionListContains("func"); +/// +////1 ? fun/*1*/ +////function func () {} + +verify.completions({ marker: "1", includes: "func" }); diff --git a/tests/cases/fourslash/completionWithDotFollowedByNamespaceKeyword.ts b/tests/cases/fourslash/completionWithDotFollowedByNamespaceKeyword.ts index 1526224eb20..5f8ce63251f 100644 --- a/tests/cases/fourslash/completionWithDotFollowedByNamespaceKeyword.ts +++ b/tests/cases/fourslash/completionWithDotFollowedByNamespaceKeyword.ts @@ -8,5 +8,4 @@ //// export function baz() { } ////} -goTo.marker(); -verify.completionListContains("baz", "function B.baz(): void"); \ No newline at end of file +verify.completions({ marker: "", exact: { name: "baz", text: "function B.baz(): void" } }); diff --git a/tests/cases/fourslash/completionWithNamespaceInsideFunction.ts b/tests/cases/fourslash/completionWithNamespaceInsideFunction.ts index f9259dd2eed..9892af996b9 100644 --- a/tests/cases/fourslash/completionWithNamespaceInsideFunction.ts +++ b/tests/cases/fourslash/completionWithNamespaceInsideFunction.ts @@ -21,26 +21,27 @@ ////} /////*33*/ -goTo.marker('1'); -verify.completionListContains("f", "function f(): void"); -verify.not.completionListContains("n", "namespace n"); -verify.not.completionListContains("I", "interface I"); - -goTo.marker('2'); -verify.completionListContains("f", "function f(): void"); -verify.not.completionListContains("n", "namespace n"); - -goTo.marker('3'); -verify.completionListContains("f", "function f(): void"); - -goTo.marker('11'); -verify.completionListContains("f2", "function f2(): void"); -verify.completionListContains("n2", "namespace n2"); -verify.completionListContains("I2", "class I2"); - -goTo.marker('22'); -verify.completionListContains("f2", "function f2(): void"); -verify.completionListContains("n2", "namespace n2"); - -goTo.marker('33'); -verify.completionListContains("f2", "function f2(): void"); \ No newline at end of file +verify.completions( + { marker: ["1", "2", "3"], includes: { name: "f", text: "function f(): void" }, excludes: ["n", "I"] }, + { + marker: "11", + includes: [ + { name: "f2", text: "function f2(): void" }, + { name: "n2", text: "namespace n2" }, + { name: "I2", text: "class I2" }, + ], + }, + { + marker: "22", + includes: [ + { name: "f2", text: "function f2(): void" }, + { name: "n2", text: "namespace n2" }, + ], + excludes: "I2", + }, + { + marker: "33", + includes: { name: "f2", text: "function f2(): void" }, + excludes: ["n2", "I2"], + }, +); diff --git a/tests/cases/fourslash/completionsDefaultExport.ts b/tests/cases/fourslash/completionsDefaultExport.ts index 82bcefac403..fff39786230 100644 --- a/tests/cases/fourslash/completionsDefaultExport.ts +++ b/tests/cases/fourslash/completionsDefaultExport.ts @@ -7,5 +7,4 @@ ////import * as a from "./a"; ////a./**/; -goTo.marker(); -verify.completionListContains("default", "function f(): void"); +verify.completions({ marker: "", exact: { name: "default", text: "function f(): void" } }); diff --git a/tests/cases/fourslash/completionsDestructuring.ts b/tests/cases/fourslash/completionsDestructuring.ts index d2e9f38871e..63cca7c4101 100644 --- a/tests/cases/fourslash/completionsDestructuring.ts +++ b/tests/cases/fourslash/completionsDestructuring.ts @@ -5,8 +5,4 @@ ////const { /*b*/ } = points[0]; ////for (const { /*c*/ } of points) {} -goTo.eachMarker(() => { - verify.completionListContains("x"); - verify.completionListContains("y"); - verify.completionListCount(2); -}); +verify.completions({ marker: test.markers(), exact: ["x", "y"] }); diff --git a/tests/cases/fourslash/completionsForRecursiveGenericTypesMember.ts b/tests/cases/fourslash/completionsForRecursiveGenericTypesMember.ts index 993b9eb73ac..afede5d3534 100644 --- a/tests/cases/fourslash/completionsForRecursiveGenericTypesMember.ts +++ b/tests/cases/fourslash/completionsForRecursiveGenericTypesMember.ts @@ -1,7 +1,7 @@ /// //// export class TestBase> -//// { +//// { //// public publicMethod(p: any): void {} //// private privateMethod(p: any): void {} //// protected protectedMethod(p: any): void {} @@ -11,8 +11,4 @@ //// } //// } -goTo.marker(); - -verify.completionListContains('publicMethod'); -verify.completionListContains('privateMethod'); -verify.completionListContains('protectedMethod'); +verify.completions({ marker: "", exact: ["publicMethod", "privateMethod", "protectedMethod", "test"] }); diff --git a/tests/cases/fourslash/completionsImportBaseUrl.ts b/tests/cases/fourslash/completionsImportBaseUrl.ts index 372dd86d4e9..413c7984215 100644 --- a/tests/cases/fourslash/completionsImportBaseUrl.ts +++ b/tests/cases/fourslash/completionsImportBaseUrl.ts @@ -15,8 +15,15 @@ ////fo/**/ // Test that it prefers a relative import (see sourceDisplay). -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/src/a" }, "const foo: 0", "", "const", undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { + name: "foo", + source: "/src/a", + sourceDisplay: "./a", + text: "const foo: 0", + kind: "const", + hasAction: true, + }, + preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts b/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts index 5f9c677b61f..35c06d5a550 100644 --- a/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts +++ b/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts @@ -8,10 +8,17 @@ ////import { x } from "./a"; ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + hasAction: true, + }, + preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts b/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts index 2b9543f0cb6..0a52a7103ee 100644 --- a/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts +++ b/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts @@ -7,12 +7,11 @@ ////import * as a from "./a"; ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts b/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts index db9b23b082b..d3027bb18cf 100644 --- a/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts +++ b/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts @@ -7,12 +7,11 @@ ////import f_o_o from "./a"; ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_default_anonymous.ts b/tests/cases/fourslash/completionsImport_default_anonymous.ts index 82e5f07b064..46b333beb29 100644 --- a/tests/cases/fourslash/completionsImport_default_anonymous.ts +++ b/tests/cases/fourslash/completionsImport_default_anonymous.ts @@ -2,6 +2,7 @@ // Use `/src` to test that directory names are not included in conversion from module path to identifier. // @module: esnext +// @noLib: true // @Filename: /src/foo-bar.ts ////export default 0; @@ -13,8 +14,15 @@ goTo.marker("0"); const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; verify.completions( - { marker: "0", excludes: { name: "default", source: "/src/foo-bar" }, preferences }, - { marker: "1", includes: { name: "fooBar", source: "/src/foo-bar", sourceDisplay: "./foo-bar", text: "(property) default: 0", kind: "property", hasAction: true }, preferences } + { + marker: "0", + exact: ["undefined", ...completion.statementKeywordsWithTypes], + }, + { + marker: "1", + includes: { name: "fooBar", source: "/src/foo-bar", sourceDisplay: "./foo-bar", text: "(property) default: 0", kind: "property", hasAction: true }, + preferences, + }, ); verify.applyCodeActionFromCompletion("1", { name: "fooBar", diff --git a/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts b/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts index bb77874068c..69138fa9815 100644 --- a/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts +++ b/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts @@ -8,12 +8,11 @@ // @Filename: /b.ts ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_default_exportDefaultIdentifier.ts b/tests/cases/fourslash/completionsImport_default_exportDefaultIdentifier.ts index 3f0cb27e00a..766f50fb9e9 100644 --- a/tests/cases/fourslash/completionsImport_default_exportDefaultIdentifier.ts +++ b/tests/cases/fourslash/completionsImport_default_exportDefaultIdentifier.ts @@ -12,11 +12,11 @@ ////f/**/; goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "(alias) const foo: 0\nexport default foo", "", "alias", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "(alias) const foo: 0\nexport default foo", kind: "alias", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts b/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts index 6f6c01cf4d1..c4cfcb98531 100644 --- a/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts +++ b/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts @@ -15,12 +15,11 @@ // @Filename: /c.ts /////**/ -goTo.marker(""); -verify.completionListContains({ name: "M", source: "m" }, "class M", "", "class", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "m", +verify.completions({ + marker: "", + includes: { name: "M", source: "m", sourceDisplay: "m", text: "class M", kind: "class", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "M", source: "m", diff --git a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts index e6f2565d5c1..7df6fbfd874 100644 --- a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts +++ b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts @@ -1,6 +1,7 @@ /// // @module: esnext +// @noLib: true // @Filename: /global.d.ts // A local variable would prevent import completions (see `completionsImport_shadowedByLocal.ts`), but a global doesn't. @@ -16,11 +17,17 @@ ////fo/**/ goTo.marker(""); -const options = { includeExternalModuleExports: true, sourceDisplay: undefined }; -verify.completionListContains("foo", "var foo: number", "", "var", undefined, undefined, options); -verify.completionListContains({ name: "foo", source: "/a" }, "const foo: 0", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { ...options, sourceDisplay: "./a" }); -verify.completionListContains({ name: "foo", source: "/b" }, "const foo: 1", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { ...options, sourceDisplay: "./b" }); - +verify.completions({ + marker: "", + exact: [ + { name: "foo", text: "var foo: number", kind: "var" }, + "undefined", + { name: "foo", source: "/a", sourceDisplay: "./a", text: "const foo: 0", kind: "const", hasAction: true }, + { name: "foo", source: "/b", sourceDisplay: "./b", text: "const foo: 1", kind: "const", hasAction: true }, + ...completion.statementKeywordsWithTypes, + ], + preferences: { includeCompletionsForModuleExports: true }, +}); verify.applyCodeActionFromCompletion("", { name: "foo", source: "/b", diff --git a/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts b/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts index fa1be5ca7d2..3442d90e05b 100644 --- a/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts +++ b/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts @@ -8,12 +8,11 @@ ////import { x } from "./a"; ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts index 94ed1b8a0fa..321f27ce760 100644 --- a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts +++ b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts @@ -1,5 +1,6 @@ /// +// @noLib: true // @Filename: /a.ts ////export function Test1() {} @@ -11,11 +12,12 @@ verify.completions({ marker: "", - includes: [ - { name: "Test1", source: "/a", sourceDisplay: "./a", text: "function Test1(): void", kind: "function", hasAction: true }, + exact: [ { name: "Test2", text: "(alias) function Test2(): void\nimport Test2", kind: "alias" }, + "undefined", + { name: "Test1", source: "/a", sourceDisplay: "./a", text: "function Test1(): void", kind: "function", hasAction: true }, + ...completion.statementKeywordsWithTypes, ], - excludes: [{ name: "Test2", source: "/a" }], preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts index b9b9b2b3ced..c6c9bc45b2c 100644 --- a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts +++ b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts @@ -11,12 +11,11 @@ // @Filename: /b.ts ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "const N.foo: 0", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "const N.foo: 0", kind: "const", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts index ba9f5675a1d..f68c03f5602 100644 --- a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts +++ b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts @@ -16,8 +16,8 @@ // @Filename: /a.ts ////fo/**/ -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "n" }, "const N.foo: number", "", "const", undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "n", +verify.completions({ + marker: "", + includes: { name: "foo", source: "n", sourceDisplay: "n", text: "const N.foo: number", kind: "const", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts b/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts index fddd8ae12ca..4416b3703c9 100644 --- a/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts +++ b/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts @@ -7,12 +7,11 @@ ////import * as a from "./a"; ////f/**/; -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_notFromIndex.ts b/tests/cases/fourslash/completionsImport_notFromIndex.ts index c42c768d23d..4ab8eaf1012 100644 --- a/tests/cases/fourslash/completionsImport_notFromIndex.ts +++ b/tests/cases/fourslash/completionsImport_notFromIndex.ts @@ -16,8 +16,11 @@ ////x/*2*/ for (const [marker, sourceDisplay] of [["0", "./src"], ["1", "./a"], ["2", "../a"]]) { - goTo.marker(marker); - verify.completionListContains({ name: "x", source: "/src/a" }, "const x: 0", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { includeCompletionsForModuleExports: true, sourceDisplay }); + verify.completions({ + marker, + includes: { name: "x", source: "/src/a", sourceDisplay, text: "const x: 0", kind: "const", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, + }); verify.applyCodeActionFromCompletion(marker, { name: "x", source: "/src/a", diff --git a/tests/cases/fourslash/completionsImport_ofAlias.ts b/tests/cases/fourslash/completionsImport_ofAlias.ts index 708a5b99d3a..cb6af7910ba 100644 --- a/tests/cases/fourslash/completionsImport_ofAlias.ts +++ b/tests/cases/fourslash/completionsImport_ofAlias.ts @@ -21,8 +21,11 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "(alias) const foo: 0\nexport foo", kind: "alias", hasAction: true }, - excludes: [{ name: "foo", source: "/a_reexport" }, { name: "foo", source: "/a_reexport_2" }], + includes: [ + "undefined", + { name: "foo", source: "/a", sourceDisplay: "./a", text: "(alias) const foo: 0\nexport foo", kind: "alias", hasAction: true }, + ...completion.statementKeywordsWithTypes, + ], preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts index 78ac08a1c12..81d195d0175 100644 --- a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts +++ b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts @@ -5,6 +5,7 @@ // @moduleResolution: node // @module: commonJs +// @noLib: true // @Filename: /foo/index.ts ////export { foo } from "./lib/foo"; @@ -17,8 +18,11 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/foo/lib/foo", sourceDisplay: "./foo", text: "const foo: 0", kind: "const", hasAction: true }, - excludes: { name: "foo", source: "/foo/index" }, + exact: [ + "undefined", + { name: "foo", source: "/foo/lib/foo", sourceDisplay: "./foo", text: "const foo: 0", kind: "const", hasAction: true }, + ...completion.statementKeywordsWithTypes, + ], preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts b/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts index 06fb93283ee..36649451530 100644 --- a/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts +++ b/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts @@ -7,8 +7,8 @@ ////import * as a from 'a'; /////**/ -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_reExportDefault.ts b/tests/cases/fourslash/completionsImport_reExportDefault.ts index b5c93e9dc0a..ae8af9c1d35 100644 --- a/tests/cases/fourslash/completionsImport_reExportDefault.ts +++ b/tests/cases/fourslash/completionsImport_reExportDefault.ts @@ -12,10 +12,16 @@ // @Filename: /use.ts ////fo/**/ -goTo.marker(""); -verify.completionListContains({ name: "foo", source: "/a/b/impl" }, "function foo(): void", "", "function", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "", + exact: [ + ...completion.globalsVars, + "undefined", + { name: "foo", source: "/a/b/impl", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + { name: "foo", source: "/a/index", sourceDisplay: "./a", text: "(alias) function foo(): void\nexport foo", kind: "alias", hasAction: true }, + ...completion.globalKeywords, + ], + preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { name: "foo", diff --git a/tests/cases/fourslash/completionsImport_reExport_wrongName.ts b/tests/cases/fourslash/completionsImport_reExport_wrongName.ts index 912f133e72a..31de7ef7d8d 100644 --- a/tests/cases/fourslash/completionsImport_reExport_wrongName.ts +++ b/tests/cases/fourslash/completionsImport_reExport_wrongName.ts @@ -20,7 +20,6 @@ verify.completions({ ], preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("", { name: "x", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_require.ts b/tests/cases/fourslash/completionsImport_require.ts index c90eb6246e7..6002366ce02 100644 --- a/tests/cases/fourslash/completionsImport_require.ts +++ b/tests/cases/fourslash/completionsImport_require.ts @@ -9,12 +9,11 @@ ////import * as s from "something"; ////fo/*b*/ -goTo.marker("b"); -verify.completionListContains({ name: "foo", source: "/a" }, "const foo: 0", "", "const", /*spanIndex*/ undefined, /*hasAction*/ true, { - includeCompletionsForModuleExports: true, - sourceDisplay: "./a", +verify.completions({ + marker: "b", + includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "const foo: 0", kind: "const", hasAction: true }, + preferences: { includeCompletionsForModuleExports: true }, }); - verify.applyCodeActionFromCompletion("b", { name: "foo", source: "/a", diff --git a/tests/cases/fourslash/completionsImport_shadowedByLocal.ts b/tests/cases/fourslash/completionsImport_shadowedByLocal.ts index 7ad88ff4d2f..afe88fa6da8 100644 --- a/tests/cases/fourslash/completionsImport_shadowedByLocal.ts +++ b/tests/cases/fourslash/completionsImport_shadowedByLocal.ts @@ -1,5 +1,7 @@ /// +// @noLib: true + // @Filename: /a.ts ////export const foo = 0; @@ -9,7 +11,6 @@ verify.completions({ marker: "", - includes: "foo", - excludes: { name: "foo", source: "/a" }, + exact: [{ name: "foo", text: "const foo: 1" }, "undefined", ...completion.statementKeywordsWithTypes], preferences: { includeCompletionsForModuleExports: true }, -}) +}); diff --git a/tests/cases/fourslash/completionsInJsxTag.ts b/tests/cases/fourslash/completionsInJsxTag.ts index 223c3875cbd..e2921aecd15 100644 --- a/tests/cases/fourslash/completionsInJsxTag.ts +++ b/tests/cases/fourslash/completionsInJsxTag.ts @@ -19,9 +19,4 @@ //// } ////} -goTo.marker("1"); -verify.completionListCount(1); -verify.completionListContains("foo", "(JSX attribute) foo: string", "Doc", "JSX attribute"); -goTo.marker("2"); -verify.completionListCount(1); -verify.completionListContains("foo", "(JSX attribute) foo: string", "Doc", "JSX attribute"); +verify.completions({ marker: ["1", "2"], exact: { name: "foo", text: "(JSX attribute) foo: string", documentation: "Doc", kind: "JSX attribute" } }); diff --git a/tests/cases/fourslash/completionsInterfaceElement.ts b/tests/cases/fourslash/completionsInterfaceElement.ts index cbf15581dc0..65b1627c8f3 100644 --- a/tests/cases/fourslash/completionsInterfaceElement.ts +++ b/tests/cases/fourslash/completionsInterfaceElement.ts @@ -13,6 +13,4 @@ ////interface EndOfFile { f; /*e*/ -for (const marker of test.markerNames()) { - verify.completionsAt(marker, ["readonly"], { isNewIdentifierLocation: true }); -} +verify.completions({ marker: test.markers(), exact: "readonly", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsJsPropertyAssignment.ts b/tests/cases/fourslash/completionsJsPropertyAssignment.ts index c7e8a9ad268..77fade15b76 100644 --- a/tests/cases/fourslash/completionsJsPropertyAssignment.ts +++ b/tests/cases/fourslash/completionsJsPropertyAssignment.ts @@ -7,4 +7,4 @@ ////const x = { p: "x" }; ////x.p = "/**/"; -verify.completionsAt("", ["x", "y"]); +verify.completions({ marker: "", exact: ["x", "y"] }); diff --git a/tests/cases/fourslash/completionsJsdocTag.ts b/tests/cases/fourslash/completionsJsdocTag.ts index 0a8088ebfaa..71a7a97bc6e 100644 --- a/tests/cases/fourslash/completionsJsdocTag.ts +++ b/tests/cases/fourslash/completionsJsdocTag.ts @@ -5,5 +5,4 @@ //// * /**/ //// */ -goTo.marker(); -verify.completionListContains("@property", "@property", "", "keyword"); +verify.completions({ marker: "", includes: { name: "@property", text: "@property", kind: "keyword" } }); diff --git a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts index 822069feb53..5eff16bb278 100644 --- a/tests/cases/fourslash/completionsJsdocTypeTagCast.ts +++ b/tests/cases/fourslash/completionsJsdocTypeTagCast.ts @@ -4,4 +4,4 @@ // @Filename: /a.js ////const x = /** @type {{ s: string }} */ ({ /**/ }); -verify.completionsAt("", ["s", "x"]); +verify.completions({ marker: "", exact: ["s", "x"] }); diff --git a/tests/cases/fourslash/completionsJsxAttributeInitializer.ts b/tests/cases/fourslash/completionsJsxAttributeInitializer.ts index f473d0be422..44d79b059a6 100644 --- a/tests/cases/fourslash/completionsJsxAttributeInitializer.ts +++ b/tests/cases/fourslash/completionsJsxAttributeInitializer.ts @@ -5,19 +5,14 @@ ////
; ////} -goTo.marker(); - -verify.completionListContains("x", "(parameter) x: number", "", "parameter", undefined, undefined, { - includeInsertTextCompletions: true, - insertText: "{x}", -}); - -verify.completionListContains("p", "(JSX attribute) p: number", "", "JSX attribute", undefined, undefined, { - includeInsertTextCompletions: true, - insertText: "{this.p}", -}); - -verify.completionListContains("a b", '(JSX attribute) "a b": number', "", "JSX attribute", undefined, undefined, { - includeInsertTextCompletions: true, - insertText: '{this["a b"]}', +verify.completions({ + marker: "", + includes: [ + { name: "x", text: "(parameter) x: number", kind: "parameter", insertText: "{x}" }, + { name: "p", text: "(JSX attribute) p: number", kind: "JSX attribute", insertText: "{this.p}" }, + { name: "a b", text: '(JSX attribute) "a b": number', kind: "JSX attribute", insertText: '{this["a b"]}' }, + ], + preferences: { + includeInsertTextCompletions: true, + }, }); diff --git a/tests/cases/fourslash/completionsJsxAttributeInitializer2.ts b/tests/cases/fourslash/completionsJsxAttributeInitializer2.ts index 581d0ad2b53..e9d740b2b42 100644 --- a/tests/cases/fourslash/completionsJsxAttributeInitializer2.ts +++ b/tests/cases/fourslash/completionsJsxAttributeInitializer2.ts @@ -12,12 +12,11 @@ ////
////
-const [replacementSpan] = test.ranges(); -goTo.marker("0"); -verify.completionListContains("foo", "const foo: 0", undefined, "const", undefined, undefined, { - includeInsertTextCompletions: true, - insertText: "{foo}", - replacementSpan, -}); - -verify.completionsAt(["1", "2"], ["b"]); +verify.completions( + { + marker: "0", + includes: { name: "foo", text: "const foo: 0", kind: "const", insertText: "{foo}", replacementSpan: test.ranges()[0] }, + preferences: { includeInsertTextCompletions: true }, + }, + { marker: ["1", "2"], exact: "b" }, +); diff --git a/tests/cases/fourslash/completionsKeyof.ts b/tests/cases/fourslash/completionsKeyof.ts index e3beae556c5..3f743ed604d 100644 --- a/tests/cases/fourslash/completionsKeyof.ts +++ b/tests/cases/fourslash/completionsKeyof.ts @@ -7,11 +7,7 @@ ////function g(key: T) {} ////g("/*g*/"); -goTo.marker("f"); -verify.completionListCount(1); -verify.completionListContains("a"); - -goTo.marker("g"); -verify.completionListCount(2); -verify.completionListContains("a"); -verify.completionListContains("b"); +verify.completions( + { marker: "f", exact: "a" }, + { marker: "g", exact: ["a", "b"] }, +); diff --git a/tests/cases/fourslash/completionsKeywordsExtends.ts b/tests/cases/fourslash/completionsKeywordsExtends.ts index 50c9b741cda..bd88311b46c 100644 --- a/tests/cases/fourslash/completionsKeywordsExtends.ts +++ b/tests/cases/fourslash/completionsKeywordsExtends.ts @@ -5,11 +5,7 @@ // Tests that `isCompletionListBlocker` is true *at* the class name, but false *after* it. -goTo.marker("a"); -verify.completionListIsEmpty(); - -goTo.marker("b"); -verify.completionListContains("extends"); - -goTo.marker("c"); -verify.completionListContains("extends"); +verify.completions( + { marker: "a", exact: undefined }, + { marker: ["b", "c"], includes: "extends" }, +); diff --git a/tests/cases/fourslash/completionsMethodWithThisParameter.ts b/tests/cases/fourslash/completionsMethodWithThisParameter.ts index eb7c00421dd..d746f3626dc 100644 --- a/tests/cases/fourslash/completionsMethodWithThisParameter.ts +++ b/tests/cases/fourslash/completionsMethodWithThisParameter.ts @@ -14,5 +14,7 @@ ////s./*s*/; ////n./*n*/; -verify.completionsAt("s", ["value", "ms", "mo", "mt", "mp", "mps"]); -verify.completionsAt("n", ["value", "mo", "mt", "mp"]); +verify.completions( + { marker: "s", exact: ["value", "ms", "mo", "mt", "mp", "mps"] }, + { marker: "n", exact: ["value", "mo", "mt", "mp"] }, +); diff --git a/tests/cases/fourslash/completionsNamespaceMergedWithClass.ts b/tests/cases/fourslash/completionsNamespaceMergedWithClass.ts index 414a233bdb1..109b6f72b1b 100644 --- a/tests/cases/fourslash/completionsNamespaceMergedWithClass.ts +++ b/tests/cases/fourslash/completionsNamespaceMergedWithClass.ts @@ -12,10 +12,7 @@ ////let x: D./*type*/; ////D./*value*/ -goTo.marker("type"); -verify.completionListContains("T"); -verify.not.completionListContains("m"); - -goTo.marker("value"); -verify.not.completionListContains("T"); -verify.completionListContains("m"); +verify.completions( + { marker: "type", exact: "T" }, + { marker: "value", exact: ["prototype", "m", ...completion.functionMembers] }, +); diff --git a/tests/cases/fourslash/completionsNamespaceMergedWithObject.ts b/tests/cases/fourslash/completionsNamespaceMergedWithObject.ts index cd799981ee7..f93792641df 100644 --- a/tests/cases/fourslash/completionsNamespaceMergedWithObject.ts +++ b/tests/cases/fourslash/completionsNamespaceMergedWithObject.ts @@ -7,10 +7,7 @@ ////let x: N./*type*/; ////N./*value*/; -goTo.marker("type"); -verify.completionListContains("T"); -verify.not.completionListContains("m"); - -goTo.marker("value"); -verify.not.completionListContains("T"); -verify.completionListContains("m"); +verify.completions( + { marker: "type", exact: "T" }, + { marker: "value", exact: "m" }, +); diff --git a/tests/cases/fourslash/completionsNewTarget.ts b/tests/cases/fourslash/completionsNewTarget.ts index 3f8a4d689cc..5c25ecbc739 100644 --- a/tests/cases/fourslash/completionsNewTarget.ts +++ b/tests/cases/fourslash/completionsNewTarget.ts @@ -6,5 +6,4 @@ //// } ////} -goTo.marker(""); -verify.completionListContains("target"); \ No newline at end of file +verify.completions({ marker: "", exact: "target" }); diff --git a/tests/cases/fourslash/completionsOptionalKindModifier.ts b/tests/cases/fourslash/completionsOptionalKindModifier.ts index 39ace2342d3..1592fb5d10b 100644 --- a/tests/cases/fourslash/completionsOptionalKindModifier.ts +++ b/tests/cases/fourslash/completionsOptionalKindModifier.ts @@ -5,6 +5,10 @@ ////x./*a*/; ////} -goTo.marker("a"); -verify.completionListContains("a", /* text */ undefined, /* documentation */ undefined, { kindModifiers: "optional" }); -verify.completionListContains("method", /* text */ undefined, /* documentation */ undefined, { kindModifiers: "optional" }); +verify.completions({ + marker: "a", + exact: [ + { name: "a", kindModifiers: "optional" }, + { name: "method", kindModifiers: "optional" }, + ], +}); diff --git a/tests/cases/fourslash/completionsOptionalMethod.ts b/tests/cases/fourslash/completionsOptionalMethod.ts index 72399f177f2..4c70e316062 100644 --- a/tests/cases/fourslash/completionsOptionalMethod.ts +++ b/tests/cases/fourslash/completionsOptionalMethod.ts @@ -5,4 +5,4 @@ ////declare const x: { m?(): void }; ////x./**/ -verify.completionsAt("", ["m"]); +verify.completions({ marker: "", exact: "m" }); diff --git a/tests/cases/fourslash/completionsPathsJsonModule.ts b/tests/cases/fourslash/completionsPathsJsonModule.ts index 6d1a621d69a..fb3370c69c9 100644 --- a/tests/cases/fourslash/completionsPathsJsonModule.ts +++ b/tests/cases/fourslash/completionsPathsJsonModule.ts @@ -9,4 +9,4 @@ // @Filename: /project/index.ts ////import { } from "/**/"; -verify.completionsAt("", ["test.json"], { isNewIdentifierLocation: true }); \ No newline at end of file +verify.completions({ marker: "", exact: "test.json", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPathsJsonModuleWithAmd.ts b/tests/cases/fourslash/completionsPathsJsonModuleWithAmd.ts index 8a2388655af..27676d1fdc9 100644 --- a/tests/cases/fourslash/completionsPathsJsonModuleWithAmd.ts +++ b/tests/cases/fourslash/completionsPathsJsonModuleWithAmd.ts @@ -9,4 +9,4 @@ // @Filename: /project/index.ts ////import { } from ".//**/"; -verify.completionsAt("", [], { isNewIdentifierLocation: true }); \ No newline at end of file +verify.completions({ marker: "", exact: [], isNewIdentifierLocation: true }); \ No newline at end of file diff --git a/tests/cases/fourslash/completionsPathsJsonModuleWithoutResolveJsonModule.ts b/tests/cases/fourslash/completionsPathsJsonModuleWithoutResolveJsonModule.ts index 432fc6e858b..95a44683247 100644 --- a/tests/cases/fourslash/completionsPathsJsonModuleWithoutResolveJsonModule.ts +++ b/tests/cases/fourslash/completionsPathsJsonModuleWithoutResolveJsonModule.ts @@ -8,4 +8,4 @@ // @Filename: /project/index.ts ////import { } from ".//**/"; -verify.completionsAt("", [], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: [], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts b/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts index 93a6ac6e4e2..a0c9f92e545 100644 --- a/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts +++ b/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts @@ -9,4 +9,4 @@ // @Filename: /project/index.ts ////import { } from ".//**/"; -verify.completionsAt("", ["test.json"], { isNewIdentifierLocation: true }); \ No newline at end of file +verify.completions({ marker: "", exact: "test.json", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping.ts b/tests/cases/fourslash/completionsPaths_pathMapping.ts index c6c879dc97e..9bff5424e5d 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping.ts @@ -21,5 +21,7 @@ ////} const [r0, r1] = test.ranges(); -verify.completionsAt("0", ["a", "b", "dir"], { isNewIdentifierLocation: true }); -verify.completionsAt("1", ["x"], { isNewIdentifierLocation: true }); +verify.completions( + { marker: "0", exact: ["a", "b", "dir"], isNewIdentifierLocation: true }, + { marker: "1", exact: "x", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts index 71d07052318..f870af30656 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts @@ -16,4 +16,4 @@ //// } ////} -verify.completionsAt("", ["x"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: ["x"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts index a9af29cd6e7..a86e5bcb0d3 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts @@ -19,4 +19,4 @@ //// } ////} -verify.completionsAt("", ["a", "b"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: ["a", "b"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts index 449ff3f65bd..9b9c67abbfc 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts @@ -13,4 +13,4 @@ //// } ////} -verify.completionsAt("", ["src", "foo/"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "", exact: ["src", "foo/"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsRecommended_contextualTypes.ts b/tests/cases/fourslash/completionsRecommended_contextualTypes.ts index fb88434f98a..8d35ba13146 100644 --- a/tests/cases/fourslash/completionsRecommended_contextualTypes.ts +++ b/tests/cases/fourslash/completionsRecommended_contextualTypes.ts @@ -20,16 +20,24 @@ recommended("arg0"); recommended("arg1", { enumName: "F" }); -recommended("prop"); +recommended("prop", { isNewIdentifierLocation: false }); recommended("tag"); -recommended("jsx"); -recommended("jsx2", { insertText: "{E}" }); +recommended("jsx", { isNewIdentifierLocation: false }); +recommended("jsx2", { isNewIdentifierLocation: false, insertText: "{E}" }); -function recommended(markerName: string, { insertText, enumName = "E" }: { insertText?: string, enumName?: string } = {}) { - goTo.marker(markerName); - verify.completionListContains(enumName, `enum ${enumName}`, "", "enum", undefined, undefined , { - isRecommended: true, - includeInsertTextCompletions: true, - insertText, +function recommended(marker: string, { insertText, isNewIdentifierLocation = true, enumName = "E" }: { insertText?: string, isNewIdentifierLocation?: boolean, enumName?: string } = {}) { + verify.completions({ + marker, + includes: { + name: enumName, + text: `enum ${enumName}`, + kind: "enum", + isRecommended: true, + insertText, + }, + isNewIdentifierLocation, + preferences: { + includeInsertTextCompletions: true, + }, }); } diff --git a/tests/cases/fourslash/completionsRecommended_equals.ts b/tests/cases/fourslash/completionsRecommended_equals.ts index 37e4c931359..356a9410ba2 100644 --- a/tests/cases/fourslash/completionsRecommended_equals.ts +++ b/tests/cases/fourslash/completionsRecommended_equals.ts @@ -5,6 +5,7 @@ ////e === /*a*/; ////e === E/*b*/ -goTo.eachMarker(["a", "b"], () => { - verify.completionListContains("Enu", "enum Enu", "", "enum", undefined, undefined, { isRecommended: true }); +verify.completions({ + marker: ["a", "b"], + includes: { name: "Enu", text: "enum Enu", kind: "enum", isRecommended: true }, }); diff --git a/tests/cases/fourslash/completionsRecommended_import.ts b/tests/cases/fourslash/completionsRecommended_import.ts index 158221f03a8..4f58827f742 100644 --- a/tests/cases/fourslash/completionsRecommended_import.ts +++ b/tests/cases/fourslash/completionsRecommended_import.ts @@ -18,21 +18,27 @@ ////alpha.f(new al/*c0*/); ////alpha.f(new /*c1*/); -goTo.eachMarker(["b0", "b1"], (_, idx) => { - verify.completionListContains( - { name: "Cls", source: "/a" }, - idx === 0 ? "constructor Cls(): Cls" : "class Cls", - "", - "class", - undefined, - /*hasAction*/ true, { - includeExternalModuleExports: true, - isRecommended: true, - sourceDisplay: "./a", - }); +const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; +const classEntry = (isConstructor: boolean): FourSlashInterface.ExpectedCompletionEntry => ({ + name: "Cls", + source: "/a", + sourceDisplay: "./a", + kind: "class", + text: isConstructor ? "constructor Cls(): Cls" : "class Cls", + hasAction: true, + isRecommended: true, }); - -goTo.eachMarker(["c0", "c1"], (_, idx) => { - verify.completionListContains("alpha", "import alpha", "", "alias", undefined, undefined, { isRecommended: true }) -}); - +verify.completions( + { marker: "b0", includes: classEntry(true), preferences }, + { marker: "b1", includes: classEntry(false), preferences }, + { + marker: ["c0", "c1"], + includes: { + name: "alpha", + text: "import alpha", + kind: "alias", + isRecommended: true, + }, + preferences, + }, +); diff --git a/tests/cases/fourslash/completionsRecommended_local.ts b/tests/cases/fourslash/completionsRecommended_local.ts index ca098bae442..76690b7dbbd 100644 --- a/tests/cases/fourslash/completionsRecommended_local.ts +++ b/tests/cases/fourslash/completionsRecommended_local.ts @@ -15,23 +15,28 @@ ////enu = E/*let0*/; ////enu = E/*let1*/; -goTo.eachMarker(["e0", "e1", "let0", "let1"], () => { - verify.completionListContains("Enu", "enum Enu", "", "enum", undefined, undefined, { isRecommended: true }); +const cls = (ctr: boolean): FourSlashInterface.ExpectedCompletionEntry => ({ + name: "Cls", + text: ctr ? "constructor Cls(): Cls" : "class Cls", + kind: "class", + isRecommended: true, }); -goTo.eachMarker(["c0", "c1"], (_, idx) => { - verify.completionListContains( - "Cls", - idx === 0 ? "constructor Cls(): Cls" : "class Cls", - "", - "class", - undefined, - undefined, { - isRecommended: true, - }); +// Not recommended, because it's an abstract class +const abs = (ctr: boolean): FourSlashInterface.ExpectedCompletionEntry => ({ + name: "Abs", + text: ctr ? "constructor Abs(): Abs" : "class Abs", + kind: "class", }); -goTo.eachMarker(["a0", "a1"], (_, idx) => { - // Not recommended, because it's an abstract class - verify.completionListContains("Abs", idx == 0 ? "constructor Abs(): Abs" : "class Abs", "", "class"); -}); +verify.completions( + { + marker: ["e0", "e1", "let0", "let1"], + includes: { name: "Enu", text: "enum Enu", kind: "enum", isRecommended: true }, + isNewIdentifierLocation: true, + }, + { marker: "c0", includes: cls(true) }, + { marker: "c1", includes: cls(false) }, + { marker: "a0", includes: abs(true) }, + { marker: "a1", includes: abs(false) }, +); diff --git a/tests/cases/fourslash/completionsRecommended_namespace.ts b/tests/cases/fourslash/completionsRecommended_namespace.ts index d3fe9c2a54b..9cf98f43b59 100644 --- a/tests/cases/fourslash/completionsRecommended_namespace.ts +++ b/tests/cases/fourslash/completionsRecommended_namespace.ts @@ -22,18 +22,12 @@ ////alpha.f(new a/*c0*/); ////alpha.f(new /*c1*/); -goTo.eachMarker(["a0", "a1"], () => { - verify.completionListContains("Name", "namespace Name", "", "module", undefined, undefined, { isRecommended: true }); -}); - -goTo.eachMarker(["b0", "b1"], () => { - verify.completionListContains({ name: "Name", source: "/a" }, "namespace Name", "", "module", undefined, /*hasAction*/ true, { - includeExternalModuleExports: true, - isRecommended: true, - sourceDisplay: "./a", - }); -}); - -goTo.eachMarker(["c0", "c1"], () => { - verify.completionListContains("alpha", "import alpha", "", "alias", undefined, undefined, { isRecommended: true }); -}); +verify.completions( + { marker: ["a0", "a1"], includes: { name: "Name", text: "namespace Name", kind: "module", isRecommended: true } }, + { + marker: ["b0", "b1"], + includes: { name: "Name", source: "/a", sourceDisplay: "./a", text: "namespace Name", kind: "module", hasAction: true, isRecommended: true, }, + preferences: { includeCompletionsForModuleExports: true }, + }, + { marker: ["c0", "c1"], includes: { name: "alpha", text: "import alpha", kind: "alias", isRecommended: true } }, +); diff --git a/tests/cases/fourslash/completionsRecommended_nonAccessibleSymbol.ts b/tests/cases/fourslash/completionsRecommended_nonAccessibleSymbol.ts index 0f27e824d2b..13afccb6c09 100644 --- a/tests/cases/fourslash/completionsRecommended_nonAccessibleSymbol.ts +++ b/tests/cases/fourslash/completionsRecommended_nonAccessibleSymbol.ts @@ -6,5 +6,4 @@ ////} ////f()(new /**/); -goTo.marker(""); -verify.not.completionListContains("C"); // Not accessible +verify.completions({ marker: "", excludes: "C" }); diff --git a/tests/cases/fourslash/completionsRecommended_switch.ts b/tests/cases/fourslash/completionsRecommended_switch.ts index a8941ac53ea..d5773c092c2 100644 --- a/tests/cases/fourslash/completionsRecommended_switch.ts +++ b/tests/cases/fourslash/completionsRecommended_switch.ts @@ -7,6 +7,7 @@ //// case /*1*/: ////} -goTo.eachMarker((_, idx) => { - verify.completionListContains("Enu", "enum Enu", "", "enum", undefined, undefined, { isRecommended: true }); +verify.completions({ + marker: test.markers(), + includes: { name: "Enu", text: "enum Enu", kind: "enum", isRecommended: true }, }); diff --git a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts index cb3f1a31fe2..e29b2b7268f 100644 --- a/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts +++ b/tests/cases/fourslash/completionsStringLiteral_fromTypeConstraint.ts @@ -3,4 +3,4 @@ ////interface Foo { foo: string; bar: string; } ////type T = Pick; -verify.completionsAt("", ["foo", "bar"]); +verify.completions({ marker: "", exact: ["foo", "bar"] }); diff --git a/tests/cases/fourslash/completionsSymbolMembers.ts b/tests/cases/fourslash/completionsSymbolMembers.ts index 269443e23dd..39b8c5c499a 100644 --- a/tests/cases/fourslash/completionsSymbolMembers.ts +++ b/tests/cases/fourslash/completionsSymbolMembers.ts @@ -11,5 +11,15 @@ ////declare const j: J; ////j[|./*j*/|]; -verify.completionsAt("i", [{ name: "s", insertText: "[s]", replacementSpan: test.ranges()[0] }], { includeInsertTextCompletions: true }); -verify.completionsAt("j", [{ name: "N", insertText: "[N]", replacementSpan: test.ranges()[1] }], { includeInsertTextCompletions: true }) +verify.completions( + { + marker: "i", + exact: { name: "s", insertText: "[s]", replacementSpan: test.ranges()[0] }, + preferences: { includeInsertTextCompletions: true }, + }, + { + marker: "j", + exact: { name: "N", insertText: "[N]", replacementSpan: test.ranges()[1] }, + preferences: { includeInsertTextCompletions: true }, + } +); diff --git a/tests/cases/fourslash/completionsUnion.ts b/tests/cases/fourslash/completionsUnion.ts index d9d1d3c792f..6bc6bd1a860 100644 --- a/tests/cases/fourslash/completionsUnion.ts +++ b/tests/cases/fourslash/completionsUnion.ts @@ -7,4 +7,4 @@ // We specifically filter out any array-like types. // Private members will be excluded by `createUnionOrIntersectionProperty`. -verify.completionsAt("", ["x"]); +verify.completions({ marker: "", exact: "x" }); diff --git a/tests/cases/fourslash/constEnumQuickInfoAndCompletionList.ts b/tests/cases/fourslash/constEnumQuickInfoAndCompletionList.ts index 8d312aa37ab..03dd93ce38d 100644 --- a/tests/cases/fourslash/constEnumQuickInfoAndCompletionList.ts +++ b/tests/cases/fourslash/constEnumQuickInfoAndCompletionList.ts @@ -7,8 +7,6 @@ ////} /////*2*/e.a; -verify.quickInfoAt("1", "const enum e"); - -goTo.marker('2'); -verify.completionListContains("e", "const enum e"); -verify.quickInfoIs("const enum e"); \ No newline at end of file +const text = "const enum e"; +verify.completions({ marker: "2", includes: { name: "e", text } }); +verify.quickInfos({ 1: text, 2: text }); diff --git a/tests/cases/fourslash/constQuickInfoAndCompletionList.ts b/tests/cases/fourslash/constQuickInfoAndCompletionList.ts index 80b7ac59507..290552d40bf 100644 --- a/tests/cases/fourslash/constQuickInfoAndCompletionList.ts +++ b/tests/cases/fourslash/constQuickInfoAndCompletionList.ts @@ -9,27 +9,22 @@ //// var z = /*6*/a; //// /*7*/ ////} -verify.quickInfoAt("1", "const a: 10"); -goTo.marker('2'); -verify.completionListContains("a", "const a: 10"); -verify.quickInfoIs("const a: 10"); +const a = "const a: 10"; +const b = "const b: 20"; +const completeA: FourSlashInterface.ExpectedCompletionEntry = { name: "a", text: a }; +const completeB: FourSlashInterface.ExpectedCompletionEntry = { name: "b", text: b }; +verify.completions( + { marker: "2", includes: completeA, excludes: "b", isNewIdentifierLocation: true }, + { marker: "3", includes: completeA, excludes: "b" }, + { marker: ["5", "6"], includes: [completeA, completeB], isNewIdentifierLocation: true }, + { marker: "7", includes: [completeA, completeB] }, +); -goTo.marker('3'); -verify.completionListContains("a", "const a: 10"); - -verify.quickInfoAt("4", "const b: 20"); - -goTo.marker('5'); -verify.completionListContains("a", "const a: 10"); -verify.completionListContains("b", "const b: 20"); -verify.quickInfoIs("const b: 20"); - -goTo.marker('6'); -verify.completionListContains("a", "const a: 10"); -verify.completionListContains("b", "const b: 20"); -verify.quickInfoIs("const a: 10"); - -goTo.marker('7'); -verify.completionListContains("a", "const a: 10"); -verify.completionListContains("b", "const b: 20"); +verify.quickInfos({ + 1: a, + 2: a, + 4: b, + 5: b, + 6: a, +}); diff --git a/tests/cases/fourslash/doubleUnderscoreCompletions.ts b/tests/cases/fourslash/doubleUnderscoreCompletions.ts index df36a9adc48..007842edc1b 100644 --- a/tests/cases/fourslash/doubleUnderscoreCompletions.ts +++ b/tests/cases/fourslash/doubleUnderscoreCompletions.ts @@ -8,5 +8,11 @@ //// var instance = new MyObject(); //// instance./*1*/ -goTo.marker("1"); -verify.completionListContains("__property", "(property) MyObject.__property: number"); +verify.completions({ + marker: "1", + exact: [ + { name: "__property", text: "(property) MyObject.__property: number" }, + "MyObject", + "instance", + ], +}); diff --git a/tests/cases/fourslash/exportDefaultClass.ts b/tests/cases/fourslash/exportDefaultClass.ts index 04ab351ab36..da22984757a 100644 --- a/tests/cases/fourslash/exportDefaultClass.ts +++ b/tests/cases/fourslash/exportDefaultClass.ts @@ -5,8 +5,4 @@ ////} //// /*2*/ -goTo.marker('1'); -verify.completionListContains("C", "class C", /*documentation*/ undefined, "class"); - -goTo.marker('2'); -verify.completionListContains("C", "class C", /*documentation*/ undefined, "class"); \ No newline at end of file +verify.completions({ marker: test.markers(), includes: { name: "C", text: "class C", kind: "class" } }); diff --git a/tests/cases/fourslash/exportDefaultFunction.ts b/tests/cases/fourslash/exportDefaultFunction.ts index 42ddced6994..3b7882e025d 100644 --- a/tests/cases/fourslash/exportDefaultFunction.ts +++ b/tests/cases/fourslash/exportDefaultFunction.ts @@ -5,8 +5,7 @@ ////} //// /*2*/ -goTo.marker('1'); -verify.completionListContains("func", "function func(): void", /*documentation*/ undefined, "function"); - -goTo.marker('2'); -verify.completionListContains("func", "function func(): void", /*documentation*/ undefined, "function"); +verify.completions({ + marker: test.markers(), + includes: { name: "func", text: "function func(): void", kind: "function" }, +}); diff --git a/tests/cases/fourslash/exportEqualCallableInterface.ts b/tests/cases/fourslash/exportEqualCallableInterface.ts index 795df0c8695..2b65ca69c6f 100644 --- a/tests/cases/fourslash/exportEqualCallableInterface.ts +++ b/tests/cases/fourslash/exportEqualCallableInterface.ts @@ -13,7 +13,7 @@ ////var t2: test; ////t2./**/ -goTo.marker(); -verify.completionListContains('apply'); -verify.completionListContains('arguments'); -verify.completionListContains('foo'); +verify.completions({ + marker: "", + exact: ["foo", ...completion.functionMembersWithPrototype], +}); diff --git a/tests/cases/fourslash/exportEqualTypes.ts b/tests/cases/fourslash/exportEqualTypes.ts index cb1e2ec90a1..6cb7eb9f9ae 100644 --- a/tests/cases/fourslash/exportEqualTypes.ts +++ b/tests/cases/fourslash/exportEqualTypes.ts @@ -19,6 +19,5 @@ verify.quickInfos({ 2: "var r1: Date", 3: "var r2: string" }); -goTo.marker('4'); -verify.completionListContains('foo'); +verify.completions({ marker: "4", exact: ["foo", ...completion.functionMembersWithPrototype] }); verify.noErrors(); diff --git a/tests/cases/fourslash/extendArrayInterface.ts b/tests/cases/fourslash/extendArrayInterface.ts index d2322b37df0..09add80a685 100644 --- a/tests/cases/fourslash/extendArrayInterface.ts +++ b/tests/cases/fourslash/extendArrayInterface.ts @@ -7,8 +7,7 @@ //// -goTo.marker("1"); -verify.completionListContains("concat"); +verify.completions({ marker: "1", includes: "concat" }); // foo doesn't exist, so both references should be in error verify.errorExistsBetweenMarkers("2", "3"); diff --git a/tests/cases/fourslash/externalModuleIntellisense.ts b/tests/cases/fourslash/externalModuleIntellisense.ts index 8577e0686bf..50838338037 100644 --- a/tests/cases/fourslash/externalModuleIntellisense.ts +++ b/tests/cases/fourslash/externalModuleIntellisense.ts @@ -21,6 +21,4 @@ goTo.marker('1'); verify.numberOfErrorsInCurrentFile(0); goTo.eof(); edit.insert("x."); -verify.completionListContains('enable'); -verify.completionListContains('post'); -verify.completionListCount(2); +verify.completions({ exact: ["enable", "post"] }); diff --git a/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts b/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts index a1d503a657a..79b1ce4f2e6 100644 --- a/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts +++ b/tests/cases/fourslash/externalModuleRefernceResolutionOrderInImportDeclaration.ts @@ -16,5 +16,4 @@ goTo.marker('1'); edit.insert("file1."); -verify.completionListContains("bar"); -verify.not.completionListContains("foo"); \ No newline at end of file +verify.completions({ includes: "bar", excludes: "foo" }); diff --git a/tests/cases/fourslash/externalModuleWithExportAssignment.ts b/tests/cases/fourslash/externalModuleWithExportAssignment.ts index 02f53b661d5..7131042427b 100644 --- a/tests/cases/fourslash/externalModuleWithExportAssignment.ts +++ b/tests/cases/fourslash/externalModuleWithExportAssignment.ts @@ -48,10 +48,14 @@ verify.quickInfoAt("2", [ goTo.marker('3'); verify.quickInfoIs("(property) test1: a1.connectModule\n(res: any, req: any, next: any) => void", undefined); -verify.completionListContains("test1", "(property) test1: a1.connectModule\n(res: any, req: any, next: any) => void", undefined); -verify.completionListContains("test2", "(method) test2(): a1.connectModule", undefined); -verify.not.completionListContains("connectModule"); -verify.not.completionListContains("connectExport"); +verify.completions({ + marker: ["3", "9"], + exact: [ + { name: "test1", text: "(property) test1: a1.connectModule\n(res: any, req: any, next: any) => void" }, + { name: "test2", text: "(method) test2(): a1.connectModule" }, + ...completion.functionMembersWithPrototype, + ], +}); verify.signatureHelp( { marker: "4", text: "test1(res: any, req: any, next: any): void" }, @@ -66,10 +70,6 @@ verify.quickInfoAt("8", "var r2: a1.connectExport", undefined); goTo.marker('9'); verify.quickInfoIs("(property) test1: a1.connectModule\n(res: any, req: any, next: any) => void", undefined); -verify.completionListContains("test1", "(property) test1: a1.connectModule\n(res: any, req: any, next: any) => void", undefined); -verify.completionListContains("test2", "(method) test2(): a1.connectModule", undefined); -verify.not.completionListContains("connectModule"); -verify.not.completionListContains("connectExport"); verify.signatureHelp( { marker: "10", text: "test1(res: any, req: any, next: any): void" }, @@ -82,9 +82,10 @@ verify.signatureHelp({ marker: "13", text: "a1(): a1.connectExport" }); verify.quickInfoAt("14", "var r4: a1.connectExport", undefined); -goTo.marker('15'); -verify.not.completionListContains("test1", "(property) test1: a1.connectModule", undefined); -verify.not.completionListContains("test2", "(method) test2(): a1.connectModule", undefined); -verify.completionListContains("connectModule", "interface a1.connectModule", undefined); -verify.completionListContains("connectExport", "interface a1.connectExport", undefined); - +verify.completions({ + marker: "15", + exact: [ + { name: "connectModule", text: "interface a1.connectModule" }, + { name: "connectExport", text: "interface a1.connectExport" }, + ], +}); diff --git a/tests/cases/fourslash/forwardReference.ts b/tests/cases/fourslash/forwardReference.ts index 355eda9113c..ad300bc6734 100644 --- a/tests/cases/fourslash/forwardReference.ts +++ b/tests/cases/fourslash/forwardReference.ts @@ -8,5 +8,4 @@ //// public n: number; ////} -goTo.marker(); -verify.completionListContains('n'); +verify.completions({ marker: "", exact: "n" }); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 57b5af7e1b6..dd6d5fce273 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -146,27 +146,6 @@ declare namespace FourSlashInterface { allowedClassElementKeywords: string[]; allowedConstructorParameterKeywords: string[]; constructor(negative?: boolean); - completionListCount(expectedCount: number): void; - completionListContains( - entryId: string | { name: string, source?: string }, - text?: string, - documentation?: string, - kind?: string | { kind?: string, kindModifiers?: string }, - spanIndex?: number, - hasAction?: boolean, - options?: UserPreferences & { - triggerCharacter?: string, - sourceDisplay?: string, - isRecommended?: true, - insertText?: string, - replacementSpan?: Range, - }, - ): void; - completionListItemsCountIsGreaterThan(count: number): void; - completionListIsEmpty(): void; - completionListContainsClassElementKeywords(): void; - completionListContainsConstructorParameterKeywords(): void; - completionListAllowsNewIdentifier(): void; errorExistsBetweenMarkers(startMarker: string, endMarker: string): void; errorExistsAfterMarker(markerName?: string): void; errorExistsBeforeMarker(markerName?: string): void; @@ -201,16 +180,7 @@ declare namespace FourSlashInterface { class verify extends verifyNegatable { assertHasRanges(ranges: Range[]): void; caretAtMarker(markerName?: string): void; - completions(...options: { - readonly marker?: ArrayOrSingle, - readonly isNewIdentifierLocation?: boolean; - readonly exact?: ArrayOrSingle; - readonly includes?: ArrayOrSingle; - readonly excludes?: ArrayOrSingle; - readonly preferences?: UserPreferences; - readonly triggerCharacter?: string; - }[]): void; - completionsAt(markerName: ArrayOrSingle, completions: ReadonlyArray, options?: CompletionsAtOptions): void; + completions(...options: CompletionsOptions[]): void; applyCodeActionFromCompletion(markerName: string, options: { name: string, source?: string, @@ -299,7 +269,6 @@ declare namespace FourSlashInterface { rangesAreDocumentHighlights(ranges?: Range[], options?: VerifyDocumentHighlightsOptions): void; rangesWithSameTextAreDocumentHighlights(): void; documentHighlightsOf(startRange: Range, ranges: Range[], options?: VerifyDocumentHighlightsOptions): void; - completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: JSDocTagInfo[]): void; /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ @@ -536,25 +505,33 @@ declare namespace FourSlashInterface { readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; } - interface CompletionsAtOptions extends UserPreferences { - triggerCharacter?: string; - isNewIdentifierLocation?: boolean; + interface CompletionsOptions { + readonly marker?: ArrayOrSingle, + readonly isNewIdentifierLocation?: boolean; + readonly isGlobalCompletion?: boolean; + readonly exact?: ArrayOrSingle; + readonly includes?: ArrayOrSingle; + readonly excludes?: ArrayOrSingle; + readonly preferences?: UserPreferences; + readonly triggerCharacter?: string; } - type ExpectedCompletionEntry = string | { - readonly name: string, - readonly source?: string, - readonly insertText?: string, - readonly replacementSpan?: Range, - readonly hasAction?: boolean, - readonly isRecommended?: boolean, - readonly kind?: string, + type ExpectedCompletionEntry = string | ExpectedCompletionEntryObject; + interface ExpectedCompletionEntryObject { + readonly name: string; + readonly source?: string; + readonly insertText?: string; + readonly replacementSpan?: Range; + readonly hasAction?: boolean; + readonly isRecommended?: boolean; + readonly kind?: string; + readonly kindModifiers?: string; // details - readonly text?: string, - readonly documentation?: string, + readonly text?: string; + readonly documentation?: string; readonly tags?: ReadonlyArray; - readonly sourceDisplay?: string, - }; + readonly sourceDisplay?: string; + } interface VerifySignatureHelpOptions { marker?: ArrayOrSingle; @@ -666,3 +643,24 @@ declare var debug: FourSlashInterface.debug; declare var format: FourSlashInterface.format; declare var cancellation: FourSlashInterface.cancellation; declare var classification: typeof FourSlashInterface.classification; +declare namespace completion { + export const globals: ReadonlyArray; + export const globalKeywords: ReadonlyArray; + export const insideMethodKeywords: ReadonlyArray; + export const globalKeywordsPlusUndefined: ReadonlyArray; + export const globalsVars: ReadonlyArray; + export function globalsInsideFunction(plus: ReadonlyArray): ReadonlyArray; + export function globalsPlus(plus: ReadonlyArray): ReadonlyArray; + export const keywordsWithUndefined: ReadonlyArray; + export const keywords: ReadonlyArray; + export const typeKeywords: ReadonlyArray; + export const globalTypes: ReadonlyArray; + export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray; + export const classElementKeywords: ReadonlyArray; + export const constructorParameterKeywords: ReadonlyArray; + export const functionMembers: ReadonlyArray; + export const stringMembers: ReadonlyArray; + export const functionMembersWithPrototype: ReadonlyArray; + export const statementKeywordsWithTypes: ReadonlyArray; + export const statementKeywords: ReadonlyArray; +} diff --git a/tests/cases/fourslash/functionProperty.ts b/tests/cases/fourslash/functionProperty.ts index 9ba3bce3543..07d617b8acc 100644 --- a/tests/cases/fourslash/functionProperty.ts +++ b/tests/cases/fourslash/functionProperty.ts @@ -23,17 +23,15 @@ verify.signatureHelp({ marker: ["signatureA", "signatureB", "signatureC"], text: "x(a: number): void" }); -goTo.marker('completionA'); -verify.completionListContains("x", "(method) x(a: number): void"); - -goTo.marker('completionB'); -verify.completionListContains("x", "(property) x: (a: number) => void"); - -goTo.marker('completionC'); -verify.completionListContains("x", "(property) x: (a: number) => void"); +const method = "(method) x(a: number): void"; +const property = "(property) x: (a: number) => void"; +verify.completions( + { marker: "completionA", exact: { name: "x", text: method } }, + { marker: ["completionB", "completionC"], exact: { name: "x", text: property } }, +); verify.quickInfos({ - quickInfoA: "(method) x(a: number): void", - quickInfoB: "(property) x: (a: number) => void", - quickInfoC: "(property) x: (a: number) => void" + quickInfoA: method, + quickInfoB: property, + quickInfoC: property, }); diff --git a/tests/cases/fourslash/functionTypes.ts b/tests/cases/fourslash/functionTypes.ts index 5ef931a602d..205861e43b5 100644 --- a/tests/cases/fourslash/functionTypes.ts +++ b/tests/cases/fourslash/functionTypes.ts @@ -21,10 +21,7 @@ ////l./*7*/prototype = Object.prototype; verify.noErrors(); -verify.completionsAt('1', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('2', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('3', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('4', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('5', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('6', ["apply", "call", "bind", "toString", "prototype", "length", "arguments", "caller" ]); -verify.completionsAt('7', ["prototype", "apply", "call", "bind", "toString", "length", "arguments", "caller" ]); +verify.completions( + { marker: ["1", "2", "3", "4", "5", "6"], exact: completion.functionMembersWithPrototype }, + { marker: "7", exact: ["prototype", ...completion.functionMembers] }, +); diff --git a/tests/cases/fourslash/genericCloduleCompletionList.ts b/tests/cases/fourslash/genericCloduleCompletionList.ts index 3ca9546eece..6b184e5079c 100644 --- a/tests/cases/fourslash/genericCloduleCompletionList.ts +++ b/tests/cases/fourslash/genericCloduleCompletionList.ts @@ -6,6 +6,4 @@ ////var d: D; ////d./**/ -goTo.marker(); -verify.completionListContains('x'); -verify.not.completionListContains('f'); +verify.completions({ marker: "", exact: "x" }); diff --git a/tests/cases/fourslash/genericTypeAliasIntersectionCompletions.ts b/tests/cases/fourslash/genericTypeAliasIntersectionCompletions.ts index 0b2646291da..b16e0eba5bb 100644 --- a/tests/cases/fourslash/genericTypeAliasIntersectionCompletions.ts +++ b/tests/cases/fourslash/genericTypeAliasIntersectionCompletions.ts @@ -28,6 +28,4 @@ //// var obj = new (merge(LeftSideNode, RightSideNode))(); //// obj./**/ -goTo.marker(); -verify.completionListContains("left"); -verify.completionListContains("right"); +verify.completions({ marker: "", exact: ["right", "left", "value", "constructor"] }); diff --git a/tests/cases/fourslash/genericTypeWithMultipleBases1.ts b/tests/cases/fourslash/genericTypeWithMultipleBases1.ts index 867cea490ef..32263a73fa4 100644 --- a/tests/cases/fourslash/genericTypeWithMultipleBases1.ts +++ b/tests/cases/fourslash/genericTypeWithMultipleBases1.ts @@ -12,7 +12,11 @@ ////var x: iScope; ////x./**/ -goTo.marker(); -verify.completionListContains('watch', '(property) iBaseScope.watch: () => void'); -verify.completionListContains('moveUp', '(property) iMover.moveUp: () => void'); -verify.completionListContains('family', '(property) iScope.family: number'); \ No newline at end of file +verify.completions({ + marker: "", + exact: [ + { name: "family", text: "(property) iScope.family: number" }, + { name: "watch", text: "(property) iBaseScope.watch: () => void" }, + { name: "moveUp", text: "(property) iMover.moveUp: () => void" }, + ], +}); diff --git a/tests/cases/fourslash/genericTypeWithMultipleBases1MultiFile.ts b/tests/cases/fourslash/genericTypeWithMultipleBases1MultiFile.ts index 6c15a5a5c01..e089824f53c 100644 --- a/tests/cases/fourslash/genericTypeWithMultipleBases1MultiFile.ts +++ b/tests/cases/fourslash/genericTypeWithMultipleBases1MultiFile.ts @@ -17,7 +17,11 @@ // @Filename: genericTypeWithMultipleBases_4.ts ////x./**/ -goTo.marker(); -verify.completionListContains('watch', '(property) iBaseScope.watch: () => void'); -verify.completionListContains('moveUp', '(property) iMover.moveUp: () => void'); -verify.completionListContains('family', '(property) iScope.family: number'); +verify.completions({ + marker: "", + includes: [ + { name: "watch", text: "(property) iBaseScope.watch: () => void" }, + { name: "moveUp", text: "(property) iMover.moveUp: () => void" }, + { name: "family", text: "(property) iScope.family: number" }, + ], +}); diff --git a/tests/cases/fourslash/getCompletionEntryDetails.ts b/tests/cases/fourslash/getCompletionEntryDetails.ts index 1ed680b6678..436c0d195bc 100644 --- a/tests/cases/fourslash/getCompletionEntryDetails.ts +++ b/tests/cases/fourslash/getCompletionEntryDetails.ts @@ -7,24 +7,23 @@ ////var bbb: string; /////*1*/ +const check = () => verify.completions({ + includes: [ + { name: "aaa", text: "var aaa: number" }, + { name: "bbb", text: "var bbb: string" }, + { name: "ccc", text: "var ccc: number" }, + { name: "ddd", text: "var ddd: string" }, + ], +}); + goTo.marker("1"); -verify.completionListContains("aaa"); -verify.completionListContains("bbb"); -verify.completionListContains("ccc"); -verify.completionListContains("ddd"); // Checking for completion details before edit should work -verify.completionEntryDetailIs("aaa", "var aaa: number"); -verify.completionEntryDetailIs("ccc", "var ccc: number"); +check(); // Make an edit edit.insert("a"); edit.backspace(); // Checking for completion details after edit should work too -verify.completionEntryDetailIs("bbb", "var bbb: string"); -verify.completionEntryDetailIs("ddd", "var ddd: string"); - -// Checking for completion details again before edit should work -verify.completionEntryDetailIs("aaa", "var aaa: number"); -verify.completionEntryDetailIs("ccc", "var ccc: number"); +check(); diff --git a/tests/cases/fourslash/getCompletionEntryDetails2.ts b/tests/cases/fourslash/getCompletionEntryDetails2.ts index 3e7e77b588c..ecb5e43918a 100644 --- a/tests/cases/fourslash/getCompletionEntryDetails2.ts +++ b/tests/cases/fourslash/getCompletionEntryDetails2.ts @@ -7,12 +7,16 @@ ////} ////Foo./**/ -goTo.marker(""); -verify.completionListContains("x"); +const exact: ReadonlyArray = [ + "prototype", + { name: "x", text: "var Foo.x: number" }, + ...completion.functionMembers, +]; +verify.completions({ marker: "", exact }); // Make an edit edit.insert("a"); edit.backspace(); // Checking for completion details after edit should work too -verify.completionEntryDetailIs("x", "var Foo.x: number"); +verify.completions({ exact }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions1.ts b/tests/cases/fourslash/getJavaScriptCompletions1.ts index 6d8f36aac1b..fd677b12354 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions1.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions1.ts @@ -6,5 +6,4 @@ ////var v; ////v./**/ -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions10.ts b/tests/cases/fourslash/getJavaScriptCompletions10.ts index 5fbd91e8988..0eaccdb26b9 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions10.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions10.ts @@ -7,5 +7,4 @@ //// */ ////function f() { this./**/ } -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions11.ts b/tests/cases/fourslash/getJavaScriptCompletions11.ts index f12f53fa960..9b15b09a277 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions11.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions11.ts @@ -6,6 +6,10 @@ ////var v; ////v./**/ -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); -verify.completionListContains("charCodeAt", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ + marker: "", + includes: [ + { name: "toExponential", kind: "method" }, + { name: "charCodeAt", kind: "method" }, + ], +}); diff --git a/tests/cases/fourslash/getJavaScriptCompletions14.ts b/tests/cases/fourslash/getJavaScriptCompletions14.ts index 52a23065a5e..d89d77ba0d4 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions14.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions14.ts @@ -9,5 +9,4 @@ ////var x = 1; ////x./*1*/ -goTo.marker("1"); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ marker: "1", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions15.ts b/tests/cases/fourslash/getJavaScriptCompletions15.ts index 2903cb6fa7c..e46b0780d42 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions15.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions15.ts @@ -19,11 +19,9 @@ //// v.x./*3*/; //// v.x.V./*4*/; -goTo.marker("1"); -verify.completionListContains("toExponential"); -goTo.marker("2"); -verify.completionListContains("toLowerCase"); -goTo.marker("3"); -verify.completionListContains("V"); -goTo.marker("4"); -verify.completionListContains("toLowerCase"); +verify.completions( + { marker: "1", includes: "toExponential" }, + { marker: "2", includes: "toLowerCase" }, + { marker: "3", exact: ["V", "ref1", "ref2", "require", "v", "x"] }, + { marker: "4", includes: "toLowerCase" }, +); diff --git a/tests/cases/fourslash/getJavaScriptCompletions16.ts b/tests/cases/fourslash/getJavaScriptCompletions16.ts index 86adead3e1a..8f698004eb4 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions16.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions16.ts @@ -24,7 +24,7 @@ goTo.marker('body'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); edit.backspace(); verify.signatureHelp({ @@ -35,4 +35,4 @@ verify.signatureHelp({ goTo.marker('method'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions18.ts b/tests/cases/fourslash/getJavaScriptCompletions18.ts index a30d4943f4f..bad58889efb 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions18.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions18.ts @@ -13,9 +13,8 @@ goTo.marker('a'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); - +verify.completions({ includes: { name: "toFixed", kind: "method" } }); goTo.marker('b'); edit.insert('.'); -verify.completionListContains('substr', undefined, undefined, 'method'); +verify.completions({ includes: { name: "substr", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions19.ts b/tests/cases/fourslash/getJavaScriptCompletions19.ts index 5a361930e86..0c90a32a322 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions19.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions19.ts @@ -18,8 +18,8 @@ goTo.marker('str'); edit.insert('.'); -verify.completionListContains('substr', undefined, undefined, 'method'); +verify.completions({ includes: { name: "substr", kind: "method" } }); goTo.marker('num'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions2.ts b/tests/cases/fourslash/getJavaScriptCompletions2.ts index b5aab81b434..4425e4a76e8 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions2.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions2.ts @@ -6,5 +6,4 @@ ////var v; ////v./**/ -goTo.marker(); -verify.completionListContains("valueOf", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ marker: "", includes: { name: "valueOf", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions20.ts b/tests/cases/fourslash/getJavaScriptCompletions20.ts index ec2bcef161b..cbe74a4b392 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions20.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions20.ts @@ -12,10 +12,12 @@ //// this.name = name; //// this.age = age; //// } -//// -//// +//// +//// //// Person.getName = 10; //// Person.getNa/**/ = 10; -goTo.marker(); -verify.completionListContains('getName'); +verify.completions({ + marker: "", + exact: ["getName", "getNa", ...completion.functionMembersWithPrototype, "Person", "name", "age"], +}); diff --git a/tests/cases/fourslash/getJavaScriptCompletions3.ts b/tests/cases/fourslash/getJavaScriptCompletions3.ts index 13a6f1673e6..da2a05c0cfb 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions3.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions3.ts @@ -6,5 +6,4 @@ ////var v; ////v./**/ -goTo.marker(); -verify.completionListContains("concat", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "concat", kind: "method" } }); \ No newline at end of file diff --git a/tests/cases/fourslash/getJavaScriptCompletions4.ts b/tests/cases/fourslash/getJavaScriptCompletions4.ts index 3719b8e1258..841c60d91b4 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions4.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions4.ts @@ -6,5 +6,4 @@ ////function foo(a,b) { } ////foo(1,2)./**/ -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions5.ts b/tests/cases/fourslash/getJavaScriptCompletions5.ts index 348feef94c3..85808d46626 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions5.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions5.ts @@ -7,9 +7,7 @@ //// * @param {T} a //// * @return {T} */ //// function foo(a) { } -//// let x = /*1*/foo; +//// let x = foo; //// foo(1)./**/ -goTo.marker('1'); -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions8.ts b/tests/cases/fourslash/getJavaScriptCompletions8.ts index 418aae676be..6ac9387b10c 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions8.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions8.ts @@ -8,5 +8,4 @@ ////var v; ////v()./**/ -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions9.ts b/tests/cases/fourslash/getJavaScriptCompletions9.ts index 1619a2ca9fc..de9a9c068db 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions9.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions9.ts @@ -8,5 +8,4 @@ ////var v; ////new v()./**/ -goTo.marker(); -verify.completionListContains("toExponential", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); diff --git a/tests/cases/fourslash/getJavaScriptGlobalCompletions1.ts b/tests/cases/fourslash/getJavaScriptGlobalCompletions1.ts index 240df24bf52..478d472217e 100644 --- a/tests/cases/fourslash/getJavaScriptGlobalCompletions1.ts +++ b/tests/cases/fourslash/getJavaScriptGlobalCompletions1.ts @@ -9,7 +9,7 @@ //// } //// return 5; //// } -//// +//// //// hello/**/ -verify.completionListContains('helloWorld'); +verify.completions({ includes: "helloWorld" }); diff --git a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts index 958dec3765d..9b047869896 100644 --- a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts +++ b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts @@ -21,9 +21,9 @@ goTo.marker('1'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.completionListContains('substr', undefined, undefined, 'method'); +verify.completions({ includes: { name: "substr", kind: "method" } }); diff --git a/tests/cases/fourslash/globalCompletionListInsideObjectLiterals.ts b/tests/cases/fourslash/globalCompletionListInsideObjectLiterals.ts index 33f8534344e..e41ec0a99f4 100644 --- a/tests/cases/fourslash/globalCompletionListInsideObjectLiterals.ts +++ b/tests/cases/fourslash/globalCompletionListInsideObjectLiterals.ts @@ -23,27 +23,12 @@ //// }; ////} -function VerifyGlobalCompletionList() { - verify.completionListItemsCountIsGreaterThan(10); -} - -// Completion on '{' location. -goTo.marker("1"); -VerifyGlobalCompletionList(); - -// Literal member completion after member name with empty member expression and missing colon. -goTo.marker("2"); -VerifyGlobalCompletionList(); - -goTo.marker("3"); -VerifyGlobalCompletionList(); - -goTo.marker("4"); -verify.completionListIsEmpty(); - -// Literal member completion after member name with empty member expression. -goTo.marker("5"); -VerifyGlobalCompletionList(); - -goTo.marker("6"); -VerifyGlobalCompletionList(); \ No newline at end of file +// 1: Completion on '{' location. +// 2: Literal member completion after member name with empty member expression and missing colon. +// 5, 6: Literal member completion after member name with empty member expression. +const exact = ["p1", "p2", "p3", "p4", ...completion.globalsPlus(["ObjectLiterals"])]; +verify.completions( + { marker: ["1"], exact, isNewIdentifierLocation: true }, + { marker: ["2", "3", "5", "6"], exact }, + { marker: "4", exact: undefined }, +); diff --git a/tests/cases/fourslash/identifierErrorRecovery.ts b/tests/cases/fourslash/identifierErrorRecovery.ts index cb266584b04..91210b9e089 100644 --- a/tests/cases/fourslash/identifierErrorRecovery.ts +++ b/tests/cases/fourslash/identifierErrorRecovery.ts @@ -10,5 +10,4 @@ verify.errorExistsBetweenMarkers("1", "2"); verify.errorExistsBetweenMarkers("3", "4"); verify.numberOfErrorsInCurrentFile(3); goTo.eof(); -verify.completionListContains("foo"); -verify.completionListContains("bar"); +verify.completions({ includes: ["foo", "bar"] }); diff --git a/tests/cases/fourslash/importJsNodeModule1.ts b/tests/cases/fourslash/importJsNodeModule1.ts index 2c4b6352cb0..e5177d19a88 100644 --- a/tests/cases/fourslash/importJsNodeModule1.ts +++ b/tests/cases/fourslash/importJsNodeModule1.ts @@ -11,8 +11,6 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/importJsNodeModule2.ts b/tests/cases/fourslash/importJsNodeModule2.ts index c8b7c479ddf..34ed62814ad 100644 --- a/tests/cases/fourslash/importJsNodeModule2.ts +++ b/tests/cases/fourslash/importJsNodeModule2.ts @@ -16,8 +16,11 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ + exact: [ + ...["n", "s", "b"].map(name => ({ name, kind: "property" })), + ...["x", "require"].map(name => ({ name, kind: "warning" })), + ], +}); edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/importJsNodeModule3.ts b/tests/cases/fourslash/importJsNodeModule3.ts index 46ff4d009be..761a2ef3e45 100644 --- a/tests/cases/fourslash/importJsNodeModule3.ts +++ b/tests/cases/fourslash/importJsNodeModule3.ts @@ -24,15 +24,13 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) });; edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); edit.backspace(4); edit.insert('y.'); -verify.completionListContains("toUpperCase", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toUpperCase", kind: "method" } }); edit.backspace(2); edit.insert('z('); verify.signatureHelp({ diff --git a/tests/cases/fourslash/importJsNodeModule4.ts b/tests/cases/fourslash/importJsNodeModule4.ts index 917bea35842..08e9b936985 100644 --- a/tests/cases/fourslash/importJsNodeModule4.ts +++ b/tests/cases/fourslash/importJsNodeModule4.ts @@ -12,8 +12,6 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) });; edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/importTypeMemberCompletions.ts b/tests/cases/fourslash/importTypeMemberCompletions.ts index b2bbc0e81b1..d91f2d271c2 100644 --- a/tests/cases/fourslash/importTypeMemberCompletions.ts +++ b/tests/cases/fourslash/importTypeMemberCompletions.ts @@ -40,12 +40,14 @@ // @Filename: /usage9.ts ////type H = typeof import("./equals")./*9*/ -verify.completionsAt("1", ["Foo"]); -verify.completionsAt("2", ["Bar"]); -verify.completionsAt("3", ["Baz", "a"]); -verify.completionsAt("4", ["Foo"]); -verify.completionsAt("5", ["Bar"]); -verify.completionsAt("6", ["Baz", "Bat"]); -verify.completionsAt("7", ["a"]); -verify.completionsAt("8", ["Bat"]); -verify.completionsAt("9", ["prototype", "bar"]); +verify.completions( + { marker: "1", exact: "Foo" }, + { marker: "2", exact: "Bar" }, + { marker: "3", exact: ["Baz", "a"] }, + { marker: "4", exact: "Foo" }, + { marker: "5", exact: "Bar" }, + { marker: "6", exact: ["Baz", "Bat"] }, + { marker: "7", exact: "a" }, + { marker: "8", exact: "Bat" }, + { marker: "9", exact: ["prototype", "bar"] }, +); diff --git a/tests/cases/fourslash/indirectClassInstantiation.ts b/tests/cases/fourslash/indirectClassInstantiation.ts index 819db337308..198515dd806 100644 --- a/tests/cases/fourslash/indirectClassInstantiation.ts +++ b/tests/cases/fourslash/indirectClassInstantiation.ts @@ -14,7 +14,7 @@ //// inst2.blah/*b*/; goTo.marker('a'); -verify.completionListContains('property'); +verify.completions({ exact: ["property", "TestObj", "constructor", "instance", "class2", "prototype", "blah", "inst2"] }); edit.backspace(); goTo.marker('b'); diff --git a/tests/cases/fourslash/javaScriptClass4.ts b/tests/cases/fourslash/javaScriptClass4.ts index 1148d5f320e..eae26f500cd 100644 --- a/tests/cases/fourslash/javaScriptClass4.ts +++ b/tests/cases/fourslash/javaScriptClass4.ts @@ -18,5 +18,4 @@ goTo.marker(); edit.insert('.baz.'); -verify.completionListContains("substr", /*displayText*/ undefined, /*documentation*/ undefined, "method"); - +verify.completions({ includes: { name: "substr", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModules13.ts b/tests/cases/fourslash/javaScriptModules13.ts index 5e3eead3b6c..3f462f343ee 100644 --- a/tests/cases/fourslash/javaScriptModules13.ts +++ b/tests/cases/fourslash/javaScriptModules13.ts @@ -19,10 +19,9 @@ goTo.file('consumer.js'); goTo.marker(); -verify.completionListContains('y'); -verify.not.completionListContains('invisible'); +verify.completions({ marker: "", includes: "y", excludes: "invisible" }); edit.insert('x.'); -verify.completionListContains('a', undefined, undefined, 'property'); +verify.completions({ includes: { name: "a", kind: "property" } }); edit.insert('a.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModules14.ts b/tests/cases/fourslash/javaScriptModules14.ts index 9039292d511..1b564c09636 100644 --- a/tests/cases/fourslash/javaScriptModules14.ts +++ b/tests/cases/fourslash/javaScriptModules14.ts @@ -21,8 +21,4 @@ //// var x = require('myMod'); //// /**/; -goTo.file('consumer.js'); -goTo.marker(); - -verify.completionListContains('y'); -verify.not.completionListContains('invisible'); +verify.completions({ marker: "", includes: "y", excludes: "invisible" }); diff --git a/tests/cases/fourslash/javaScriptModules15.ts b/tests/cases/fourslash/javaScriptModules15.ts index 0636f0360af..7a000c53a2c 100644 --- a/tests/cases/fourslash/javaScriptModules15.ts +++ b/tests/cases/fourslash/javaScriptModules15.ts @@ -20,8 +20,6 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ includes: ["s", "b", "n"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModules16.ts b/tests/cases/fourslash/javaScriptModules16.ts index 09a777f7d2c..715e5d84da4 100644 --- a/tests/cases/fourslash/javaScriptModules16.ts +++ b/tests/cases/fourslash/javaScriptModules16.ts @@ -15,8 +15,11 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ + exact: [ + ...["n", "s", "b"].map(name => ({ name, kind: "property" })), + ...["x", "require"].map(name => ({ name, kind: "warning" })), + ], +}); edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModules17.ts b/tests/cases/fourslash/javaScriptModules17.ts index 83ae882f323..02cddc4006f 100644 --- a/tests/cases/fourslash/javaScriptModules17.ts +++ b/tests/cases/fourslash/javaScriptModules17.ts @@ -11,8 +11,6 @@ goTo.file('consumer.js'); goTo.marker(); edit.insert('.'); -verify.completionListContains("n", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("s", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); -verify.completionListContains("b", /*displayText:*/ undefined, /*documentation*/ undefined, "property"); +verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModules18.ts b/tests/cases/fourslash/javaScriptModules18.ts index 77a751f2a9b..fa7e3489129 100644 --- a/tests/cases/fourslash/javaScriptModules18.ts +++ b/tests/cases/fourslash/javaScriptModules18.ts @@ -9,6 +9,4 @@ // @Filename: other.js //// /**/; -goTo.file('other.js'); - -verify.not.completionListContains('x'); +verify.completions({ marker: "", excludes: "x" }); diff --git a/tests/cases/fourslash/javaScriptModules19.ts b/tests/cases/fourslash/javaScriptModules19.ts index 56ee5a2a2e5..37304c4593a 100644 --- a/tests/cases/fourslash/javaScriptModules19.ts +++ b/tests/cases/fourslash/javaScriptModules19.ts @@ -17,10 +17,9 @@ goTo.file('consumer.js'); goTo.marker(); -verify.completionListContains('y'); -verify.not.completionListContains('invisible'); +verify.completions({ marker: "", includes: "y", excludes: "invisible" }); edit.insert('x.'); -verify.completionListContains('a', undefined, undefined, 'property'); +verify.completions({ includes: { name: "a", kind: "property" } }); edit.insert('a.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/javaScriptModulesWithBackticks.ts b/tests/cases/fourslash/javaScriptModulesWithBackticks.ts index b2ce64d3647..aef3a0a7e84 100644 --- a/tests/cases/fourslash/javaScriptModulesWithBackticks.ts +++ b/tests/cases/fourslash/javaScriptModulesWithBackticks.ts @@ -8,5 +8,4 @@ //// var a = require(`./a`); //// a./**/; -goTo.marker(); -verify.completionListContains("x"); +verify.completions({ marker: "", includes: "x" }); diff --git a/tests/cases/fourslash/javaScriptPrototype1.ts b/tests/cases/fourslash/javaScriptPrototype1.ts index 7eae28f9e98..e586b124e44 100644 --- a/tests/cases/fourslash/javaScriptPrototype1.ts +++ b/tests/cases/fourslash/javaScriptPrototype1.ts @@ -8,7 +8,7 @@ //// } //// myCtor.prototype.foo = function() { return 32 }; //// myCtor.prototype.bar = function() { return '' }; -//// +//// //// var m = new myCtor(10); //// m/*1*/ //// var a = m.foo; @@ -22,25 +22,22 @@ // Members of the class instance goTo.marker('1'); edit.insert('.'); -verify.completionListContains('foo', undefined, undefined, 'method'); -verify.completionListContains('bar', undefined, undefined, 'method'); +verify.completions({ includes: ["foo", "bar"].map(name => ({ name, kind: "method" })) }); edit.backspace(); // Members of a class method (1) goTo.marker('2'); edit.insert('.'); -verify.completionListContains('length', undefined, undefined, 'property'); +verify.completions({ includes: { name: "length", kind: "property" } }); edit.backspace(); // Members of the invocation of a class method (1) goTo.marker('3'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); -verify.not.completionListContains('substr', undefined, undefined, 'method'); +verify.completions({ includes: "toFixed", excludes: "substr" }); edit.backspace(); // Members of the invocation of a class method (2) goTo.marker('4'); edit.insert('.'); -verify.completionListContains('substr', undefined, undefined, 'method'); -verify.not.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: "substr", excludes: "toFixed" }); diff --git a/tests/cases/fourslash/javaScriptPrototype3.ts b/tests/cases/fourslash/javaScriptPrototype3.ts index 4a92f4226b9..627f5c39977 100644 --- a/tests/cases/fourslash/javaScriptPrototype3.ts +++ b/tests/cases/fourslash/javaScriptPrototype3.ts @@ -2,19 +2,26 @@ // Inside an inferred method body, the type of 'this' is the class type +// @noLib: true // @allowNonTsExtensions: true // @Filename: myMod.js //// function myCtor(x) { //// this.qua = 10; //// } -//// myCtor.prototype.foo = function() { return this/**/; }; +//// myCtor.prototype.foo = function() { return this./**/; }; //// myCtor.prototype.bar = function() { return '' }; -//// +//// goTo.marker(); edit.insert('.'); // Check members of the function -verify.completionListContains('foo', undefined, undefined, 'method'); -verify.completionListContains('bar', undefined, undefined, 'method'); -verify.completionListContains('qua', undefined, undefined, 'property'); +verify.completions({ + marker: "", + exact: [ + { name: "qua", kind: "property" }, + { name: "foo", kind: "method" }, + { name: "bar", kind: "method" }, + ...["myCtor", "x", "prototype"].map(name => ({ name, kind: "warning" })), + ], +}); diff --git a/tests/cases/fourslash/javaScriptPrototype4.ts b/tests/cases/fourslash/javaScriptPrototype4.ts index 81cb5fe3784..98deee4f22a 100644 --- a/tests/cases/fourslash/javaScriptPrototype4.ts +++ b/tests/cases/fourslash/javaScriptPrototype4.ts @@ -9,13 +9,11 @@ //// } //// myCtor.prototype.foo = function() { return 32 }; //// myCtor.prototype.bar = function() { return '' }; -//// +//// //// myCtor/*1*/ goTo.marker('1'); edit.insert('.'); // Check members of the function -verify.completionListContains('foo', undefined, undefined, 'warning'); -verify.completionListContains('bar', undefined, undefined, 'warning'); -verify.completionListContains('qua', undefined, undefined, 'warning'); +verify.completions({ includes: ["foo", "bar", "qua"].map(name => ({ name, kind: "warning" })) }); diff --git a/tests/cases/fourslash/javaScriptPrototype5.ts b/tests/cases/fourslash/javaScriptPrototype5.ts index a0125e47512..2473f658f5a 100644 --- a/tests/cases/fourslash/javaScriptPrototype5.ts +++ b/tests/cases/fourslash/javaScriptPrototype5.ts @@ -15,5 +15,4 @@ goTo.marker(); edit.insert('.'); // Check members of the function -verify.completionListContains('foo', undefined, undefined, 'property'); -verify.completionListContains('bar', undefined, undefined, 'property'); +verify.completions({ includes: ["foo", "bar"].map(name => ({ name, kind: "property" })) }); diff --git a/tests/cases/fourslash/javascriptModules20.ts b/tests/cases/fourslash/javascriptModules20.ts index 7ef5c73e1c3..8b8f0095959 100644 --- a/tests/cases/fourslash/javascriptModules20.ts +++ b/tests/cases/fourslash/javascriptModules20.ts @@ -9,5 +9,4 @@ //// import * as mod from "./mod" //// mod./**/ -goTo.marker(); -verify.completionListContains('a'); +verify.completions({ marker: "", exact: [{ name: "a", kind: "property" }, { name: "mod", kind: "warning" }] }); diff --git a/tests/cases/fourslash/javascriptModules21.ts b/tests/cases/fourslash/javascriptModules21.ts index 3a046515924..5a8dd6b872b 100644 --- a/tests/cases/fourslash/javascriptModules21.ts +++ b/tests/cases/fourslash/javascriptModules21.ts @@ -10,5 +10,4 @@ //// import mod from "./mod" //// mod./**/ -goTo.marker(); -verify.completionListContains('a'); +verify.completions({ marker: "", exact: [{ name: "a", kind: "property" }, { name: "mod", kind: "warning" }] }); diff --git a/tests/cases/fourslash/javascriptModules22.ts b/tests/cases/fourslash/javascriptModules22.ts index caa8c6798b1..ccc6d741c90 100644 --- a/tests/cases/fourslash/javascriptModules22.ts +++ b/tests/cases/fourslash/javascriptModules22.ts @@ -19,14 +19,13 @@ //// import def, {sausages} from "./mod2" //// a./**/ -goTo.marker(); -verify.completionListContains('toString'); +verify.completions({ marker: "", includes: "toString" }); edit.backspace(2); edit.insert("def."); -verify.completionListContains("name"); +verify.completions({ includes: "name" }); edit.insert("name;\nsausages."); -verify.completionListContains("eggs"); +verify.completions({ includes: "eggs" }); edit.insert("eggs;"); verify.noErrors(); diff --git a/tests/cases/fourslash/javascriptModules23.ts b/tests/cases/fourslash/javascriptModules23.ts index eafbea87baa..303a73444fb 100644 --- a/tests/cases/fourslash/javascriptModules23.ts +++ b/tests/cases/fourslash/javascriptModules23.ts @@ -8,5 +8,4 @@ //// import {a} from "./mod" //// a./**/ -goTo.marker(); -verify.completionListContains('toString'); +verify.completions({ marker: "", includes: "toString" }); diff --git a/tests/cases/fourslash/javascriptModules25.ts b/tests/cases/fourslash/javascriptModules25.ts index aceada8af21..ec4b41c27f4 100644 --- a/tests/cases/fourslash/javascriptModules25.ts +++ b/tests/cases/fourslash/javascriptModules25.ts @@ -9,5 +9,4 @@ //// import * as mod from "./mod" //// mod./**/ -goTo.marker(); -verify.completionListContains('a'); +verify.completions({ marker: "", includes: "a" }); diff --git a/tests/cases/fourslash/jsDocFunctionSignatures3.ts b/tests/cases/fourslash/jsDocFunctionSignatures3.ts index 87efaec3308..c519a1dcc72 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures3.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures3.ts @@ -18,15 +18,15 @@ //// otherMethod(p1) { //// p1/*2*/ //// } -//// +//// //// }; goTo.marker('1'); edit.insert('.'); -verify.completionListContains('substr', undefined, undefined, 'method'); +verify.completions({ includes: { name: "substr", kind: "method" } }); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.completionListContains('toFixed', undefined, undefined, 'method'); +verify.completions({ includes: { name: "toFixed", kind: "method" } }); edit.backspace(); diff --git a/tests/cases/fourslash/jsDocGenerics1.ts b/tests/cases/fourslash/jsDocGenerics1.ts index e5570937ba4..70e13851cf7 100644 --- a/tests/cases/fourslash/jsDocGenerics1.ts +++ b/tests/cases/fourslash/jsDocGenerics1.ts @@ -23,12 +23,4 @@ //// var x; //// x[0].a./*3*/ - -goTo.marker('1'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); - -goTo.marker('2'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); - -goTo.marker('3'); -verify.completionListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); +verify.completions({ marker: test.markers(), includes: { name: "toFixed", kind: "method" } }); diff --git a/tests/cases/fourslash/jsDocTags.ts b/tests/cases/fourslash/jsDocTags.ts index 7cb5ae7198e..ddd1c547250 100644 --- a/tests/cases/fourslash/jsDocTags.ts +++ b/tests/cases/fourslash/jsDocTags.ts @@ -76,10 +76,13 @@ verify.signatureHelp( { marker: "13", tags: [{ name: "returns", text: "a value" }] }, ); -goTo.marker('14'); -verify.completionEntryDetailIs( - "newMethod", - "(method) Foo.newMethod(): void", - "method documentation", - "method", - [{name: "mytag", text: "a JSDoc tag"}]); +verify.completions({ + marker: "14", + includes: { + name: "newMethod", + text: "(method) Foo.newMethod(): void", + documentation: "method documentation", + kind: "method", + tags: [{ name: "mytag", text: "a JSDoc tag" }], + }, +}); diff --git a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts index d6c3ca4f914..d3c4aafc938 100644 --- a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts +++ b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts @@ -11,60 +11,54 @@ //// */ //// var x; //// /** @type {/*5*/T./*2TypeMember*/O.Q.NumberLike} */ -//// var x1; +//// var x1; //// /** @type {/*6*/T./*3TypeMember*/People} */ //// var x1; //// /*globalValue*/ -interface VerifyCompletionsInJsDoc { - verifyType(symbol: string, kind: string): void; - verifyValue(symbol: string, kind: string): void; - verifyTypeMember(symbol: string, kind: string): void; +const types: ReadonlyArray = [ + { name: "T", kind: "module" }, +]; +const values: ReadonlyArray = [ + { name: "x", kind: "var" }, + { name: "x1", kind: "var" }, +]; +const typeMembers: ReadonlyArray = [ + { name: "NumberLike", kind: "type" }, + { name: "People", kind: "type" }, + { name: "O", kind: "module" }, +]; +function warnings(entries: ReadonlyArray): ReadonlyArray { + return entries.map(e => ({ ...e, kind: "warning" })); } -function verifyCompletionsInJsDocType(marker: string, { verifyType, verifyValue, verifyTypeMember }: VerifyCompletionsInJsDoc) { - goTo.marker(marker); - - verifyType("T", "module"); - - // TODO: May be filter keywords based on context - //verifyType("string", "keyword"); - //verifyType("number", "keyword"); - - verifyValue("x", "var"); - verifyValue("x1", "var"); - - verifyTypeMember("NumberLike", "type"); - verifyTypeMember("People", "type"); - verifyTypeMember("O", "module"); -} - -function verifySymbolPresentWithKind(symbol: string, kind: string) { - return verify.completionListContains(symbol, /*text*/ undefined, /*documentation*/ undefined, kind); -} - -function verifySymbolPresentWithWarning(symbol: string) { - return verifySymbolPresentWithKind(symbol, "warning"); -} - -for (let i = 1; i <= 6; i++) { - verifyCompletionsInJsDocType(i.toString(), { - verifyType: verifySymbolPresentWithKind, - verifyValue: verifySymbolPresentWithWarning, - verifyTypeMember: verifySymbolPresentWithWarning, - }); -} -verifyCompletionsInJsDocType("globalValue", { - verifyType: verifySymbolPresentWithWarning, - verifyValue: verifySymbolPresentWithKind, - verifyTypeMember: verifySymbolPresentWithWarning, -}); -for (let i = 1; i <= 3; i++) { - verifyCompletionsInJsDocType(i.toString() + "TypeMember", { - verifyType: verifySymbolPresentWithWarning, - verifyValue: verifySymbolPresentWithWarning, - verifyTypeMember: verifySymbolPresentWithKind, - }); -} -goTo.marker("propertyName"); -verify.completionListIsEmpty(); +verify.completions( + { + marker: ["1", "2", "3", "4", "5", "6"], + includes: [ + ...types, + ...warnings(values), + ...warnings(typeMembers), + ], + }, + { + marker: "globalValue", + includes: [ + ...values, + ...warnings(types), + ...warnings(typeMembers), + ], + }, + { + marker: [1, 2, 3].map(i => `${i}TypeMember`), + includes: [ + ...typeMembers, + ...warnings(types), + ...warnings(values), + ], + }, + { + marker: "propertyName", + exact: undefined, + }, +); diff --git a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion2.ts b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion2.ts index 038c5db5528..9cb94689b76 100644 --- a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion2.ts +++ b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion2.ts @@ -10,7 +10,7 @@ //// /** //// * @param {string} foo A value. //// * @returns {number} Another value -//// * @mytag +//// * @mytag //// */ //// method4(foo) { return 3; } //// } @@ -21,45 +21,21 @@ /////*globalValue*/ ////x./*valueMember*/ -interface VerifyCompletionsInJsDoc { - verifyValueOrType(symbol: string, kind: string): void; - verifyValue(symbol: string, kind: string): void; - verifyValueMember(symbol: string, kind: string): void; +function getCompletions(nonWarnings: ReadonlyArray): ReadonlyArray { + const withKinds: ReadonlyArray = [ + { name: "Foo", kind: "class" }, + { name: "x", kind: "var" }, + { name: "property1", kind: "property" }, + { name: "method3", kind: "method" }, + { name: "method4", kind: "method" }, + { name: "foo", kind: "warning" }, + ]; + for (const name of nonWarnings) ts.Debug.assert(withKinds.some(entry => entry.name === name)); + return withKinds.map(entry => nonWarnings.includes(entry.name) ? entry : ({ name: entry.name, kind: "warning" })); } -function verifyCompletionsInJsDocType(marker: string, { verifyValueOrType, verifyValue, verifyValueMember }: VerifyCompletionsInJsDoc) { - goTo.marker(marker); - - verifyValueOrType("Foo", "class"); - - verifyValue("x", "var"); - - verifyValueMember("property1", "property"); - verifyValueMember("method3", "method"); - verifyValueMember("method4", "method"); - verifyValueMember("foo", "warning"); -} - -function verifySymbolPresentWithKind(symbol: string, kind: string) { - return verify.completionListContains(symbol, /*text*/ undefined, /*documentation*/ undefined, kind); -} - -function verifySymbolPresentWithWarning(symbol: string) { - return verifySymbolPresentWithKind(symbol, "warning"); -} - -verifyCompletionsInJsDocType("type", { - verifyValueOrType: verifySymbolPresentWithKind, - verifyValue: verifySymbolPresentWithWarning, - verifyValueMember: verifySymbolPresentWithWarning, -}); -verifyCompletionsInJsDocType("globalValue", { - verifyValueOrType: verifySymbolPresentWithKind, - verifyValue: verifySymbolPresentWithKind, - verifyValueMember: verifySymbolPresentWithWarning, -}); -verifyCompletionsInJsDocType("valueMember", { - verifyValueOrType: verifySymbolPresentWithWarning, - verifyValue: verifySymbolPresentWithWarning, - verifyValueMember: verifySymbolPresentWithKind, -}); +verify.completions( + { marker: "type", includes: getCompletions(["Foo"]) }, + { marker: "globalValue", includes: getCompletions(["Foo", "x"]) }, + { marker: "valueMember", includes: getCompletions(["property1", "method3", "method4", "foo"]) }, +); diff --git a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts index 66c3856d0b7..0c939191808 100644 --- a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts +++ b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts @@ -13,7 +13,7 @@ //// /** //// * @param {string} foo A value. //// * @returns {number} Another value -//// * @mytag +//// * @mytag //// */ //// method4(foo) { return 3; } //// } @@ -30,98 +30,63 @@ ////x1./*valueMemberOfFooInstance*/; ////Foo./*valueMemberOfFoo*/; -function verifySymbolPresentWithKind(symbol: string, kind: string) { - return verify.completionListContains(symbol, /*text*/ undefined, /*documentation*/ undefined, kind); -} +const warnings = (names: ReadonlyArray): ReadonlyArray => + names.map(name => ({ name, kind: "warning" })); -function verifySymbolPresentWithWarning(symbol: string) { - return verifySymbolPresentWithKind(symbol, "warning"); -} - -for (const marker of ["type1", "type2"]) { - goTo.marker(marker); - verifySymbolPresentWithKind("Foo", "class"); - - verifySymbolPresentWithWarning("Namespace"); - verifySymbolPresentWithWarning("SomeType"); - - verifySymbolPresentWithWarning("x"); - verifySymbolPresentWithWarning("x1"); - verifySymbolPresentWithWarning("method1"); - verifySymbolPresentWithWarning("property1"); - verifySymbolPresentWithWarning("method3"); - verifySymbolPresentWithWarning("method4"); - verifySymbolPresentWithWarning("foo"); -} - -goTo.marker("typeFooMember"); -verifySymbolPresentWithWarning("Foo"); -verifySymbolPresentWithKind("Namespace", "module"); -verifySymbolPresentWithWarning("SomeType"); -verifySymbolPresentWithWarning("x"); -verifySymbolPresentWithWarning("x1"); -verifySymbolPresentWithWarning("method1"); -verifySymbolPresentWithWarning("property1"); -verifySymbolPresentWithWarning("method3"); -verifySymbolPresentWithWarning("method4"); -verifySymbolPresentWithWarning("foo"); - -goTo.marker("NamespaceMember"); -verifySymbolPresentWithWarning("Foo"); -verifySymbolPresentWithWarning("Namespace"); -verifySymbolPresentWithKind("SomeType", "type"); -verifySymbolPresentWithWarning("x"); -verifySymbolPresentWithWarning("x1"); -verifySymbolPresentWithWarning("method1"); -verifySymbolPresentWithWarning("property1"); -verifySymbolPresentWithWarning("method3"); -verifySymbolPresentWithWarning("method4"); -verifySymbolPresentWithWarning("foo"); - -goTo.marker("globalValue"); -verifySymbolPresentWithKind("Foo", "class"); -verifySymbolPresentWithWarning("Namespace"); -verifySymbolPresentWithWarning("SomeType"); -verifySymbolPresentWithKind("x", "var"); -verifySymbolPresentWithKind("x1", "var"); -verifySymbolPresentWithWarning("method1"); -verifySymbolPresentWithWarning("property1"); -verifySymbolPresentWithWarning("method3"); -verifySymbolPresentWithWarning("method4"); -verifySymbolPresentWithWarning("foo"); - -goTo.marker("valueMemberOfSomeType"); -verifySymbolPresentWithWarning("Foo"); -verifySymbolPresentWithWarning("Namespace"); -verifySymbolPresentWithWarning("SomeType"); -verifySymbolPresentWithWarning("x"); -verifySymbolPresentWithWarning("x1"); -verifySymbolPresentWithWarning("method1"); -verifySymbolPresentWithWarning("property1"); -verifySymbolPresentWithWarning("method3"); -verifySymbolPresentWithWarning("method4"); -verifySymbolPresentWithWarning("foo"); - -goTo.marker("valueMemberOfFooInstance"); -verifySymbolPresentWithWarning("Foo"); -verifySymbolPresentWithWarning("Namespace"); -verifySymbolPresentWithWarning("SomeType"); -verifySymbolPresentWithWarning("x"); -verifySymbolPresentWithWarning("x1"); -verifySymbolPresentWithWarning("method1"); -verifySymbolPresentWithKind("property1", "property"); -verifySymbolPresentWithKind("method3", "method"); -verifySymbolPresentWithKind("method4", "method"); -verifySymbolPresentWithKind("foo", "warning"); - -goTo.marker("valueMemberOfFoo"); -verifySymbolPresentWithWarning("Foo"); -verifySymbolPresentWithWarning("Namespace"); -verifySymbolPresentWithWarning("SomeType"); -verifySymbolPresentWithWarning("x"); -verifySymbolPresentWithWarning("x1"); -verifySymbolPresentWithKind("method1", "method"); -verifySymbolPresentWithWarning("property1"); -verifySymbolPresentWithWarning("method3"); -verifySymbolPresentWithWarning("method4"); -verifySymbolPresentWithWarning("foo"); \ No newline at end of file +verify.completions( + { + marker: ["type1", "type2"], + includes: [ + { name: "Foo", kind: "class" }, + ...warnings(["Namespace", "SomeType", "x", "x1", "method1", "property1", "method3", "method4", "foo"]), + ], + }, + { + marker: "typeFooMember", + exact: [ + { name: "Namespace", kind: "module" }, + ...warnings(["Foo", "value", "property1", "method1", "method3", "method4", "foo", "age", "SomeType", "x", "x1"]), + ], + }, + { + marker: "NamespaceMember", + exact: [ + { name: "SomeType", kind: "type" }, + ...warnings(["Foo", "value", "property1", "method1", "method3", "method4", "foo", "age", "Namespace", "x", "x1"]), + ], + }, + { + marker: "globalValue", + includes: [ + { name: "Foo", kind: "class" }, + { name: "x", kind: "var" }, + { name: "x1", kind: "var" }, + ...warnings(["Namespace", "SomeType", "method1", "property1", "method3", "method4", "foo"]), + ], + }, + { + marker: "valueMemberOfSomeType", + exact: [ + { name: "age", kind: "property" }, + ...warnings(["Foo", "value", "property1", "method1", "method3", "method4", "foo", "Namespace", "SomeType", "x", "x1"]), + ], + }, + { + marker: "valueMemberOfFooInstance", + exact: [ + { name: "property1", kind: "property" }, + { name: "method3", kind: "method" }, + { name: "method4", kind: "method" }, + ...warnings(["Foo", "value", "method1", "foo", "age", "Namespace", "SomeType", "x", "x1"]), + ], + }, + { + marker: "valueMemberOfFoo", + exact: [ + { name: "prototype", kind: "property" }, + { name: "method1", kind: "method" }, + ...completion.functionMembers, + ...warnings(["Foo", "value", "property1", "method3", "method4", "foo", "age", "Namespace", "SomeType", "x", "x1"]), + ], + }, +); diff --git a/tests/cases/fourslash/jsdocNullableUnion.ts b/tests/cases/fourslash/jsdocNullableUnion.ts index 50b929b1912..f8c4e13a8ce 100644 --- a/tests/cases/fourslash/jsdocNullableUnion.ts +++ b/tests/cases/fourslash/jsdocNullableUnion.ts @@ -1,23 +1,21 @@ /// // @allowNonTsExtensions: true +// @checkJs: true // @Filename: Foo.js -//// +/////** //// * @param {never | {x: string}} p1 //// * @param {undefined | {y: number}} p2 //// * @param {null | {z: boolean}} p3 //// * @returns {void} nothing //// */ ////function f(p1, p2, p3) { -//// p1./*1*/ -//// p2./*2*/ -//// p3./*3*/ +//// p1./*1*/; +//// p2./*2*/; +//// p3./*3*/; ////} -goTo.marker('1'); -verify.completionListContains("x"); - -goTo.marker('2'); -verify.completionListContains("y"); - -goTo.marker('3'); -verify.completionListContains("z"); +verify.completions( + { marker: "1", exact: "x" }, + { marker: "2", exact: "y" }, + { marker: "3", exact: "z" }, +); diff --git a/tests/cases/fourslash/jsdocParameterNameCompletion.ts b/tests/cases/fourslash/jsdocParameterNameCompletion.ts index b379cb77135..05aa388009b 100644 --- a/tests/cases/fourslash/jsdocParameterNameCompletion.ts +++ b/tests/cases/fourslash/jsdocParameterNameCompletion.ts @@ -22,8 +22,8 @@ //// */ ////function i(foo, bar) {} -verify.completionsAt("0", ["foo", "bar"]); -verify.completionsAt("1", ["bar"]); -verify.completionsAt("2", ["canary", "canoodle"]); -verify.completionsAt("3", ["foo", "bar"]); -verify.completionsAt("4", ["foo", "bar"]); +verify.completions( + { marker: ["0", "3", "4"], exact: ["foo", "bar"] }, + { marker: "1", exact: "bar" }, + { marker: "2", exact: ["canary", "canoodle"] }, +); diff --git a/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts b/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts index b7a2b7d8993..21cea81e57b 100644 --- a/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts +++ b/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts @@ -30,111 +30,53 @@ //// */ ////var y; -function verifySymbolPresentWithKind(symbol: string, kind: string) { - return verify.completionListContains(symbol, /*text*/ undefined, /*documentation*/ undefined, kind); -} - -function verifySymbolNotPresent(symbol: string) { - return verify.not.completionListContains(symbol); -} - -goTo.marker("type1"); -verifySymbolPresentWithKind("Foo", "class"); -verifySymbolPresentWithKind("I", "interface"); -verifySymbolNotPresent("Namespace"); -verifySymbolNotPresent("SomeType"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolNotPresent("method1"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("typeFooMember"); -verifySymbolNotPresent("Foo"); -verifySymbolNotPresent("I"); -verifySymbolPresentWithKind("Namespace", "module"); -verifySymbolNotPresent("SomeType"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolNotPresent("method1"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("NamespaceMember"); -verifySymbolNotPresent("Foo"); -verifySymbolNotPresent("I"); -verifySymbolNotPresent("Namespace"); -verifySymbolPresentWithKind("SomeType", "interface"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolNotPresent("method1"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("globalValue"); -verifySymbolPresentWithKind("Foo", "class"); -verifySymbolNotPresent("I"); -verifySymbolNotPresent("Namespace"); -verifySymbolNotPresent("SomeType"); -verifySymbolPresentWithKind("x", "var"); -verifySymbolPresentWithKind("x1", "var"); -verifySymbolPresentWithKind("y", "var"); -verifySymbolNotPresent("method1"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("valueMemberOfSomeType"); -verifySymbolNotPresent("Foo"); -verifySymbolNotPresent("I"); -verifySymbolNotPresent("Namespace"); -verifySymbolNotPresent("SomeType"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolNotPresent("method1"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("valueMemberOfFooInstance"); -verifySymbolNotPresent("Foo"); -verifySymbolNotPresent("I"); -verifySymbolNotPresent("Namespace"); -verifySymbolNotPresent("SomeType"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolNotPresent("method1"); -verifySymbolPresentWithKind("property1", "property"); -verifySymbolPresentWithKind("method3", "method"); -verifySymbolPresentWithKind("method4", "method"); -verifySymbolNotPresent("foo"); - -goTo.marker("valueMemberOfFoo"); -verifySymbolNotPresent("Foo"); -verifySymbolNotPresent("I"); -verifySymbolNotPresent("Namespace"); -verifySymbolNotPresent("SomeType"); -verifySymbolNotPresent("x"); -verifySymbolNotPresent("x1"); -verifySymbolNotPresent("y"); -verifySymbolPresentWithKind("method1", "method"); -verifySymbolNotPresent("property1"); -verifySymbolNotPresent("method3"); -verifySymbolNotPresent("method4"); -verifySymbolNotPresent("foo"); - -goTo.marker("propertyName"); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions( + { + marker: "type1", + includes: [ + { name: "Foo", kind: "class" }, + { name: "I", kind: "interface" }, + ], + excludes: ["Namespace", "SomeType", "x", "x1", "y", "method1", "property1", "method3", "method4", "foo"], + }, + { + marker: "typeFooMember", + exact: { name: "Namespace", kind: "module" }, + }, + { + marker: "NamespaceMember", + exact: { name: "SomeType", kind: "interface" }, + }, + { + marker: "globalValue", + includes: [ + { name: "Foo", kind: "class" }, + { name: "x", kind: "var" }, + { name: "x1", kind: "var" }, + { name: "y", kind: "var" }, + ], + excludes: ["I", "Namespace", "SomeType", "method1", "property1", "method3", "method4", "foo"], + }, + // This is TypeScript code, so the @type tag doesn't change the type of `x`. + { marker: "valueMemberOfSomeType", exact: undefined }, + { + marker: "valueMemberOfFooInstance", + exact: [ + { name: "property1", kind: "property" }, + { name: "method3", kind: "method" }, + { name: "method4", kind: "method" }, + ], + }, + { + marker: "valueMemberOfFoo", + exact: [ + "prototype", + { name: "method1", kind: "method" }, + ...completion.functionMembers, + ], + }, + { + marker: "propertyName", + exact: undefined, + }, +); diff --git a/tests/cases/fourslash/lambdaThisMembers.ts b/tests/cases/fourslash/lambdaThisMembers.ts index 1a5aa112a6c..d0936b62403 100644 --- a/tests/cases/fourslash/lambdaThisMembers.ts +++ b/tests/cases/fourslash/lambdaThisMembers.ts @@ -9,8 +9,4 @@ //// } //// } -goTo.marker(); -verify.completionListContains("a"); -verify.completionListContains("b"); -verify.completionListCount(2); - +verify.completions({ marker: "", exact: ["a", "b"] }); diff --git a/tests/cases/fourslash/letQuickInfoAndCompletionList.ts b/tests/cases/fourslash/letQuickInfoAndCompletionList.ts index 5f9764b9357..66a5d95439a 100644 --- a/tests/cases/fourslash/letQuickInfoAndCompletionList.ts +++ b/tests/cases/fourslash/letQuickInfoAndCompletionList.ts @@ -7,20 +7,21 @@ //// /*4*/b = /*5*/a; ////} -verify.quickInfoAt("1", "let a: number"); +const a = "let a: number"; +const b = "let b: number"; +const completionA: FourSlashInterface.ExpectedCompletionEntry = { name: "a", text: a }; +const completionB: FourSlashInterface.ExpectedCompletionEntry = { name: "b", text: b }; -goTo.marker('2'); -verify.completionListContains("a", "let a: number"); -verify.quickInfoIs("let a: number"); +verify.completions( + { marker: "2", includes: completionA }, + { marker: "4", includes: [completionA, completionB] }, + { marker: "5", includes: [completionA, completionB], isNewIdentifierLocation: true }, +); -verify.quickInfoAt("3", "let b: number"); - -goTo.marker('4'); -verify.completionListContains("a", "let a: number"); -verify.completionListContains("b", "let b: number"); -verify.quickInfoIs("let b: number"); - -goTo.marker('5'); -verify.completionListContains("a", "let a: number"); -verify.completionListContains("b", "let b: number"); -verify.quickInfoIs("let a: number"); +verify.quickInfos({ + 1: a, + 2: a, + 3: b, + 4: b, + 5: a, +}); diff --git a/tests/cases/fourslash/memberCompletionFromFunctionCall.ts b/tests/cases/fourslash/memberCompletionFromFunctionCall.ts index 9bd59e1dc9f..d55d0d99034 100644 --- a/tests/cases/fourslash/memberCompletionFromFunctionCall.ts +++ b/tests/cases/fourslash/memberCompletionFromFunctionCall.ts @@ -8,5 +8,4 @@ goTo.marker(); edit.insert("."); -verify.not.completionListIsEmpty(); -verify.completionListContains("text"); \ No newline at end of file +verify.completions({ exact: "text" }); diff --git a/tests/cases/fourslash/memberCompletionInForEach1.ts b/tests/cases/fourslash/memberCompletionInForEach1.ts index b90da43c119..f26a5e409ba 100644 --- a/tests/cases/fourslash/memberCompletionInForEach1.ts +++ b/tests/cases/fourslash/memberCompletionInForEach1.ts @@ -6,11 +6,9 @@ goTo.marker('1'); edit.insert('.'); -verify.completionListContains('trim'); -verify.completionListCount(21); +verify.completions({ exact: completion.stringMembers }); edit.insert('});'); // need the following lines to not have parse errors in order for completion list to appear goTo.marker('2'); edit.insert('.'); -verify.completionListContains('trim'); -verify.completionListCount(21); +verify.completions({ exact: completion.stringMembers }); diff --git a/tests/cases/fourslash/memberCompletionOnRightSideOfImport.ts b/tests/cases/fourslash/memberCompletionOnRightSideOfImport.ts index 223995ebb0c..98546eee3d3 100644 --- a/tests/cases/fourslash/memberCompletionOnRightSideOfImport.ts +++ b/tests/cases/fourslash/memberCompletionOnRightSideOfImport.ts @@ -2,5 +2,4 @@ ////import x = M./**/ -goTo.marker(""); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts b/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts index f77a8b0c612..84fa058086c 100644 --- a/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts +++ b/tests/cases/fourslash/memberCompletionOnTypeParameters2.ts @@ -15,7 +15,4 @@ //// y = this.x./**/ // completion list here ////} - -goTo.marker(); -verify.completionListContains("foo"); -verify.completionListCount(1); +verify.completions({ marker: "", exact: "foo" }); diff --git a/tests/cases/fourslash/memberListAfterDoubleDot.ts b/tests/cases/fourslash/memberListAfterDoubleDot.ts index 489e7c3b105..1da99ddaa07 100644 --- a/tests/cases/fourslash/memberListAfterDoubleDot.ts +++ b/tests/cases/fourslash/memberListAfterDoubleDot.ts @@ -2,5 +2,4 @@ ////../**/ -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/memberListAfterSingleDot.ts b/tests/cases/fourslash/memberListAfterSingleDot.ts index ba0cdb1a1eb..1b4957ecfbb 100644 --- a/tests/cases/fourslash/memberListAfterSingleDot.ts +++ b/tests/cases/fourslash/memberListAfterSingleDot.ts @@ -2,5 +2,4 @@ ////./**/ -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/memberListErrorRecovery.ts b/tests/cases/fourslash/memberListErrorRecovery.ts index ee1fdf9193c..a7414b4769e 100644 --- a/tests/cases/fourslash/memberListErrorRecovery.ts +++ b/tests/cases/fourslash/memberListErrorRecovery.ts @@ -5,6 +5,4 @@ ////Foo./**/; /////*1*/var bar; -goTo.marker(); -verify.completionListContains("fun"); -verify.not.errorExistsAfterMarker("1"); \ No newline at end of file +verify.completions({ marker: "", includes: "fun" }); diff --git a/tests/cases/fourslash/memberListInFunctionCall.ts b/tests/cases/fourslash/memberListInFunctionCall.ts index 82e05bc4a00..67ff7ad0f8f 100644 --- a/tests/cases/fourslash/memberListInFunctionCall.ts +++ b/tests/cases/fourslash/memberListInFunctionCall.ts @@ -10,6 +10,5 @@ goTo.marker(); edit.insert('.'); - -verify.completionListContains('charAt'); +verify.completions({ includes: "charAt" }); diff --git a/tests/cases/fourslash/memberListInReopenedEnum.ts b/tests/cases/fourslash/memberListInReopenedEnum.ts index a03ee39041c..70dae89b782 100644 --- a/tests/cases/fourslash/memberListInReopenedEnum.ts +++ b/tests/cases/fourslash/memberListInReopenedEnum.ts @@ -10,9 +10,12 @@ //// var x = E./*1*/ ////} - -goTo.marker('1'); -verify.completionListContains('A', '(enum member) E.A = 0'); -verify.completionListContains('B', '(enum member) E.B = 1'); -verify.completionListContains('C', '(enum member) E.C = 0'); -verify.completionListContains('D', '(enum member) E.D = 1'); \ No newline at end of file +verify.completions({ + marker: "1", + exact: [ + { name: "A", text: "(enum member) E.A = 0" }, + { name: "B", text: "(enum member) E.B = 1" }, + { name: "C", text: "(enum member) E.C = 0" }, + { name: "D", text: "(enum member) E.D = 1" }, + ], +}); diff --git a/tests/cases/fourslash/memberListInWithBlock.ts b/tests/cases/fourslash/memberListInWithBlock.ts index 5253e924ff3..889c2cdcab5 100644 --- a/tests/cases/fourslash/memberListInWithBlock.ts +++ b/tests/cases/fourslash/memberListInWithBlock.ts @@ -11,14 +11,8 @@ //// } ////} -goTo.marker('1'); -verify.completionListIsEmpty(); - -goTo.marker('2'); -// Only keywords should show in completion, no members or types -verify.not.completionListContains("foo"); -verify.not.completionListContains("f"); -verify.not.completionListContains("c"); -verify.not.completionListContains("d"); -verify.not.completionListContains("x"); -verify.not.completionListContains("Object"); +verify.completions( + { marker: "1", exact: undefined }, + // Only keywords should show in completion, no members or types + { marker: "2", excludes: ["foo", "f", "c", "d", "x", "Object"] }, +); diff --git a/tests/cases/fourslash/memberListInWithBlock2.ts b/tests/cases/fourslash/memberListInWithBlock2.ts index 534cd12a416..07dfd49855e 100644 --- a/tests/cases/fourslash/memberListInWithBlock2.ts +++ b/tests/cases/fourslash/memberListInWithBlock2.ts @@ -5,8 +5,7 @@ ////} //// ////with (x) { -//// var y: IFoo = { /*1*/ }; +//// var y: IFoo = { /*1*/ }; ////} -goTo.marker('1'); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "1", exact: undefined }); diff --git a/tests/cases/fourslash/memberListInWithBlock3.ts b/tests/cases/fourslash/memberListInWithBlock3.ts index b30ceed9897..5495b8f4c0d 100644 --- a/tests/cases/fourslash/memberListInWithBlock3.ts +++ b/tests/cases/fourslash/memberListInWithBlock3.ts @@ -3,5 +3,4 @@ ////var x = { a: 0 }; ////with(x./*1*/ -goTo.marker('1'); -verify.completionListContains("a"); +verify.completions({ marker: "1", exact: "a" }); diff --git a/tests/cases/fourslash/memberListOfClass.ts b/tests/cases/fourslash/memberListOfClass.ts index 3355109e4a7..fcc01c604ca 100644 --- a/tests/cases/fourslash/memberListOfClass.ts +++ b/tests/cases/fourslash/memberListOfClass.ts @@ -9,7 +9,10 @@ ////var f = new C1(); ////f./**/ -goTo.marker(); -verify.completionListCount(2); -verify.completionListContains('pubMeth', '(method) C1.pubMeth(): void'); -verify.completionListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file +verify.completions({ + marker: "", + exact: [ + { name: "pubMeth", text: "(method) C1.pubMeth(): void" }, + { name: "pubProp", text: "(property) C1.pubProp: number" }, + ], +}); diff --git a/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts b/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts index 5caaf5d9c23..e114d3a2143 100644 --- a/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts +++ b/tests/cases/fourslash/memberListOfEnumFromExternalModule.ts @@ -8,6 +8,4 @@ ////import t = require('./memberListOfEnumFromExternalModule_file0'); ////var topic = t.Topic./*1*/ -goTo.file("memberListOfEnumFromExternalModule_file1.ts"); -goTo.marker('1'); -verify.completionListContains("One"); \ No newline at end of file +verify.completions({ marker: "1", exact: ["One", "Two"] }); diff --git a/tests/cases/fourslash/memberListOfEnumInModule.ts b/tests/cases/fourslash/memberListOfEnumInModule.ts index 0a3887e3304..6f4fe6ef239 100644 --- a/tests/cases/fourslash/memberListOfEnumInModule.ts +++ b/tests/cases/fourslash/memberListOfEnumInModule.ts @@ -8,6 +8,4 @@ //// var f: Foo = Foo./**/; ////} -goTo.marker(); -verify.completionListContains("bar"); -verify.completionListContains("baz"); \ No newline at end of file +verify.completions({ marker: "", exact: ["bar", "baz"] }); diff --git a/tests/cases/fourslash/memberListOfExportedClass.ts b/tests/cases/fourslash/memberListOfExportedClass.ts index 3c9fe36358b..a84c22e85aa 100644 --- a/tests/cases/fourslash/memberListOfExportedClass.ts +++ b/tests/cases/fourslash/memberListOfExportedClass.ts @@ -10,6 +10,4 @@ //// ////c./**/ // test on c. -goTo.marker(); -verify.completionListCount(1); -verify.completionListContains('pub', '(property) M.C.pub: number'); \ No newline at end of file +verify.completions({ marker: "", exact: { name: "pub", text: "(property) M.C.pub: number" } }); diff --git a/tests/cases/fourslash/memberListOfModule.ts b/tests/cases/fourslash/memberListOfModule.ts index 0e095c94cbd..3dac514dda5 100644 --- a/tests/cases/fourslash/memberListOfModule.ts +++ b/tests/cases/fourslash/memberListOfModule.ts @@ -13,7 +13,4 @@ //// ////var x: Foo./**/ -goTo.marker(); -verify.completionListCount(1); -verify.completionListContains('Bar'); -verify.not.completionListContains('Blah'); \ No newline at end of file +verify.completions({ marker: "", exact: "Bar" }); diff --git a/tests/cases/fourslash/memberListOfModuleAfterInvalidCharater.ts b/tests/cases/fourslash/memberListOfModuleAfterInvalidCharater.ts index 76ffa87dd4f..98e39c8a141 100644 --- a/tests/cases/fourslash/memberListOfModuleAfterInvalidCharater.ts +++ b/tests/cases/fourslash/memberListOfModuleAfterInvalidCharater.ts @@ -6,5 +6,4 @@ ////@ ////testModule./**/ -goTo.marker(); -verify.completionListContains('foo', 'var testModule.foo: number'); +verify.completions({ marker: "", exact: { name: "foo", text: "var testModule.foo: number" } }); diff --git a/tests/cases/fourslash/memberListOfModuleBeforeKeyword.ts b/tests/cases/fourslash/memberListOfModuleBeforeKeyword.ts index 0ea07e87a0a..1f7e2ab5e24 100644 --- a/tests/cases/fourslash/memberListOfModuleBeforeKeyword.ts +++ b/tests/cases/fourslash/memberListOfModuleBeforeKeyword.ts @@ -9,16 +9,12 @@ //// export class Test3 {} ////} //// -////TypeModule1./*dotedExpression*/ +////TypeModule1./*dottedExpression*/ ////module TypeModule3 { //// export class Test3 {} ////} // Verify the memberlist of module when the following line has a keyword -goTo.marker('namedType'); -verify.completionListContains('C1'); -verify.completionListContains('C2'); - -goTo.marker('dotedExpression'); -verify.completionListContains('C1'); -verify.completionListContains('C2'); \ No newline at end of file +verify.completions( + { marker: test.markers(), exact: ["C1", "C2"] }, +); diff --git a/tests/cases/fourslash/memberListOfModuleInAnotherModule.ts b/tests/cases/fourslash/memberListOfModuleInAnotherModule.ts index d8b90a3c219..0fd2d196315 100644 --- a/tests/cases/fourslash/memberListOfModuleInAnotherModule.ts +++ b/tests/cases/fourslash/memberListOfModuleInAnotherModule.ts @@ -20,18 +20,14 @@ //// iMod1./*3*/iMex = 1; ////} -goTo.marker('1'); -verify.completionListContains('meX', 'var mod1.meX: number'); -verify.completionListContains('meFunc', 'function mod1.meFunc(): void'); -verify.completionListContains('meClass', 'class mod1.meClass'); -verify.completionListContains('meMod', 'namespace mod1.meMod'); -verify.completionListContains('meInt', 'interface mod1.meInt'); - -goTo.marker('2'); -verify.completionListContains('meX', 'var mod1.meX: number'); -verify.completionListContains('meFunc', 'function mod1.meFunc(): void'); -verify.completionListContains('meClass', 'class mod1.meClass'); -verify.completionListContains('meMod', 'namespace mod1.meMod'); - -goTo.marker('3'); -verify.completionListContains('iMex', 'var mod1.meMod.iMex: number'); +const values: ReadonlyArray = [ + { name: "meFunc", text: "function mod1.meFunc(): void" }, + { name: "meX", text: "var mod1.meX: number" }, + { name: "meClass", text: "class mod1.meClass" }, + { name: "meMod", text: "namespace mod1.meMod" }, +]; +verify.completions( + { marker: "1", exact: [...values, { name: "meInt", text: "interface mod1.meInt" }] }, + { marker: "2", exact: values }, + { marker: "3", exact: { name: "iMex", text: "var mod1.meMod.iMex: number" } }, +); diff --git a/tests/cases/fourslash/memberListOfVarInArrowExpression.ts b/tests/cases/fourslash/memberListOfVarInArrowExpression.ts index b1a91ae3cb2..f146a86332d 100644 --- a/tests/cases/fourslash/memberListOfVarInArrowExpression.ts +++ b/tests/cases/fourslash/memberListOfVarInArrowExpression.ts @@ -13,6 +13,5 @@ ////}); ////function each(items: T[], handler: (item: T) => void) { } -goTo.marker('1'); -verify.quickInfoIs("(property) a1: string"); -verify.completionListContains("a1", "(property) a1: string"); \ No newline at end of file +verify.quickInfoAt("1", "(property) a1: string"); +verify.completions({ marker: "1", exact: { name: "a1", text: "(property) a1: string" } }); diff --git a/tests/cases/fourslash/memberListOnConstructorType.ts b/tests/cases/fourslash/memberListOnConstructorType.ts index 3d5596f2e58..336814aca41 100644 --- a/tests/cases/fourslash/memberListOnConstructorType.ts +++ b/tests/cases/fourslash/memberListOnConstructorType.ts @@ -3,6 +3,4 @@ ////var f: new () => void; ////f./*1*/ -goTo.marker('1'); -verify.completionListContains('apply'); -verify.completionListContains('arguments'); \ No newline at end of file +verify.completions({ marker: "1", exact: completion.functionMembersWithPrototype }); diff --git a/tests/cases/fourslash/memberListOnContextualThis.ts b/tests/cases/fourslash/memberListOnContextualThis.ts index e17600cad98..d35f49e2c68 100644 --- a/tests/cases/fourslash/memberListOnContextualThis.ts +++ b/tests/cases/fourslash/memberListOnContextualThis.ts @@ -5,8 +5,5 @@ ////declare function ctx(callback: (this: A) => string): string; ////ctx(function () { return th/*1*/is./*2*/a }); -goTo.marker('1'); -verify.quickInfoIs("this: A"); -goTo.marker('2'); -verify.completionListContains('a', '(property) A.a: string'); - +verify.quickInfoAt("1", "this: A"); +verify.completions({ marker: "2", exact: { name: "a", text: "(property) A.a: string" } }); diff --git a/tests/cases/fourslash/memberListOnExplicitThis.ts b/tests/cases/fourslash/memberListOnExplicitThis.ts index 425eb17f8ba..b437e3c70a6 100644 --- a/tests/cases/fourslash/memberListOnExplicitThis.ts +++ b/tests/cases/fourslash/memberListOnExplicitThis.ts @@ -12,18 +12,19 @@ ////function f(this: void) {this./*3*/} ////function g(this: Restricted) {this./*4*/} -goTo.marker('1'); -verify.completionListContains('f', '(method) C1.f(this: this): void'); -verify.completionListContains('g', '(method) C1.g(this: Restricted): void'); -verify.completionListContains('n', '(property) C1.n: number'); -verify.completionListContains('m', '(property) C1.m: number'); - -goTo.marker('2'); -verify.completionListContains('n', '(property) Restricted.n: number'); - -goTo.marker('3'); -verify.completionListIsEmpty(); - -goTo.marker('4'); -verify.completionListContains('n', '(property) Restricted.n: number'); - +verify.completions( + { + marker: "1", + exact: [ + { name: "n", text: "(property) C1.n: number" }, + { name: "m", text: "(property) C1.m: number" }, + { name: "f", text: "(method) C1.f(this: this): void" }, + { name: "g", text: "(method) C1.g(this: Restricted): void" }, + ], + }, + { + marker: ["2", "4"], + exact: { name: "n", text: "(property) Restricted.n: number" }, + }, + { marker: "3", exact: undefined }, +); diff --git a/tests/cases/fourslash/memberListOnFunctionParameter.ts b/tests/cases/fourslash/memberListOnFunctionParameter.ts index 52daacb3573..8679f1be591 100644 --- a/tests/cases/fourslash/memberListOnFunctionParameter.ts +++ b/tests/cases/fourslash/memberListOnFunctionParameter.ts @@ -5,9 +5,8 @@ //// x.forEach(function (y) { y./**/} ); ////} -goTo.marker(); -verify.completionListContains("charAt"); -verify.completionListContains("charCodeAt"); -verify.completionListContains("length"); -verify.completionListContains("concat"); -verify.not.completionListContains("toFixed"); \ No newline at end of file +verify.completions({ + marker: "", + includes: "charAt", + excludes: "toFixed", +}); diff --git a/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts b/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts index c44835f6882..edc7432ab07 100644 --- a/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts +++ b/tests/cases/fourslash/memberListOnThisInClassWithPrivates.ts @@ -7,7 +7,12 @@ //// private privProp = 0; ////} -goTo.marker(); -verify.completionListContains('privMeth', '(method) C1.privMeth(): void'); -verify.completionListContains('pubMeth', '(method) C1.pubMeth(): void'); -verify.completionListContains('pubProp', '(property) C1.pubProp: number'); \ No newline at end of file +verify.completions({ + marker: "", + exact: [ + { name: "pubMeth", text: "(method) C1.pubMeth(): void" }, + { name: "privMeth", text: "(method) C1.privMeth(): void" }, + { name: "pubProp", text: "(property) C1.pubProp: number" }, + { name: "privProp", text: "(property) C1.privProp: number" }, + ], +}) diff --git a/tests/cases/fourslash/memberlistOnDDot.ts b/tests/cases/fourslash/memberlistOnDDot.ts index 11efdd5d523..c9d80fd827f 100644 --- a/tests/cases/fourslash/memberlistOnDDot.ts +++ b/tests/cases/fourslash/memberlistOnDDot.ts @@ -6,4 +6,4 @@ goTo.marker(); edit.insert('.'); edit.insert('.'); -//verify.not.completionListContains('charAt'); \ No newline at end of file +verify.completions({ exact: undefined }); diff --git a/tests/cases/fourslash/mergedDeclarations1.ts b/tests/cases/fourslash/mergedDeclarations1.ts index 3c99b89e0e7..b0b8806e956 100644 --- a/tests/cases/fourslash/mergedDeclarations1.ts +++ b/tests/cases/fourslash/mergedDeclarations1.ts @@ -17,11 +17,7 @@ ////var p2 = point./*2*/origin; ////var b = point./*3*/equals(p1, p2); -goTo.marker('1'); -verify.completionListContains('point'); - -goTo.marker('2'); -verify.completionListContains('origin'); - -goTo.marker('3'); -verify.completionListContains('equals'); \ No newline at end of file +verify.completions( + { marker: "1", includes: "point", isNewIdentifierLocation: true }, + { marker: ["2", "3"], exact: ["equals", "origin", ...completion.functionMembersWithPrototype] }, +); diff --git a/tests/cases/fourslash/mergedDeclarations2.ts b/tests/cases/fourslash/mergedDeclarations2.ts index 426a27d7b76..d02e557ba6b 100644 --- a/tests/cases/fourslash/mergedDeclarations2.ts +++ b/tests/cases/fourslash/mergedDeclarations2.ts @@ -13,8 +13,7 @@ ////var p2 = point./*1*/origin; ////var b = point./*2*/equals(p1, p2); -goTo.marker('1'); -verify.completionListContains('origin'); - -goTo.marker('2'); -verify.completionListContains('equals'); \ No newline at end of file +verify.completions( + { marker: "1", includes: "origin" }, + { marker: "2", includes: "equals" }, +); diff --git a/tests/cases/fourslash/mergedDeclarationsWithExportAssignment1.ts b/tests/cases/fourslash/mergedDeclarationsWithExportAssignment1.ts index f6a159f7eee..5854f830d82 100644 --- a/tests/cases/fourslash/mergedDeclarationsWithExportAssignment1.ts +++ b/tests/cases/fourslash/mergedDeclarationsWithExportAssignment1.ts @@ -15,19 +15,17 @@ ////var /*3*/z = new /*2*/Foo(); ////var /*5*/r2 = Foo./*4*/x; -verify.quickInfoAt("1", [ - "(alias) class Foo", - "(alias) namespace Foo", - "import Foo = require('./mergedDeclarationsWithExportAssignment1_file0')" -].join("\n")); - -goTo.marker('2'); -verify.completionListContains('Foo'); - -verify.quickInfoAt("3", "var z: Foo"); - -goTo.marker('4'); -verify.completionListContains('x'); - -verify.quickInfoAt("5", "var r2: number"); +verify.quickInfos({ + 1: [ + "(alias) class Foo", + "(alias) namespace Foo", + "import Foo = require('./mergedDeclarationsWithExportAssignment1_file0')" + ].join("\n"), + 3: "var z: Foo", + 5: "var r2: number", +}); +verify.completions( + { marker: "2", includes: "Foo" }, + { marker: "4", includes: "x" }, +); diff --git a/tests/cases/fourslash/moduleMembersOfGenericType.ts b/tests/cases/fourslash/moduleMembersOfGenericType.ts index 1c5a3acff2c..f3af3e2080f 100644 --- a/tests/cases/fourslash/moduleMembersOfGenericType.ts +++ b/tests/cases/fourslash/moduleMembersOfGenericType.ts @@ -5,5 +5,4 @@ ////} ////var r = M./**/; -goTo.marker(); -verify.completionListContains('x', 'var M.x: (x: T) => T'); +verify.completions({ marker: "", exact: { name: "x", text: "var M.x: (x: T) => T" } }); diff --git a/tests/cases/fourslash/multiModuleClodule1.ts b/tests/cases/fourslash/multiModuleClodule1.ts index 5aeb2e709f5..fa52150896f 100644 --- a/tests/cases/fourslash/multiModuleClodule1.ts +++ b/tests/cases/fourslash/multiModuleClodule1.ts @@ -17,26 +17,11 @@ ////} //// ////var c = new C/*1*/(C./*2*/x); -////c/*3*/.foo = C./*4*/foo; +////c./*3*/foo = C./*4*/foo; -goTo.marker('1'); -verify.completionListContains('C'); - -goTo.marker('2'); -verify.completionListContains('x'); -verify.completionListContains('foo'); - -verify.completionListContains('boo'); -verify.not.completionListContains('bar'); - -goTo.marker('3'); -// editor is doing the right thing, fourslash is not -//verify.completionListContains('foo'); -//verify.completionListContains('bar'); - -goTo.marker('4'); -verify.completionListContains('x'); -verify.completionListContains('foo'); -verify.completionListContains('boo'); - -verify.noErrors(); \ No newline at end of file +verify.completions( + { marker: "1", includes: "C" }, + { marker: ["2", "4"], exact: ["prototype", "boo", "x", "foo", ...completion.functionMembers] }, + { marker: "3", exact: ["foo", "bar"] }, +); +verify.noErrors(); diff --git a/tests/cases/fourslash/multiModuleFundule1.ts b/tests/cases/fourslash/multiModuleFundule1.ts index 71fd64771d6..6cc23caf81f 100644 --- a/tests/cases/fourslash/multiModuleFundule1.ts +++ b/tests/cases/fourslash/multiModuleFundule1.ts @@ -13,21 +13,17 @@ ////var /*4*/r2 = new C(/*3*/ // using void returning function as constructor ////var r3 = C./*5*/ -goTo.marker('1'); -verify.completionListContains('C'); +verify.completions({ marker: "1", includes: "C", isNewIdentifierLocation: true }); edit.insert('C.x);'); verify.quickInfoAt("2", "var r: void"); -goTo.marker('3'); -verify.completionListContains('C'); +verify.completions({ marker: "3", includes: "C", isNewIdentifierLocation: true }); edit.insert('C.x);'); verify.quickInfoAt("4", "var r2: any"); -goTo.marker('5'); -verify.completionListContains('x'); -verify.completionListContains('foo'); +verify.completions({ marker: "5", includes: ["x", "foo"] }); edit.insert('x;'); verify.noErrors(); \ No newline at end of file diff --git a/tests/cases/fourslash/noCompletionListOnCommentsInsideObjectLiterals.ts b/tests/cases/fourslash/noCompletionListOnCommentsInsideObjectLiterals.ts index 38f9133149e..9247b2593a5 100644 --- a/tests/cases/fourslash/noCompletionListOnCommentsInsideObjectLiterals.ts +++ b/tests/cases/fourslash/noCompletionListOnCommentsInsideObjectLiterals.ts @@ -11,8 +11,4 @@ //// }; ////} -goTo.marker("1"); -verify.completionListIsEmpty(); - -goTo.marker("2"); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: test.markers(), exact: undefined }); diff --git a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts index 3493c4c2cff..681ea8f04d7 100644 --- a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts +++ b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts @@ -9,23 +9,21 @@ // @Filename: /a.js //// export const x = 0; //// export class C {} -//// +//// // @Filename: /b.js //// /**/ -goTo.file("/b.js"); -goTo.marker(); -verify.not.completionListContains("fail", undefined, undefined, undefined, undefined, undefined, { includeCompletionsForModuleExports: true }); +verify.completions({ marker: "", excludes: "fail", preferences: { includeCompletionsForModuleExports: true } }); edit.insert("export const k = 10;\r\nf"); -verify.completionListContains( - { name: "fail", source: "/node_modules/foo/index" }, - "const fail: number", - "", - "const", - undefined, - true, - { - includeCompletionsForModuleExports: true, - sourceDisplay: "./node_modules/foo/index" - }); +verify.completions({ + includes: { + name: "fail", + source: "/node_modules/foo/index", + sourceDisplay: "./node_modules/foo/index", + text: "const fail: number", + kind: "const", + hasAction: true, + }, + preferences: { includeCompletionsForModuleExports: true }, +}); diff --git a/tests/cases/fourslash/nonExistingImport.ts b/tests/cases/fourslash/nonExistingImport.ts index 899d4422aad..a06a58a14e0 100644 --- a/tests/cases/fourslash/nonExistingImport.ts +++ b/tests/cases/fourslash/nonExistingImport.ts @@ -5,5 +5,4 @@ //// var n: num/*1*/ ////} -goTo.marker('1'); -verify.not.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "1", exact: completion.globalTypes }); diff --git a/tests/cases/fourslash/objectLiteralBindingInParameter.ts b/tests/cases/fourslash/objectLiteralBindingInParameter.ts index b1cbd21d929..b35890a0d3b 100644 --- a/tests/cases/fourslash/objectLiteralBindingInParameter.ts +++ b/tests/cases/fourslash/objectLiteralBindingInParameter.ts @@ -18,18 +18,4 @@ //// } ////}; -goTo.marker("1"); -verify.completionListContains("x1"); -verify.completionListContains("x2"); - -goTo.marker("2"); -verify.completionListContains("x1"); -verify.completionListContains("x2"); - -goTo.marker("3"); -verify.completionListContains("x1"); -verify.completionListContains("x2"); - -goTo.marker("4"); -verify.completionListContains("x1"); -verify.completionListContains("x2"); \ No newline at end of file +verify.completions({ marker: test.markers(), exact: ["x1", "x2"] }); diff --git a/tests/cases/fourslash/paramHelpOnCommaInString.ts b/tests/cases/fourslash/paramHelpOnCommaInString.ts index 258dbfa48e3..56d7cdabfac 100644 --- a/tests/cases/fourslash/paramHelpOnCommaInString.ts +++ b/tests/cases/fourslash/paramHelpOnCommaInString.ts @@ -5,4 +5,4 @@ ////blah('hola/*1*/,/*2*/') // making sure the comma in a string literal doesn't trigger param help on the second function param -verify.signatureHelp({ marker: test.markerNames(), parameterName: "foo" }); +verify.signatureHelp({ marker: test.markers(), parameterName: "foo" }); diff --git a/tests/cases/fourslash/parameterInfoOnParameterType.ts b/tests/cases/fourslash/parameterInfoOnParameterType.ts index 117f07021db..dc12353f502 100644 --- a/tests/cases/fourslash/parameterInfoOnParameterType.ts +++ b/tests/cases/fourslash/parameterInfoOnParameterType.ts @@ -5,4 +5,4 @@ ////foo("test"/*1*/); ////foo(b/*2*/); -verify.signatureHelp({ marker: test.markerNames(), parameterName: "a" }); +verify.signatureHelp({ marker: test.markers(), parameterName: "a" }); diff --git a/tests/cases/fourslash/proto.ts b/tests/cases/fourslash/proto.ts index 8dc82c53cd1..acf7f15b1b5 100644 --- a/tests/cases/fourslash/proto.ts +++ b/tests/cases/fourslash/proto.ts @@ -12,8 +12,7 @@ verify.quickInfos({ 2: "var __proto__: M.__proto__" }); -goTo.marker('3'); -verify.completionListContains("__proto__", "var __proto__: M.__proto__", ""); +verify.completions({ marker: "3", includes: { name: "__proto__", text: "var __proto__: M.__proto__" } }); edit.insert("__proto__"); verify.goToDefinitionIs("2"); diff --git a/tests/cases/fourslash/protoPropertyInObjectLiteral.ts b/tests/cases/fourslash/protoPropertyInObjectLiteral.ts index 74e422fcec7..0f450f9c94f 100644 --- a/tests/cases/fourslash/protoPropertyInObjectLiteral.ts +++ b/tests/cases/fourslash/protoPropertyInObjectLiteral.ts @@ -9,14 +9,12 @@ ////o1./*1*/ ////o2./*2*/ -goTo.marker('1'); -verify.completionListContains("__proto__", '(property) "__proto__": number'); +verify.completions({ marker: "1", exact: { name: "__proto__", text: '(property) "__proto__": number' } }); edit.insert("__proto__ = 10;"); verify.quickInfoAt("1", '(property) "__proto__": number'); -goTo.marker('2'); -verify.completionListContains("__proto__", '(property) __proto__: number'); +verify.completions({ marker: "2", exact: { name: "__proto__", text: "(property) __proto__: number" } }); edit.insert("__proto__ = 10;"); verify.quickInfoAt("2", "(property) __proto__: number"); diff --git a/tests/cases/fourslash/protoVarInContextualObjectLiteral.ts b/tests/cases/fourslash/protoVarInContextualObjectLiteral.ts index cf76ba7c3cd..68a15567435 100644 --- a/tests/cases/fourslash/protoVarInContextualObjectLiteral.ts +++ b/tests/cases/fourslash/protoVarInContextualObjectLiteral.ts @@ -39,56 +39,35 @@ //// /*6*/ //// }; -goTo.marker('1'); -verify.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); -edit.insert('__proto__: 10,'); -verify.not.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); +const tripleProto: FourSlashInterface.ExpectedCompletionEntry = { name: "___proto__", text: "(property) ___proto__: string" }; +const proto: FourSlashInterface.ExpectedCompletionEntry = { name: "__proto__", text: "(property) __proto__: number" }; +const protoQuoted: FourSlashInterface.ExpectedCompletionEntry = { name: "__proto__", text: '(property) "__proto__": number' }; +const p: FourSlashInterface.ExpectedCompletionEntry = { name: "p", text: "(property) p: number" }; -goTo.marker('2'); -verify.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ marker: "1", exact: [proto, p] }); +edit.insert('__proto__: 10,'); +verify.completions({ exact: p }); + +verify.completions({ marker: "2", exact: [proto, p] }); edit.insert('"__proto__": 10,'); -verify.not.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: p }); -goTo.marker('3'); -verify.completionListContains("__proto__", '(property) "__proto__": number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ marker: "3", exact: [protoQuoted, p] }) edit.insert('__proto__: 10,'); -verify.not.completionListContains("__proto__", '(property) "__proto__": number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: p }); -goTo.marker('4'); -verify.completionListContains("__proto__", '(property) "__proto__": number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ marker: "4", exact: [protoQuoted, p] }); edit.insert('"__proto__": 10,'); -verify.not.completionListContains("__proto__", '(property) "__proto__": number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: p }); -goTo.marker('5'); -verify.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ marker: "5", exact: [proto, tripleProto, p] }); edit.insert('__proto__: 10,'); -verify.not.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: [tripleProto, p] }); edit.insert('"___proto__": "10",'); -verify.not.completionListContains("__proto__", '(property) __proto__: number'); -verify.not.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: p }); -goTo.marker('6'); -verify.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("__proto__", '(property) __proto__: number'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ marker: "6", exact: [proto, tripleProto, p] }); edit.insert('___proto__: "10",'); -verify.completionListContains("__proto__", '(property) __proto__: number'); -verify.not.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("p", '(property) p: number'); +verify.completions({ exact: [proto, p] }); edit.insert('"__proto__": 10,'); -verify.not.completionListContains("__proto__", '(property) __proto__: number'); -verify.not.completionListContains("___proto__", '(property) ___proto__: string'); -verify.completionListContains("p", '(property) p: number'); \ No newline at end of file +verify.completions({ exact: p }); diff --git a/tests/cases/fourslash/protoVarVisibleWithOuterScopeUnderscoreProto.ts b/tests/cases/fourslash/protoVarVisibleWithOuterScopeUnderscoreProto.ts index c0c7eb9f3ce..b24cbfb7ae8 100644 --- a/tests/cases/fourslash/protoVarVisibleWithOuterScopeUnderscoreProto.ts +++ b/tests/cases/fourslash/protoVarVisibleWithOuterScopeUnderscoreProto.ts @@ -7,6 +7,10 @@ //// /**/ ////} -goTo.marker(''); -verify.completionListContains("__proto__", '(local var) __proto__: string'); -verify.completionListContains("___proto__", 'var ___proto__: number'); +verify.completions({ + marker: "", + includes: [ + { name: "__proto__", text: "(local var) __proto__: string" }, + { name: "___proto__", text: "var ___proto__: number" }, + ], +}); diff --git a/tests/cases/fourslash/prototypeProperty.ts b/tests/cases/fourslash/prototypeProperty.ts index cae07d04a3e..ada6d724469 100644 --- a/tests/cases/fourslash/prototypeProperty.ts +++ b/tests/cases/fourslash/prototypeProperty.ts @@ -6,5 +6,4 @@ verify.quickInfoAt("1", "(property) A.prototype: A"); -goTo.marker('2'); -verify.completionListContains('prototype', '(property) A.prototype: A'); +verify.completions({ marker: "2", includes: [{ name: "prototype", text: "(property) A.prototype: A" }] }); diff --git a/tests/cases/fourslash/qualifiedName_import-declaration-with-variable-entity-names.ts b/tests/cases/fourslash/qualifiedName_import-declaration-with-variable-entity-names.ts index ea660aa89ec..9cdedf6d46e 100644 --- a/tests/cases/fourslash/qualifiedName_import-declaration-with-variable-entity-names.ts +++ b/tests/cases/fourslash/qualifiedName_import-declaration-with-variable-entity-names.ts @@ -11,7 +11,7 @@ ////var x = Alpha.[|{| "name" : "mem" |}x|] goTo.marker('import'); -verify.completionListContains('x', 'var Alpha.x: number'); +verify.completions({ includes: { name: "x", text: "var Alpha.x: number" } }); var def: FourSlashInterface.Range = test.ranges().filter(range => range.marker.data.name === "def")[0]; var imp: FourSlashInterface.Range = test.ranges().filter(range => range.marker.data.name === "import")[0]; diff --git a/tests/cases/fourslash/quickInfoOnNarrowedType.ts b/tests/cases/fourslash/quickInfoOnNarrowedType.ts index 2c8f4c8e216..da9a7ba0c7a 100644 --- a/tests/cases/fourslash/quickInfoOnNarrowedType.ts +++ b/tests/cases/fourslash/quickInfoOnNarrowedType.ts @@ -4,7 +4,7 @@ ////function foo(strOrNum: string | number) { //// if (typeof /*1*/strOrNum === "number") { -//// return /*2*/strOrNum; +//// return /*2*/strOrNum; //// } //// else { //// return /*3*/strOrNum.length; @@ -18,26 +18,19 @@ //// /*6*/s; ////} -goTo.marker('1'); -verify.quickInfoIs('(parameter) strOrNum: string | number'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string | number"); +verify.quickInfos({ + 1: "(parameter) strOrNum: string | number", + 2: "(parameter) strOrNum: number", + 3: "(parameter) strOrNum: string", + 4: "let s: string | undefined", + 5: "let s: string | undefined", + 6: "let s: string", +}); -goTo.marker('2'); -verify.quickInfoIs('(parameter) strOrNum: number'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: number"); - -goTo.marker('3'); -verify.quickInfoIs('(parameter) strOrNum: string'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string"); - -goTo.marker('4'); -verify.quickInfoIs('let s: string | undefined'); -verify.completionListContains("s", "let s: string | undefined"); - -goTo.marker('5'); -verify.quickInfoIs('let s: string | undefined'); -verify.completionListContains("s", "let s: string | undefined"); - -goTo.marker('6'); -verify.quickInfoIs('let s: string'); -verify.completionListContains("s", "let s: string"); +verify.completions( + { marker: "1", includes: { name: "strOrNum", text: "(parameter) strOrNum: string | number" } }, + { marker: "2", includes: { name: "strOrNum", text: "(parameter) strOrNum: number" } }, + { marker: "3", includes: { name: "strOrNum", text: "(parameter) strOrNum: string" } }, + { marker: ["4", "5"], includes: { name: "s", text: "let s: string | undefined" } }, + { marker: "6", includes: { name: "s", text: "let s: string" } }, +); diff --git a/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts b/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts index 54a80194f37..f995cd25cc4 100644 --- a/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts +++ b/tests/cases/fourslash/quickInfoOnNarrowedTypeInModule.ts @@ -26,50 +26,26 @@ //// strOrNum = m./*9*/exportedStrOrNum; ////} -goTo.marker('1'); -verify.quickInfoIs('var nonExportedStrOrNum: string | number'); -verify.completionListContains("nonExportedStrOrNum", "var nonExportedStrOrNum: string | number"); +verify.quickInfos({ + 1: "var nonExportedStrOrNum: string | number", + 2: "var nonExportedStrOrNum: number", + 3: "var nonExportedStrOrNum: string", + 4: "var m.exportedStrOrNum: string | number", + 5: "var m.exportedStrOrNum: number", + 6: "var m.exportedStrOrNum: string", + 7: "var m.exportedStrOrNum: string | number", + 8: "var m.exportedStrOrNum: number", + 9: "var m.exportedStrOrNum: string", +}); -goTo.marker('2'); -verify.quickInfoIs('var nonExportedStrOrNum: number'); -verify.completionListContains("nonExportedStrOrNum", "var nonExportedStrOrNum: number"); - -goTo.marker('3'); -verify.quickInfoIs('var nonExportedStrOrNum: string'); -verify.completionListContains("nonExportedStrOrNum", "var nonExportedStrOrNum: string"); - -goTo.marker('4'); -verify.quickInfoIs('var m.exportedStrOrNum: string | number'); -verify.completionListContains("exportedStrOrNum", "var exportedStrOrNum: string | number"); - -goTo.marker('5'); -verify.quickInfoIs('var m.exportedStrOrNum: number'); -verify.completionListContains("exportedStrOrNum", "var exportedStrOrNum: number"); - -goTo.marker('6'); -verify.quickInfoIs('var m.exportedStrOrNum: string'); -verify.completionListContains("exportedStrOrNum", "var exportedStrOrNum: string"); - -goTo.marker('7'); -verify.quickInfoIs('var m.exportedStrOrNum: string | number'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string | number"); - -goTo.marker('8'); -verify.quickInfoIs('var m.exportedStrOrNum: number'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: number"); - -goTo.marker('9'); -verify.quickInfoIs('var m.exportedStrOrNum: string'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string"); - -goTo.marker('7'); -verify.quickInfoIs('var m.exportedStrOrNum: string | number'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string | number"); - -goTo.marker('8'); -verify.quickInfoIs('var m.exportedStrOrNum: number'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: number"); - -goTo.marker('9'); -verify.quickInfoIs('var m.exportedStrOrNum: string'); -verify.completionListContains("exportedStrOrNum", "var m.exportedStrOrNum: string"); \ No newline at end of file +verify.completions( + { marker: "1", includes: { name: "nonExportedStrOrNum", text: "var nonExportedStrOrNum: string | number" } }, + { marker: "2", includes: { name: "nonExportedStrOrNum", text: "var nonExportedStrOrNum: number" }, isNewIdentifierLocation: true }, + { marker: "3", includes: { name: "nonExportedStrOrNum", text: "var nonExportedStrOrNum: string" }, isNewIdentifierLocation: true }, + { marker: "4", includes: { name: "exportedStrOrNum", text: "var exportedStrOrNum: string | number" } }, + { marker: "5", includes: { name: "exportedStrOrNum", text: "var exportedStrOrNum: number" }, isNewIdentifierLocation: true }, + { marker: "6", includes: { name: "exportedStrOrNum", text: "var exportedStrOrNum: string" }, isNewIdentifierLocation: true }, + { marker: "7", includes: { name: "exportedStrOrNum", text: "var m.exportedStrOrNum: string | number" } }, + { marker: "8", includes: { name: "exportedStrOrNum", text: "var m.exportedStrOrNum: number" } }, + { marker: "9", includes: { name: "exportedStrOrNum", text: "var m.exportedStrOrNum: string" } }, +); diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts index e11af2beda4..1d7130948c1 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithAccessors.ts @@ -1,6 +1,6 @@ /// -////function /*1*/makePoint(x: number) { +////function /*1*/makePoint(x: number) { //// return { //// b: 10, //// get x() { return x; }, @@ -13,12 +13,15 @@ verify.quickInfos({ 1: "function makePoint(x: number): {\n b: number;\n x: number;\n}", - 2: "var x: number" + 2: "var x: number", + 3: "(property) x: number", + 4: "var point: {\n b: number;\n x: number;\n}", }); -goTo.marker('3'); -verify.completionListContains("x", "(property) x: number", undefined); -verify.completionListContains("b", "(property) b: number", undefined); -verify.quickInfoIs("(property) x: number"); - -verify.quickInfoAt("4", "var point: {\n b: number;\n x: number;\n}"); +verify.completions({ + marker: "3", + exact: [ + { name: "b", text: "(property) b: number" }, + { name: "x", text: "(property) x: number" }, + ], +}); diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts index f592b255ac0..2c7a07dd844 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlyGetter.ts @@ -1,6 +1,6 @@ /// -////function /*1*/makePoint(x: number) { +////function /*1*/makePoint(x: number) { //// return { //// get x() { return x; }, //// }; @@ -10,10 +10,8 @@ verify.quickInfos({ 1: "function makePoint(x: number): {\n readonly x: number;\n}", - 2: "var x: number" + 2: "var x: number", + 4: "var point: {\n readonly x: number;\n}", }); -goTo.marker('3'); -verify.completionListContains("x", "(property) x: number", undefined); - -verify.quickInfoAt("4", "var point: {\n readonly x: number;\n}"); +verify.completions({ marker: "3", exact: { name: "x", text: "(property) x: number" } }); diff --git a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts index d66626cc99d..d9639821792 100644 --- a/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts +++ b/tests/cases/fourslash/quickInfoOnObjectLiteralWithOnlySetter.ts @@ -1,6 +1,6 @@ /// -////function /*1*/makePoint(x: number) { +////function /*1*/makePoint(x: number) { //// return { //// b: 10, //// set x(a: number) { this.b = a; } @@ -9,11 +9,16 @@ ////var /*3*/point = makePoint(2); ////point./*2*/x = 30; -verify.quickInfoAt("1", "function makePoint(x: number): {\n b: number;\n x: number;\n}"); +verify.completions({ + marker: "2", + exact: [ + { name: "b", text: "(property) b: number" }, + { name: "x", text: "(property) x: number" }, + ], +}); -goTo.marker('2'); -verify.completionListContains("x", "(property) x: number", undefined); -verify.completionListContains("b", "(property) b: number", undefined); -verify.quickInfoIs("(property) x: number"); - -verify.quickInfoAt("3", "var point: {\n b: number;\n x: number;\n}"); +verify.quickInfos({ + 1: "function makePoint(x: number): {\n b: number;\n x: number;\n}", + 2: "(property) x: number", + 3: "var point: {\n b: number;\n x: number;\n}", +}); diff --git a/tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts b/tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts index 368064ea7f6..2b433fd13c9 100644 --- a/tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts +++ b/tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts @@ -13,5 +13,12 @@ ////x/*1*/./*2*/m(); verify.quickInfoAt("1", "var x: C"); -goTo.marker('2'); -verify.completionListContains('m', '(property) C.m: (a: string) => void', 'The prototype method.'); +verify.completions({ + marker: "2", + includes: { + name: "m", + text: "(property) C.m: (a: string) => void", + documentation: "The prototype method.", + tags: [{ name: "param", text: "a Parameter definition." }], + }, +}); diff --git a/tests/cases/fourslash/selfReferencedExternalModule.ts b/tests/cases/fourslash/selfReferencedExternalModule.ts index 3c96c320784..142d45e5a08 100644 --- a/tests/cases/fourslash/selfReferencedExternalModule.ts +++ b/tests/cases/fourslash/selfReferencedExternalModule.ts @@ -4,6 +4,10 @@ ////export var I = 1; ////A./**/I -goTo.marker(); -verify.completionListContains("A", "import A = require('./app')"); -verify.completionListContains("I", "var I: number"); +verify.completions({ + marker: "", + exact: [ + { name: "A", text: "import A = require('./app')" }, + { name: "I", text: "var I: number" }, + ], +}); diff --git a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles01.ts b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles01.ts index 243975fde2d..005f42f82bc 100644 --- a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles01.ts +++ b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles01.ts @@ -14,7 +14,8 @@ //// import a = require("./a"); //// a.fo/*2*/ -goTo.marker('1'); -verify.completionEntryDetailIs("foo", "var foo: (p1: string) => void", "Modify the parameter"); -goTo.marker('2'); -verify.completionEntryDetailIs("foo", "(property) a.foo: (p1: string) => void", "Modify the parameter"); +const entry = (text: string): FourSlashInterface.ExpectedCompletionEntry => ({ name: "foo", text, documentation: "Modify the parameter", tags: [{ name: "param", text: "p1" }] }); +verify.completions( + { marker: "1", includes: entry("var foo: (p1: string) => void") }, + { marker: "2", exact: entry("(property) a.foo: (p1: string) => void") }, +); diff --git a/tests/cases/fourslash/server/completions01.ts b/tests/cases/fourslash/server/completions01.ts index 38fdbab4eda..21fb7145ebb 100644 --- a/tests/cases/fourslash/server/completions01.ts +++ b/tests/cases/fourslash/server/completions01.ts @@ -6,11 +6,9 @@ goTo.marker('1'); edit.insert('.'); -verify.completionListContains('trim'); -verify.completionListCount(21); +verify.completions({ includes: "trim" }); edit.insert('});'); // need the following lines to not have parse errors in order for completion list to appear goTo.marker('2'); edit.insert('.'); -verify.completionListContains('trim'); -verify.completionListCount(21); +verify.completions({ includes: "trim" }); diff --git a/tests/cases/fourslash/server/completions02.ts b/tests/cases/fourslash/server/completions02.ts index b6c39a5c723..1a493af524b 100644 --- a/tests/cases/fourslash/server/completions02.ts +++ b/tests/cases/fourslash/server/completions02.ts @@ -7,12 +7,14 @@ ////} ////Foo./**/ -goTo.marker(""); -verify.completionListContains("x"); +const entryName = (e: FourSlashInterface.ExpectedCompletionEntry) => typeof e === "string" ? e : e.name; +const sortedFunctionMembers = completion.functionMembersWithPrototype.slice().sort((a, b) => entryName(a).localeCompare(entryName(b))); +const exact: ReadonlyArray = [...sortedFunctionMembers, { name: "x", text: "var Foo.x: number" }]; +verify.completions({ marker: "", exact }); // Make an edit edit.insert("a"); edit.backspace(); // Checking for completion details after edit should work too -verify.completionEntryDetailIs("x", "var Foo.x: number"); +verify.completions({ exact }); diff --git a/tests/cases/fourslash/server/completions03.ts b/tests/cases/fourslash/server/completions03.ts index ef5f1651951..ad8aeff2b77 100644 --- a/tests/cases/fourslash/server/completions03.ts +++ b/tests/cases/fourslash/server/completions03.ts @@ -14,7 +14,4 @@ //// /**/ //// } -goTo.marker(""); -verify.completionListContains("three"); -verify.not.completionListContains("one"); -verify.not.completionListContains("two"); +verify.completions({ marker: "", exact: "three" }); diff --git a/tests/cases/fourslash/server/jsdocParamTagSpecialKeywords.ts b/tests/cases/fourslash/server/jsdocParamTagSpecialKeywords.ts index be7ca5f0dff..2d7606ccbeb 100644 --- a/tests/cases/fourslash/server/jsdocParamTagSpecialKeywords.ts +++ b/tests/cases/fourslash/server/jsdocParamTagSpecialKeywords.ts @@ -9,6 +9,4 @@ //// type./**/ //// } - -goTo.marker(); -verify.completionListContains("charAt"); \ No newline at end of file +verify.completions({ marker: "", includes: "charAt" }); diff --git a/tests/cases/fourslash/server/jsdocTypedefTag.ts b/tests/cases/fourslash/server/jsdocTypedefTag.ts index 1ab70604561..ed27e6e29ef 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTag.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTag.ts @@ -51,41 +51,24 @@ //// d.dogName./*dogName*/; //// d.dogAge./*dogAge*/; -goTo.marker('numberLike'); -verify.completionListContains('charAt'); -verify.completionListContains('toExponential'); +verify.completions( + { marker: "numberLike", includes: ["charAt", "toExponential"] }, -goTo.marker('person'); -verify.completionListContains('personName'); -verify.completionListContains('personAge'); -goTo.marker('personName'); -verify.completionListContains('charAt'); -goTo.marker('personAge'); -verify.completionListContains('toExponential'); + { marker: "person", includes: ["personName", "personAge"] }, + { marker: "personName", includes: "charAt" }, + { marker: "personAge", includes: "toExponential" }, -goTo.marker('animal'); -verify.completionListContains('animalName'); -verify.completionListContains('animalAge'); -goTo.marker('animalName'); -verify.completionListContains('charAt'); -goTo.marker('animalAge'); -verify.completionListContains('toExponential'); + { marker: "animal", includes: ["animalName", "animalAge"] }, + { marker: "animalName", includes: "charAt" }, + { marker: "animalAge", includes: "toExponential" }, -goTo.marker('dog'); -verify.completionListContains('dogName'); -verify.completionListContains('dogAge'); -goTo.marker('dogName'); -verify.completionListContains('charAt'); -goTo.marker('dogAge'); -verify.completionListContains('toExponential'); + { marker: "dog", includes: ["dogName", "dogAge"] }, + { marker: "dogName", includes: "charAt" }, + { marker: "dogAge", includes: "toExponential" }, -goTo.marker('cat'); -verify.completionListContains('catName'); -verify.completionListContains('catAge'); -goTo.marker('catName'); -verify.completionListContains('charAt'); -goTo.marker('catAge'); -verify.completionListContains('toExponential'); + { marker: "cat", includes: ["catName", "catAge"] }, + { marker: "catName", includes: "charAt" }, + { marker: "catAge", includes: "toExponential" }, +); -goTo.marker("AnimalType"); -verify.quickInfoIs("type Animal = {\n animalName: string;\n animalAge: number;\n}", "- think Giraffes"); +verify.quickInfoAt("AnimalType", "type Animal = {\n animalName: string;\n animalAge: number;\n}", "- think Giraffes"); diff --git a/tests/cases/fourslash/server/jsdocTypedefTag1.ts b/tests/cases/fourslash/server/jsdocTypedefTag1.ts index 273dc1002af..4c7bde499eb 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTag1.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTag1.ts @@ -9,12 +9,11 @@ //// */ //// function foo() { } -//// /** +//// /** //// * @param {MyType} my //// */ //// function a(my) { //// my.yes./*1*/ //// } -goTo.marker('1'); -verify.completionListContains('charAt'); \ No newline at end of file +verify.completions({ marker: "1", includes: "charAt" }); diff --git a/tests/cases/fourslash/server/jsdocTypedefTag2.ts b/tests/cases/fourslash/server/jsdocTypedefTag2.ts index 60210935210..601db945130 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTag2.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTag2.ts @@ -9,22 +9,21 @@ //// */ //// function foo() {} -//// /** +//// /** //// * @param {A.B.MyType} my2 //// */ //// function a(my2) { //// my2.yes./*1*/ //// } -//// /** +//// /** //// * @param {MyType} my2 //// */ //// function b(my2) { //// my2.yes./*2*/ //// } - -goTo.marker('1'); -verify.completionListContains('charAt'); -goTo.marker('2'); -verify.not.completionListContains('charAt'); \ No newline at end of file +verify.completions( + { marker: "1", includes: "charAt" }, + { marker: "2", excludes: "charAt" }, +); diff --git a/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts b/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts index 29330a73d3c..0d04b58606f 100644 --- a/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts +++ b/tests/cases/fourslash/server/jsdocTypedefTagNamespace.ts @@ -15,13 +15,7 @@ //// /** @type {T.People} */ //// var x1; x1./*3*/; -goTo.marker("1"); -verify.completionListContains('charAt'); -verify.completionListContains('toExponential'); - -goTo.marker("2"); -verify.completionListContains('age'); - -goTo.marker("3"); -verify.completionListContains('charAt'); -verify.completionListContains('toExponential'); \ No newline at end of file +verify.completions( + { marker: ["1", "3"], includes: ["charAt", "toExponential"] }, + { marker: "2", includes: "age" }, +); diff --git a/tests/cases/fourslash/server/openFile.ts b/tests/cases/fourslash/server/openFile.ts index 320e52c9f5e..e30bccc488a 100644 --- a/tests/cases/fourslash/server/openFile.ts +++ b/tests/cases/fourslash/server/openFile.ts @@ -13,4 +13,4 @@ var overridingContent = "var t = 10; t."; goTo.file("test.ts", overridingContent); goTo.file("test1.ts"); goTo.eof(); -verify.completionListContains("toExponential"); +verify.completions({ includes: "toExponential" }); diff --git a/tests/cases/fourslash/server/openFileWithSyntaxKind.ts b/tests/cases/fourslash/server/openFileWithSyntaxKind.ts index dcb1e54999e..16e05cf4080 100644 --- a/tests/cases/fourslash/server/openFileWithSyntaxKind.ts +++ b/tests/cases/fourslash/server/openFileWithSyntaxKind.ts @@ -16,4 +16,4 @@ goTo.file("test.ts", /*content*/ undefined, "JS"); goTo.eof(); -verify.completionListContains("toExponential"); +verify.completions({ includes: "toExponential" }); diff --git a/tests/cases/fourslash/server/typeReferenceOnServer.ts b/tests/cases/fourslash/server/typeReferenceOnServer.ts index 574ea6f60c4..5a3273da7d7 100644 --- a/tests/cases/fourslash/server/typeReferenceOnServer.ts +++ b/tests/cases/fourslash/server/typeReferenceOnServer.ts @@ -4,6 +4,5 @@ ////var x: number; ////x./*1*/ -goTo.marker("1"); -verify.not.completionListIsEmpty(); +verify.completions({ marker: "1", includes: "toFixed" }); diff --git a/tests/cases/fourslash/shims-pp/getCompletionsAtPosition.ts b/tests/cases/fourslash/shims-pp/getCompletionsAtPosition.ts index f81572ccebf..527c0d0b6ca 100644 --- a/tests/cases/fourslash/shims-pp/getCompletionsAtPosition.ts +++ b/tests/cases/fourslash/shims-pp/getCompletionsAtPosition.ts @@ -1,4 +1,4 @@ -/// +/// ////function foo(strOrNum: string | number) { //// /*1*/ @@ -10,11 +10,8 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string | number"); - -goTo.marker('2'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: number"); - -goTo.marker('3'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string"); \ No newline at end of file +verify.completions( + { marker: "1", includes: { name: "strOrNum", text: "(parameter) strOrNum: string | number" } }, + { marker: "2", includes: { name: "strOrNum", text: "(parameter) strOrNum: number" } }, + { marker: "3", includes: { name: "strOrNum", text: "(parameter) strOrNum: string" } }, +); diff --git a/tests/cases/fourslash/shims/getCompletionsAtPosition.ts b/tests/cases/fourslash/shims/getCompletionsAtPosition.ts index f81572ccebf..aa8f7a64e7f 100644 --- a/tests/cases/fourslash/shims/getCompletionsAtPosition.ts +++ b/tests/cases/fourslash/shims/getCompletionsAtPosition.ts @@ -10,11 +10,8 @@ //// } ////} -goTo.marker('1'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string | number"); - -goTo.marker('2'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: number"); - -goTo.marker('3'); -verify.completionListContains("strOrNum", "(parameter) strOrNum: string"); \ No newline at end of file +verify.completions( + { marker: "1", includes: { name: "strOrNum", text: "(parameter) strOrNum: string | number" } }, + { marker: "2", includes: { name: "strOrNum", text: "(parameter) strOrNum: number" } }, + { marker: "3", includes: { name: "strOrNum", text: "(parameter) strOrNum: string" } }, +); diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates1.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates1.ts index 3824d238af3..334ce17779c 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates1.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates1.ts @@ -6,7 +6,7 @@ //// f `/*1*/ qwe/*2*/rty /*3*/$/*4*/{ 123 }/*5*/ as/*6*/df /*7*/$/*8*/{ 41234 }/*9*/ zxc/*10*/vb /*11*/$/*12*/{ g ` ` }/*13*/ /*14*/ /*15*/` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 4, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates2.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates2.ts index dc8fafdf7b4..b2c88fcd315 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates2.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates2.ts @@ -6,7 +6,7 @@ //// f `/*1*/ qwe/*2*/rty /*3*/$/*4*/{ 123 }/*5*/ as/*6*/df /*7*/$/*8*/{ 41234 }/*9*/ zxc/*10*/vb /*11*/$/*12*/{ g ` ` }/*13*/ /*14*/ /*15*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 4, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates3.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates3.ts index 8ec7d55e0c8..1022f7df13f 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates3.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates3.ts @@ -6,7 +6,7 @@ //// f ` qwerty ${/*1*/ /*2*/123/*3*/ /*4*/} asdf ${ 41234 } zxcvb ${ g ` ` } ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 4, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates4.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates4.ts index 526aea35957..a0e6208c90b 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates4.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates4.ts @@ -6,7 +6,7 @@ //// f ` qwerty ${ 123 } asdf ${/*1*/ /*2*/ /*3*/41/*4*/234/*5*/ /*6*/} zxcvb ${ g ` ` } ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 4, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates5.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates5.ts index 4b29879047f..25b83ece4be 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates5.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates5.ts @@ -6,7 +6,7 @@ //// f ` qwerty ${ 123 } asdf ${ 41234 } zxcvb ${/*1*/ /*2*/g/*3*/ /*4*/` `/*5*/ /*6*/} ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 4, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates6.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates6.ts index a0455fe0116..70d49704aef 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates6.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates6.ts @@ -6,7 +6,7 @@ //// f ` qwerty ${ 123 } asdf ${ 41234 } zxcvb ${ g `/*1*/ /*2*/ /*3*/` } ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "g(templateStrings: any, x: any, y: any, z: any): string", argumentCount: 1, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplates7.ts b/tests/cases/fourslash/signatureHelpTaggedTemplates7.ts index bd5456ccdd0..1c20a904b4e 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplates7.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplates7.ts @@ -6,7 +6,7 @@ //// f `/*1*/ /*2*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 1, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete1.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete1.ts index 7c50431f62f..93888461b3a 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete1.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete1.ts @@ -6,7 +6,7 @@ //// f `/*1*/ /*2*/${ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 2, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete2.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete2.ts index c8ed457422e..f693b991ce5 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete2.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete2.ts @@ -6,7 +6,7 @@ //// f ` ${/*1*/ /*2*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 2, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete3.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete3.ts index 375a3d919ec..7dd7c9331fb 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete3.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete3.ts @@ -6,7 +6,7 @@ //// f ` ${ }/*1*/ /*2*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 2, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete4.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete4.ts index 275dd2b5360..4641f73b69d 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete4.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete4.ts @@ -6,7 +6,7 @@ //// f ` ${ } ${/*1*/ /*2*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 3, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete5.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete5.ts index fa02e910637..3d82c58cbd5 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete5.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete5.ts @@ -6,7 +6,7 @@ //// f ` ${ } ${ }/*1*/ /*2*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 3, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete6.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete6.ts index c283d2e0053..0b602f34661 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete6.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete6.ts @@ -6,7 +6,7 @@ //// f ` ${ 123 } ${/*1*/ } ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 3, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete7.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete7.ts index b375bcc30d2..89bee03054f 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete7.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete7.ts @@ -9,7 +9,7 @@ //// /*8*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 3, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete8.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete8.ts index 1224f317f01..184a6ad5dd0 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete8.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete8.ts @@ -6,7 +6,7 @@ //// f `/*1*/\/*2*/`/*3*/ /*4*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 1, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete9.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete9.ts index 5635cf2a418..07b86e067eb 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete9.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesIncomplete9.ts @@ -6,7 +6,7 @@ //// f `/*1*/ \\\/*2*/`/*3*/ /*4*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", argumentCount: 1, parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesNested1.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesNested1.ts index e8c39a633a0..38b0f0e3b93 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesNested1.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesNested1.ts @@ -6,7 +6,7 @@ //// f `a ${ g `/*1*/alpha/*2*/ ${/*3*/ 12/*4*/3 /*5*/} beta /*6*/${ /*7*/456 /*8*/} gamma/*9*/` } b ${ g `/*10*/txt/*11*/` } c ${ g `/*12*/aleph /*13*/$/*14*/{ 12/*15*/3 } beit/*16*/` } d`; verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "g(templateStrings: any, x: any, y: any, z: any): string", parameterCount: 4, }); diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesNested2.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesNested2.ts index 32a64402ee3..bf99fd8e7df 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesNested2.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesNested2.ts @@ -6,7 +6,7 @@ //// f `/*1*/a $/*2*/{ /*3*/g /*4*/`alpha ${ 123 } beta ${ 456 } gamma`/*5*/ }/*6*/ b $/*7*/{ /*8*/g /*9*/`txt`/*10*/ } /*11*/c ${ /*12*/g /*13*/`aleph ${ 123 } beit`/*14*/ } d/*15*/`; verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), text: "f(templateStrings: any, x: any, y: any, z: any): number", parameterCount: 4, }); diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags1.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags1.ts index 7d119a4d3e8..ca38f83a778 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags1.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags1.ts @@ -8,7 +8,7 @@ //// f `/*1*/ /*2*/$/*3*/{ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o1: string): number", argumentCount: 2, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags2.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags2.ts index 9bd062cf62f..268a811dd2f 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags2.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags2.ts @@ -8,7 +8,7 @@ //// f `${/*1*/ /*2*/ /*3*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o1: string): number", argumentCount: 2, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags3.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags3.ts index 3a76cbc1ada..98936bfcc56 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags3.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags3.ts @@ -8,7 +8,7 @@ //// f `${/*1*/ "s/*2*/tring" /*3*/ } ${ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: TemplateStringsArray, p1_o3: string, p2_o3: boolean, p3_o3: number): boolean", argumentCount: 3, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags4.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags4.ts index fbf66ddd58e..3294dc1da50 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags4.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags4.ts @@ -8,7 +8,7 @@ //// f `${/*1*/ 123.456/*2*/ /*3*/ } ${ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o2: number, p2_o2: number, p3_o2: number): string", parameterCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags5.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags5.ts index dc4dc4db7ae..7dc7be257cc 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags5.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags5.ts @@ -8,7 +8,7 @@ //// f `${ } ${/*1*/ /*2*/ /*3*/ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o2: number, p2_o2: number, p3_o2: number): string", argumentCount: 3, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags6.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags6.ts index e012ec63665..2b2c9c5f221 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags6.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags6.ts @@ -8,7 +8,7 @@ //// f `${ } ${/*1*/ /*2*/ /*3*/} verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o2: number, p2_o2: number, p3_o2: number): string", argumentCount: 3, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags7.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags7.ts index f61b0921ebf..8e77f60b5c0 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags7.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags7.ts @@ -8,7 +8,7 @@ //// f `${ } ${/*1*/ fa/*2*/lse /*3*/} verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: TemplateStringsArray, p1_o3: string, p2_o3: boolean, p3_o3: number): boolean", argumentCount: 3, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags8.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags8.ts index 58ad3426f78..258067573de 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags8.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags8.ts @@ -8,7 +8,7 @@ //// f `${ undefined } ${ undefined } ${/*1*/ 10/*2*/./*3*/01 /*4*/} ` verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o2: number, p2_o2: number, p3_o2: number): string", argumentCount: 4, diff --git a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags9.ts b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags9.ts index daf0a55965e..7fbaf5ecb52 100644 --- a/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags9.ts +++ b/tests/cases/fourslash/signatureHelpTaggedTemplatesWithOverloadedTags9.ts @@ -8,7 +8,7 @@ //// f `${/*1*/ /*2*/ /*3*/} ${ verify.signatureHelp({ - marker: test.markerNames(), + marker: test.markers(), overloadsCount: 3, text: "f(templateStrings: string[], p1_o2: number, p2_o2: number, p3_o2: number): string", argumentCount: 3, diff --git a/tests/cases/fourslash/stringLiteralCompletionsForStringEnumContextualType.ts b/tests/cases/fourslash/stringLiteralCompletionsForStringEnumContextualType.ts index 664bfbac369..4c5228c1017 100644 --- a/tests/cases/fourslash/stringLiteralCompletionsForStringEnumContextualType.ts +++ b/tests/cases/fourslash/stringLiteralCompletionsForStringEnumContextualType.ts @@ -5,5 +5,4 @@ ////} ////const e: E = "/**/"; -goTo.marker(""); -verify.completionListIsEmpty(); +verify.completions({ marker: "", exact: [] }); diff --git a/tests/cases/fourslash/thisPredicateFunctionCompletions01.ts b/tests/cases/fourslash/thisPredicateFunctionCompletions01.ts index 8c9abb85418..de869dcd8d5 100644 --- a/tests/cases/fourslash/thisPredicateFunctionCompletions01.ts +++ b/tests/cases/fourslash/thisPredicateFunctionCompletions01.ts @@ -40,13 +40,11 @@ //// obj./*5*/; //// } -goTo.marker("1"); -verify.completionListContains("content"); -goTo.marker("2"); -verify.completionListContains("host"); -goTo.marker("3"); -verify.completionListContains("children"); -goTo.marker("4"); -verify.completionListContains("host"); -goTo.marker("5"); -verify.completionListContains("host"); \ No newline at end of file +const common: ReadonlyArray = ["isFile", "isDirectory", "isNetworked", "path"]; +verify.completions( + { marker: "1", exact: ["content", ...common] }, + { marker: "2", exact: ["host", "content", ...common] }, + { marker: "3", exact: ["children", ...common] }, + { marker: "4", exact: ["host", "children", ...common] }, + { marker: "5", exact: ["host", ...common] }, +); diff --git a/tests/cases/fourslash/thisPredicateFunctionCompletions02.ts b/tests/cases/fourslash/thisPredicateFunctionCompletions02.ts index e2e311ea649..d83c43e2cf9 100644 --- a/tests/cases/fourslash/thisPredicateFunctionCompletions02.ts +++ b/tests/cases/fourslash/thisPredicateFunctionCompletions02.ts @@ -31,13 +31,8 @@ //// } //// } -goTo.marker("1"); -verify.completionListContains("extraContents"); -goTo.marker("2"); -verify.completionListContains("broken"); -goTo.marker("3"); -verify.completionListContains("extraContents"); -goTo.marker("4"); -verify.completionListContains("spoiled"); -goTo.marker("5"); -verify.completionListContains("extraContents"); \ No newline at end of file +verify.completions( + { marker: ["1", "3", "5"], exact: ["contents", "isSundries", "isSupplies", "isPackedTight", "extraContents"] }, + { marker: "2", exact: "broken" }, + { marker: "4", exact: "spoiled" }, +); diff --git a/tests/cases/fourslash/thisPredicateFunctionCompletions03.ts b/tests/cases/fourslash/thisPredicateFunctionCompletions03.ts index 4985a1ca561..8c395bdb801 100644 --- a/tests/cases/fourslash/thisPredicateFunctionCompletions03.ts +++ b/tests/cases/fourslash/thisPredicateFunctionCompletions03.ts @@ -44,13 +44,7 @@ //// } //// let checked/*14*/LeaderStatus = isLeader/*15*/Guard(a); - -goTo.marker("2"); -verify.completionListContains("lead"); -goTo.marker("4"); -verify.completionListContains("follow"); - -goTo.marker("6"); -verify.completionListContains("lead"); -goTo.marker("8"); -verify.completionListContains("follow"); +verify.completions( + { marker: ["2", "6"], exact: ["lead", "isLeader", "isFollower"] }, + { marker: ["4", "8"], exact: ["follow", "isLeader", "isFollower"] }, +); diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionAbsolutePaths.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionAbsolutePaths.ts index 99fffd7a7d6..3bf1ce13125 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionAbsolutePaths.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionAbsolutePaths.ts @@ -26,18 +26,7 @@ // @Filename: e2.js //// /*e2*/ -goTo.marker("0"); -verify.completionListContains("fourslash"); -verify.not.completionListItemsCountIsGreaterThan(1); - -goTo.marker("1"); -verify.completionListContains("fourslash"); -verify.not.completionListItemsCountIsGreaterThan(1); - -goTo.marker("2"); -verify.completionListContains("f1.ts"); -verify.completionListContains("f2.tsx"); -verify.completionListContains("e1.ts"); -verify.completionListContains("folder"); -verify.completionListContains("tests"); -verify.not.completionListItemsCountIsGreaterThan(5); \ No newline at end of file +verify.completions( + { marker: ["0", "1"], exact: "fourslash", isNewIdentifierLocation: true }, + { marker: "2", exact: ["e1.ts", "f1.ts", "f2.tsx", "folder", "tests"], isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts index e25521ed812..81b19359f26 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionBackandForwardSlash.ts @@ -54,10 +54,19 @@ testBlock(12, 'h.ts', "d3"); testBlock(16, 'h.ts', "d3"); testBlock(20, 'h.ts', "d3"); testBlock(24, 'h.ts', "d3"); -verify.completionsAt("28", ["g.ts", "d2"], { isNewIdentifierLocation: true }); +verify.completions({ marker: "28", exact: ["g.ts", "d2"], isNewIdentifierLocation: true }); function testBlock(offset: number, fileName: string, dir: string) { const names = [fileName, dir]; - verify.completionsAt([offset, offset + 1, offset + 2].map(String), names, { isNewIdentifierLocation: true }); - verify.completionsAt(String(offset + 3), names.map(name => ({ name, replacementSpan: test.ranges()[offset / 4] })), { isNewIdentifierLocation: true }); + verify.completions( + { + marker: [offset, offset + 1, offset + 2].map(String), + exact: names, + isNewIdentifierLocation: true, + }, + { + marker: String(offset + 3), + exact: names.map(name => ({ name, replacementSpan: test.ranges()[offset / 4] })), + isNewIdentifierLocation: true, + }); } diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionContext.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionContext.ts index ccab45a2b21..2204afc61fc 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionContext.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionContext.ts @@ -9,13 +9,7 @@ //// /// /*7*/ -for(let m = 0; m < 8; ++m) { - goTo.marker("" + m); - verify.not.completionListItemsCountIsGreaterThan(0); -} - -for(let m of ["8", "9"]) { - goTo.marker(m); - verify.completionListContains("f.ts"); - verify.not.completionListItemsCountIsGreaterThan(1); -} \ No newline at end of file +verify.completions( + { marker: ["0", "1", "2", "3", "4", "5", "6", "7"], exact: undefined, isNewIdentifierLocation: true }, + { marker: ["8", "9"], exact: "f.ts", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionExtensionsAllowJSFalse.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionExtensionsAllowJSFalse.ts index 95a4cd01b60..198a46cdeb9 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionExtensionsAllowJSFalse.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionExtensionsAllowJSFalse.ts @@ -8,24 +8,22 @@ //// /// ({ name, replacementSpan: test.ranges()[idx] })), { isNewIdentifierLocation: true }); -} +const ranges = test.ranges(); +verify.completions( + { + marker: ["0", "1", "2", "3", "7"], + exact: names, + isNewIdentifierLocation: true, + }, + ...markersWithReplacementSpan.map((marker, i): FourSlashInterface.CompletionsOptions => ({ + marker: String(marker), + exact: names.map(name => ({ name, replacementSpan: ranges[i] })), + isNewIdentifierLocation: true, + })), +); diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts index a67310d0349..2922453c89d 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionRelativePaths.ts @@ -32,15 +32,17 @@ //// /// ({ name, replacementSpan: test.ranges()[0] })), { isNewIdentifierLocation: true }); -verify.completionsAt("3", ["h.ts", "d3"].map(name => ({ name, replacementSpan: test.ranges()[1] })), { isNewIdentifierLocation: true }); +verify.completions( + // working dir completions + { marker: ["0", "1", "4"], exact: ["h.ts", "d3"], isNewIdentifierLocation: true }, + { marker: "2", exact: ["h.ts", "d3"].map(name => ({ name, replacementSpan: test.ranges()[0] })), isNewIdentifierLocation: true }, + { marker: "3", exact: ["h.ts", "d3"].map(name => ({ name, replacementSpan: test.ranges()[1] })), isNewIdentifierLocation: true }, -// parent dir completions -verify.completionsAt(["5", "6"], ["g.ts", "d2"], { isNewIdentifierLocation: true }); -verify.completionsAt("7", ["f.ts", "d1"], { isNewIdentifierLocation: true }); + // parent dir completions + { marker: ["5", "6"], exact: ["g.ts", "d2"], isNewIdentifierLocation: true }, + { marker: "7", exact: ["f.ts", "d1"], isNewIdentifierLocation: true }, -// child dir completions -verify.completionsAt(["8", "9"], ["i.ts", "d4"], { isNewIdentifierLocation: true }); -verify.completionsAt(["10", "11"], ["j.ts"], { isNewIdentifierLocation: true }); + // child dir completions + { marker: ["8", "9"], exact: ["i.ts", "d4"], isNewIdentifierLocation: true }, + { marker: ["10", "11"], exact: "j.ts", isNewIdentifierLocation: true }, +); diff --git a/tests/cases/fourslash/tripleSlashRefPathCompletionRootdirs.ts b/tests/cases/fourslash/tripleSlashRefPathCompletionRootdirs.ts index 2eb58646675..9e82be11f21 100644 --- a/tests/cases/fourslash/tripleSlashRefPathCompletionRootdirs.ts +++ b/tests/cases/fourslash/tripleSlashRefPathCompletionRootdirs.ts @@ -35,9 +35,4 @@ // @Filename: e2.js //// /*e2*/ - -goTo.marker("0"); - -verify.completionListContains("module0.ts"); - -verify.not.completionListItemsCountIsGreaterThan(1); \ No newline at end of file +verify.completions({ marker: "0", exact: "module0.ts", isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/tsxCompletion1.ts b/tests/cases/fourslash/tsxCompletion1.ts index f638b0b6e4f..12d62333d84 100644 --- a/tests/cases/fourslash/tsxCompletion1.ts +++ b/tests/cases/fourslash/tsxCompletion1.ts @@ -9,6 +9,4 @@ //// } //// var x =
; -goTo.marker(); -verify.completionListContains('ONE'); -verify.completionListContains('TWO'); +verify.completions({ marker: "", exact: ["ONE", "TWO"] }); diff --git a/tests/cases/fourslash/tsxCompletion11.ts b/tests/cases/fourslash/tsxCompletion11.ts index 5d9c869a9b6..a98b6132850 100644 --- a/tests/cases/fourslash/tsxCompletion11.ts +++ b/tests/cases/fourslash/tsxCompletion11.ts @@ -10,5 +10,4 @@ //// import {Thing} from './exporter'; //// var x1 =
; //// let opt4 = ; -goTo.marker("1"); -verify.completionListContains('propx'); -verify.completionListContains('propString'); -verify.completionListContains('optional'); - -goTo.marker("2"); -verify.completionListContains('propx'); -verify.completionListContains('propString'); - -goTo.marker("3"); -verify.completionListContains("propString") -verify.completionListContains("optional") -verify.not.completionListContains("propx") - -goTo.marker("4"); -verify.completionListContains("propString"); -verify.not.completionListContains("propx"); -verify.not.completionListContains("optional"); - -goTo.marker("5"); -verify.completionListContains('propx'); -verify.completionListContains('propString'); -verify.completionListContains('optional'); \ No newline at end of file +verify.completions( + { marker: ["1", "2", "5"], exact: ["propx", "propString", "optional"] }, + { marker: "3", exact: ["propString", "optional"] }, + { marker: "4", exact: "propString" }, +); diff --git a/tests/cases/fourslash/tsxCompletion13.ts b/tests/cases/fourslash/tsxCompletion13.ts index 9a79de927d2..b1ac2c7af7a 100644 --- a/tests/cases/fourslash/tsxCompletion13.ts +++ b/tests/cases/fourslash/tsxCompletion13.ts @@ -30,33 +30,8 @@ //// let opt = ; //// let opt = ; -goTo.marker("1"); -verify.completionListContains('children'); -verify.completionListContains('className'); -verify.completionListContains('onClick'); -verify.completionListContains('goTo'); - -goTo.marker("2"); -verify.completionListContains('className'); -verify.completionListContains('onClick'); -verify.completionListContains('goTo'); - -goTo.marker("3"); -verify.completionListContains('children'); -verify.completionListContains('className'); -verify.not.completionListContains('goTo'); - -goTo.marker("4"); -verify.completionListContains('children'); -verify.completionListContains('className'); - -goTo.marker("5"); -verify.completionListContains('children'); -verify.completionListContains('className'); -verify.not.completionListContains('onClick'); - -goTo.marker("6"); -verify.completionListContains('children'); -verify.completionListContains('className'); -verify.completionListContains('onClick'); -verify.completionListContains('goTo'); \ No newline at end of file +verify.completions( + { marker: ["1", "6"], exact: ["onClick", "children", "className", "goTo"] }, + { marker: "2", exact: ["onClick", "className", "goTo"] }, + { marker: ["3", "4", "5"], exact: ["children", "className"] }, +); diff --git a/tests/cases/fourslash/tsxCompletion2.ts b/tests/cases/fourslash/tsxCompletion2.ts index d33f9106877..157f8858d35 100644 --- a/tests/cases/fourslash/tsxCompletion2.ts +++ b/tests/cases/fourslash/tsxCompletion2.ts @@ -10,6 +10,4 @@ //// class MyComp { props: { ONE: string; TWO: number } } //// var x = ; -goTo.marker(); -verify.completionListContains('ONE'); -verify.completionListContains('TWO'); +verify.completions({ marker: "", exact: ["ONE", "TWO"] }); diff --git a/tests/cases/fourslash/tsxCompletion3.ts b/tests/cases/fourslash/tsxCompletion3.ts index 5ee712f7e96..08e8be38657 100644 --- a/tests/cases/fourslash/tsxCompletion3.ts +++ b/tests/cases/fourslash/tsxCompletion3.ts @@ -9,6 +9,4 @@ //// } ////
; -goTo.marker(); -verify.completionListContains('two'); -verify.not.completionListContains('one'); +verify.completions({ marker: "", exact: "two" }); diff --git a/tests/cases/fourslash/tsxCompletion4.ts b/tests/cases/fourslash/tsxCompletion4.ts index 6a66c4a898f..536476d4053 100644 --- a/tests/cases/fourslash/tsxCompletion4.ts +++ b/tests/cases/fourslash/tsxCompletion4.ts @@ -10,5 +10,4 @@ //// let bag = { x: 100, y: 200 }; ////
; -goTo.marker(); -verify.completionListContains("ONE"); -verify.completionListContains("TWO"); -verify.not.completionListAllowsNewIdentifier(); \ No newline at end of file +verify.completions({ marker: "", exact: ["ONE", "TWO"] }); diff --git a/tests/cases/fourslash/tsxCompletion6.ts b/tests/cases/fourslash/tsxCompletion6.ts index 5bb01717be7..bdc7823ec92 100644 --- a/tests/cases/fourslash/tsxCompletion6.ts +++ b/tests/cases/fourslash/tsxCompletion6.ts @@ -9,7 +9,4 @@ //// } //// var x =
; -goTo.marker(); - -verify.completionListContains("TWO"); -verify.not.completionListAllowsNewIdentifier(); +verify.completions({ marker: "", exact: "TWO" }); diff --git a/tests/cases/fourslash/tsxCompletion7.ts b/tests/cases/fourslash/tsxCompletion7.ts index ca489b8e0c4..87638f38e38 100644 --- a/tests/cases/fourslash/tsxCompletion7.ts +++ b/tests/cases/fourslash/tsxCompletion7.ts @@ -10,8 +10,4 @@ //// let y = { ONE: '' }; //// var x =
; -goTo.marker(); - -verify.completionListContains("ONE"); -verify.completionListContains("TWO"); -verify.not.completionListAllowsNewIdentifier(); +verify.completions({ marker: "", exact: ["ONE", "TWO"] }); diff --git a/tests/cases/fourslash/tsxCompletion9.ts b/tests/cases/fourslash/tsxCompletion9.ts index 12542cc6b5b..21d2c43f676 100644 --- a/tests/cases/fourslash/tsxCompletion9.ts +++ b/tests/cases/fourslash/tsxCompletion9.ts @@ -13,12 +13,9 @@ //// var x4 =
/*10*/
; ////
//// /*end*/ -//// +//// for (var i = 1; i <= 10; i++) { - goTo.marker(i + ''); - verify.completionListIsEmpty(); + verify.completions({ marker: String(i), exact: undefined }); } - -goTo.marker('end'); -verify.not.completionListIsEmpty(); +verify.completions({ marker: "end", includes: "null" }); diff --git a/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback.ts b/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback.ts index 911fa41470d..b23b7f23c69 100644 --- a/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback.ts +++ b/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback.ts @@ -20,11 +20,10 @@ //// return ( //// //// { user => ( -////

{ user./**/ }

+////

{ user./**/ }

//// )} ////
//// ); //// } -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback1.ts b/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback1.ts index d849948775e..6c805e897d0 100644 --- a/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback1.ts +++ b/tests/cases/fourslash/tsxCompletionInFunctionExpressionOfChildrenCallback1.ts @@ -21,11 +21,10 @@ //// return ( //// //// { user => ( -////

{ user./**/ }

+////

{ user./**/ }

//// )} ////
//// ); //// } -goTo.marker(); -verify.completionListContains('Name'); \ No newline at end of file +verify.completions({ marker: "", exact: "Name" }); diff --git a/tests/cases/fourslash/tsxCompletionNonTagLessThan.ts b/tests/cases/fourslash/tsxCompletionNonTagLessThan.ts index 8fb1501eb50..b2b6a046e6b 100644 --- a/tests/cases/fourslash/tsxCompletionNonTagLessThan.ts +++ b/tests/cases/fourslash/tsxCompletionNonTagLessThan.ts @@ -5,12 +5,7 @@ ////[].map -goTo.marker(); -verify.completionListIsEmpty(); \ No newline at end of file +verify.completions({ marker: "", exact: undefined }); diff --git a/tests/cases/fourslash/typeArgCompletion.ts b/tests/cases/fourslash/typeArgCompletion.ts index 19fe006f26a..a32bab43e93 100644 --- a/tests/cases/fourslash/typeArgCompletion.ts +++ b/tests/cases/fourslash/typeArgCompletion.ts @@ -8,5 +8,4 @@ ////} ////var x1: I1; -goTo.marker(); -verify.completionListContains("Derived"); +verify.completions({ marker: "", includes: "Derived" }); diff --git a/tests/cases/fourslash/unclosedCommentsInConstructor.ts b/tests/cases/fourslash/unclosedCommentsInConstructor.ts index a81bfb1fbf2..ebc532ae44b 100644 --- a/tests/cases/fourslash/unclosedCommentsInConstructor.ts +++ b/tests/cases/fourslash/unclosedCommentsInConstructor.ts @@ -1,8 +1,7 @@ /// ////class Foo { -//// constructor(/*/**/) { } +//// constructor(/* /**/) { } ////} -goTo.marker(); -// verify.completionListIsEmpty(); // TODO: difference between LS and FourSlash \ No newline at end of file +verify.completions({ marker: "", exact: undefined, isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/unclosedStringLiteralErrorRecovery.ts b/tests/cases/fourslash/unclosedStringLiteralErrorRecovery.ts index 88c13954ec0..5c51d897f4a 100644 --- a/tests/cases/fourslash/unclosedStringLiteralErrorRecovery.ts +++ b/tests/cases/fourslash/unclosedStringLiteralErrorRecovery.ts @@ -6,6 +6,5 @@ ////var f = new foo(); ////f./**/ -goTo.marker(); // Error recovery for unclosed string literals -verify.completionListContains('x'); +verify.completions({ marker: "", exact: "x" }); diff --git a/tests/cases/fourslash/underscoreTypings01.ts b/tests/cases/fourslash/underscoreTypings01.ts index e75f3ad61ce..b2c96552dcf 100644 --- a/tests/cases/fourslash/underscoreTypings01.ts +++ b/tests/cases/fourslash/underscoreTypings01.ts @@ -47,6 +47,4 @@ verify.quickInfos({ 12: "(parameter) x: any" }); -goTo.marker('13'); -verify.completionListContains('length'); -verify.not.completionListContains('toFixed'); \ No newline at end of file +verify.completions({ marker: "13", includes: "length", excludes: "toFixed" }); From 672b0e3e16ad18b422dbe0cec5a98fce49881b76 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 29 Oct 2018 11:12:51 -0700 Subject: [PATCH 137/262] Have flatMap return a ReadonlyArray by default (#28205) --- src/compiler/checker.ts | 2 +- src/compiler/core.ts | 23 +++++++++++++++---- src/compiler/transformers/declarations.ts | 2 +- src/compiler/types.ts | 4 ++-- src/compiler/utilities.ts | 6 ++--- src/harness/fourslash.ts | 14 +++++------ src/harness/harness.ts | 2 +- src/server/project.ts | 2 +- src/server/protocol.ts | 2 +- src/server/session.ts | 4 ++-- src/services/codeFixProvider.ts | 2 +- src/services/codefixes/importFixes.ts | 2 +- src/services/codefixes/inferFromUsage.ts | 2 +- src/services/findAllReferences.ts | 18 +++++++++++---- src/services/goToDefinition.ts | 6 ++--- src/services/services.ts | 6 ++--- src/services/types.ts | 10 ++++---- .../reference/api/tsserverlibrary.d.ts | 16 ++++++------- tests/baselines/reference/api/typescript.d.ts | 14 +++++------ 19 files changed, 80 insertions(+), 57 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e209041f9fb..197dc4ccbd5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28090,7 +28090,7 @@ namespace ts { return ts.typeHasCallOrConstructSignatures(type, checker); } - function getRootSymbols(symbol: Symbol): Symbol[] { + function getRootSymbols(symbol: Symbol): ReadonlyArray { const roots = getImmediateRootSymbols(symbol); return roots ? flatMap(roots, getRootSymbols) : [symbol]; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7e9813658f5..6288f30b144 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -511,12 +511,27 @@ namespace ts { * @param array The array to map. * @param mapfn The callback used to map the result into one or more values. */ - export function flatMap(array: ReadonlyArray, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[]; - export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined; - export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] | undefined { + export function flatMap(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): ReadonlyArray { let result: U[] | undefined; if (array) { - result = []; + for (let i = 0; i < array.length; i++) { + const v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + result = addRange(result, v); + } + else { + result = append(result, v); + } + } + } + } + return result || emptyArray; + } + + export function flatMapToMutable(array: ReadonlyArray | undefined, mapfn: (x: T, i: number) => U | ReadonlyArray | undefined): U[] { + const result: U[] = []; + if (array) { for (let i = 0; i < array.length; i++) { const v = mapfn(array[i], i); if (v) { diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 00e787c421b..9ccca4732e8 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1043,7 +1043,7 @@ namespace ts { const modifiers = createNodeArray(ensureModifiers(input, isPrivate)); const typeParameters = ensureTypeParams(input, input.typeParameters); const ctor = getFirstConstructorWithBody(input); - let parameterProperties: PropertyDeclaration[] | undefined; + let parameterProperties: ReadonlyArray | undefined; if (ctor) { const oldDiag = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, param => { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e7d20bfc249..aeb310671ed 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2793,7 +2793,7 @@ namespace ts { export interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. @@ -3079,7 +3079,7 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined; /* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index fa3885d4b76..96b9c3c2f67 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3038,7 +3038,7 @@ namespace ts { return fileDiagnostics.get(fileName) || []; } - const fileDiags: Diagnostic[] = flatMap(filesWithDiagnostics, f => fileDiagnostics.get(f)); + const fileDiags: Diagnostic[] = flatMapToMutable(filesWithDiagnostics, f => fileDiagnostics.get(f)); if (!nonFileDiagnostics.length) { return fileDiags; } @@ -5234,7 +5234,7 @@ namespace ts { } if (isJSDocTypeAlias(node)) { Debug.assert(node.parent.kind === SyntaxKind.JSDocComment); - return flatMap(node.parent.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : undefined) as ReadonlyArray; + return flatMap(node.parent.tags, tag => isJSDocTemplateTag(tag) ? tag.typeParameters : undefined); } if (node.typeParameters) { return node.typeParameters; @@ -7777,7 +7777,7 @@ namespace ts { return `^(${pattern})${terminator}`; } - export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string[] | undefined { + export function getRegularExpressionsForWildcards(specs: ReadonlyArray | undefined, basePath: string, usage: "files" | "directories" | "exclude"): ReadonlyArray | undefined { if (specs === undefined || specs.length === 0) { return undefined; } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 82ef60e7fbc..a3721dd29f4 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -491,7 +491,7 @@ namespace FourSlash { ]; } - private getAllDiagnostics(): ts.Diagnostic[] { + private getAllDiagnostics(): ReadonlyArray { return ts.flatMap(this.languageServiceAdapterHost.getFilenames(), fileName => { if (!ts.isAnySupportedFileExtension(fileName)) { return []; @@ -532,7 +532,7 @@ namespace FourSlash { predicate(start!, start! + length!, startMarker.position, endMarker === undefined ? undefined : endMarker.position)); // TODO: GH#18217 } - private printErrorLog(expectErrors: boolean, errors: ts.Diagnostic[]) { + private printErrorLog(expectErrors: boolean, errors: ReadonlyArray): void { if (expectErrors) { Harness.IO.log("Expected error not found. Error list is:"); } @@ -613,7 +613,7 @@ namespace FourSlash { this.verifyGoToX(arg0, endMarkerNames, () => this.getGoToDefinitionAndBoundSpan()); } - private getGoToDefinition(): ts.DefinitionInfo[] { + private getGoToDefinition(): ReadonlyArray { return this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; } @@ -626,7 +626,7 @@ namespace FourSlash { this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition)); } - private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToX(arg0: any, endMarkerNames: ArrayOrSingle | undefined, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { if (endMarkerNames) { this.verifyGoToXPlain(arg0, endMarkerNames, getDefs); } @@ -646,7 +646,7 @@ namespace FourSlash { } } - private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => ts.DefinitionInfo[] | ts.DefinitionInfoAndBoundSpan | undefined) { + private verifyGoToXPlain(startMarkerNames: ArrayOrSingle, endMarkerNames: ArrayOrSingle, getDefs: () => ReadonlyArray | ts.DefinitionInfoAndBoundSpan | undefined) { for (const start of toArray(startMarkerNames)) { this.verifyGoToXSingle(start, endMarkerNames, getDefs); } @@ -1890,7 +1890,7 @@ Actual: ${stringify(fullActual)}`); public verifyRangesInImplementationList(markerName: string) { this.goToMarker(markerName); - const implementations: ImplementationLocationInformation[] = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; + const implementations: ReadonlyArray = this.languageService.getImplementationAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; if (!implementations || !implementations.length) { this.raiseError("verifyRangesInImplementationList failed - expected to find at least one implementation location but got 0"); } @@ -2383,7 +2383,7 @@ Actual: ${stringify(fullActual)}`); * Rerieves a codefix satisfying the parameters, or undefined if no such codefix is found. * @param fileName Path to file where error should be retrieved from. */ - private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): ts.CodeFixAction[] { + private getCodeFixes(fileName: string, errorCode?: number, preferences: ts.UserPreferences = ts.emptyOptions): ReadonlyArray { const diagnosticsForCodeFix = this.getDiagnostics(fileName, /*includeSuggestions*/ true).map(diagnostic => ({ start: diagnostic.start, length: diagnostic.length, diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 5896ff3a782..c19c1ab141e 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -490,7 +490,7 @@ namespace Harness { getExecutingFilePath(): string; getWorkspaceRoot(): string; exit(exitCode?: number): void; - readDirectory(path: string, extension?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readDirectory(path: string, extension?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): ReadonlyArray; getAccessibleFileSystemEntries(dirname: string): ts.FileSystemEntries; tryEnableSourceMapsForHost?(): void; getEnvironmentVariable?(name: string): string; diff --git a/src/server/project.ts b/src/server/project.ts index b87ddc9fb7f..ecf62b724ec 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -548,7 +548,7 @@ namespace ts.server { } getExternalFiles(): SortedReadonlyArray { - return toSortedArray(flatMap(this.plugins, plugin => { + return toSortedArray(flatMapToMutable(this.plugins, plugin => { if (typeof plugin.getExternalFiles !== "function") return; try { return plugin.getExternalFiles(this); diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 14b2fa7c43c..81b7af72e5b 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1023,7 +1023,7 @@ namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. diff --git a/src/server/session.ts b/src/server/session.ts index efd369edb69..54caf953ee6 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -267,7 +267,7 @@ namespace ts.server { projects: Projects, action: (project: Project, value: T) => ReadonlyArray | U | undefined, ): U[] { - const outputs = flatMap(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); + const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); if (!isArray(projects) && projects.symLinkedProjects) { projects.symLinkedProjects.forEach((projects, path) => { const value = getValue(path as Path); @@ -1230,7 +1230,7 @@ namespace ts.server { const nameSpan = nameInfo && nameInfo.textSpan; const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; const symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; - const refs: protocol.ReferencesResponseItem[] = flatMap(references, referencedSymbol => + const refs: ReadonlyArray = flatMap(references, referencedSymbol => referencedSymbol.references.map(({ fileName, textSpan, isWriteAccess, isDefinition }): protocol.ReferencesResponseItem => { const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(fileName)); const start = scriptInfo.positionToLineOffset(textSpan.start); diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index ad4e37974b3..8d42fdcc6c2 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -62,7 +62,7 @@ namespace ts { return arrayFrom(errorCodeToFixes.keys()); } - export function getFixes(context: CodeFixContext): CodeFixAction[] { + export function getFixes(context: CodeFixContext): ReadonlyArray { return flatMap(errorCodeToFixes.get(String(context.errorCode)) || emptyArray, f => f.getCodeActions(context)); } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 2f6d68c52f4..14bfc8b2761 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -289,7 +289,7 @@ namespace ts.codefix { // `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 to keep the shortest paths first - return choicesForEachExportingModule.sort((a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); + return sort(choicesForEachExportingModule, (a, b) => a.moduleSpecifier.length - b.moduleSpecifier.length); } function getFixesForAddImport( diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index cef820bbf59..997f0988c33 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -228,7 +228,7 @@ namespace ts.codefix { function addJSDocTags(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parent: HasJSDoc, newTags: ReadonlyArray): void { const comments = mapDefined(parent.jsDoc, j => j.comment); - const oldTags = flatMap(parent.jsDoc, j => j.tags); + const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags); const unmergedNewTags = newTags.filter(newTag => !oldTags || !oldTags.some((tag, i) => { const merged = tryMergeJsdocTags(tag, newTag); if (merged) oldTags[i] = merged; diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 41aae6ae825..b7ded40c28f 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1,8 +1,8 @@ /* @internal */ namespace ts.FindAllReferences { export interface SymbolAndEntries { - definition: Definition | undefined; - references: Entry[]; + readonly definition: Definition | undefined; + readonly references: ReadonlyArray; } export const enum DefinitionKind { Symbol, Label, Keyword, This, String } @@ -60,7 +60,7 @@ namespace ts.FindAllReferences { return map(referenceEntries, entry => toImplementationLocation(entry, checker)); } - function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): Entry[] | undefined { + function getImplementationReferenceEntries(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray, node: Node, position: number): ReadonlyArray | undefined { if (node.kind === SyntaxKind.SourceFile) { return undefined; } @@ -94,11 +94,19 @@ namespace ts.FindAllReferences { export type ToReferenceOrRenameEntry = (entry: Entry, originalNode: Node) => T; - export function getReferenceEntriesForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName)): Entry[] | undefined { + export function getReferenceEntriesForNode( + position: number, + node: Node, + program: Program, + sourceFiles: ReadonlyArray, + cancellationToken: CancellationToken, + options: Options = {}, + sourceFilesSet: ReadonlyMap = arrayToSet(sourceFiles, f => f.fileName), + ): ReadonlyArray | undefined { return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } - function flattenEntries(referenceSymbols: SymbolAndEntries[] | undefined): Entry[] | undefined { + function flattenEntries(referenceSymbols: SymbolAndEntries[] | undefined): ReadonlyArray | undefined { return referenceSymbols && flatMap(referenceSymbols, r => r.references); } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 02d590bb8b6..8f495aadfe1 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -1,6 +1,6 @@ /* @internal */ namespace ts.GoToDefinition { - export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined { + export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { const reference = getReferenceAtPosition(sourceFile, position, program); if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; @@ -129,7 +129,7 @@ namespace ts.GoToDefinition { } /// Goto type - export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] | undefined { + export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): ReadonlyArray | undefined { const node = getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; @@ -145,7 +145,7 @@ namespace ts.GoToDefinition { return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); } - function definitionFromType(type: Type, checker: TypeChecker, node: Node): DefinitionInfo[] { + function definitionFromType(type: Type, checker: TypeChecker, node: Node): ReadonlyArray { return flatMap(type.isUnion() && !(type.flags & TypeFlags.Enum) ? type.types : [type], t => t.symbol && getDefinitionFromSymbol(checker, t.symbol, node)); } diff --git a/src/services/services.ts b/src/services/services.ts index 725decf18f2..a91836e6687 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1496,7 +1496,7 @@ namespace ts { } /// Goto definition - function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined { + function getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { synchronizeHostData(); return GoToDefinition.getDefinitionAtPosition(program, getValidSourceFile(fileName), position); } @@ -1506,7 +1506,7 @@ namespace ts { return GoToDefinition.getDefinitionAndBoundSpan(program, getValidSourceFile(fileName), position); } - function getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined { + function getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined { synchronizeHostData(); return GoToDefinition.getTypeDefinitionAtPosition(program.getTypeChecker(), getValidSourceFile(fileName), position); } @@ -1519,7 +1519,7 @@ namespace ts { } /// References and Occurrences - function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined { + function getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined { return flatMap(getDocumentHighlights(fileName, position, [fileName]), entry => entry.highlightSpans.map(highlightSpan => ({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, diff --git a/src/services/types.ts b/src/services/types.ts index 21ce83070df..a43da2b6465 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -289,19 +289,19 @@ namespace ts { getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 15606263db0..87bbf1a1cd2 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1755,7 +1755,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -1925,7 +1925,7 @@ declare namespace ts { typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -4696,16 +4696,16 @@ declare namespace ts { getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -6405,7 +6405,7 @@ declare namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. */ diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index ad934eef56b..fd4f5752614 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1755,7 +1755,7 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): ReadonlyArray; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. @@ -1925,7 +1925,7 @@ declare namespace ts { typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; - getRootSymbols(symbol: Symbol): Symbol[]; + getRootSymbols(symbol: Symbol): ReadonlyArray; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. @@ -4696,16 +4696,16 @@ declare namespace ts { getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; + getImplementationAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + getOccurrencesAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; From 24febc2445c39c16ab1b018e18b067b942dcef83 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 29 Oct 2018 11:56:49 -0700 Subject: [PATCH 138/262] Allow to combine --resolveJsonModule with --isolatedModules (#28207) --- src/compiler/program.ts | 6 +++--- .../reference/isolatedModules_resolveJsonModule.js | 12 ++++++++++++ .../isolatedModules_resolveJsonModule.symbols | 8 ++++++++ .../isolatedModules_resolveJsonModule.types | 8 ++++++++ .../compiler/isolatedModules_resolveJsonModule.ts | 8 ++++++++ 5 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/isolatedModules_resolveJsonModule.js create mode 100644 tests/baselines/reference/isolatedModules_resolveJsonModule.symbols create mode 100644 tests/baselines/reference/isolatedModules_resolveJsonModule.types create mode 100644 tests/cases/compiler/isolatedModules_resolveJsonModule.ts diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 3e927c0b75f..85c6b27f4ec 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2667,13 +2667,13 @@ namespace ts { const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; - const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !f.isDeclarationFile ? f : undefined); + const firstNonAmbientExternalModuleSourceFile = find(files, f => isExternalModule(f) && !f.isDeclarationFile); if (options.isolatedModules) { if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { createDiagnosticForOptionName(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } - const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !f.isDeclarationFile ? f : undefined); + const firstNonExternalModuleSourceFile = find(files, f => !isExternalModule(f) && !f.isDeclarationFile && f.scriptKind !== ScriptKind.JSON); if (firstNonExternalModuleSourceFile) { const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); @@ -2716,7 +2716,7 @@ namespace ts { const dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure - if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) { + if (options.outDir && dir === "" && files.some(file => getRootLength(file.fileName) > 1)) { createDiagnosticForOptionName(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } diff --git a/tests/baselines/reference/isolatedModules_resolveJsonModule.js b/tests/baselines/reference/isolatedModules_resolveJsonModule.js new file mode 100644 index 00000000000..cdff02c07f0 --- /dev/null +++ b/tests/baselines/reference/isolatedModules_resolveJsonModule.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/isolatedModules_resolveJsonModule.ts] //// + +//// [a.ts] +import j = require("./j.json"); + +//// [j.json] +{} + + +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/isolatedModules_resolveJsonModule.symbols b/tests/baselines/reference/isolatedModules_resolveJsonModule.symbols new file mode 100644 index 00000000000..6282706d3aa --- /dev/null +++ b/tests/baselines/reference/isolatedModules_resolveJsonModule.symbols @@ -0,0 +1,8 @@ +=== /a.ts === +import j = require("./j.json"); +>j : Symbol(j, Decl(a.ts, 0, 0)) + +=== /j.json === +{} +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModules_resolveJsonModule.types b/tests/baselines/reference/isolatedModules_resolveJsonModule.types new file mode 100644 index 00000000000..c63dd52da1a --- /dev/null +++ b/tests/baselines/reference/isolatedModules_resolveJsonModule.types @@ -0,0 +1,8 @@ +=== /a.ts === +import j = require("./j.json"); +>j : {} + +=== /j.json === +{} +>{} : {} + diff --git a/tests/cases/compiler/isolatedModules_resolveJsonModule.ts b/tests/cases/compiler/isolatedModules_resolveJsonModule.ts new file mode 100644 index 00000000000..51eec55d172 --- /dev/null +++ b/tests/cases/compiler/isolatedModules_resolveJsonModule.ts @@ -0,0 +1,8 @@ +// @isolatedModules: true +// @resolveJsonModule: true + +// @Filename: /a.ts +import j = require("./j.json"); + +// @Filename: /j.json +{} From d32c1b091a110b1921cc48c401a269d23da994d1 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 29 Oct 2018 11:25:28 -0700 Subject: [PATCH 139/262] Ignore any changes to file or folder that are in node_modules and start with "." Fixes #27673 --- src/compiler/resolutionCache.ts | 7 +++++ src/server/editorServices.ts | 2 ++ .../unittests/tsserverProjectSystem.ts | 27 +++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index b22d90a76f6..d293ce8dab6 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -71,6 +71,10 @@ namespace ts { nonRecursive?: boolean; } + export function isPathInNodeModulesStartingWithDot(path: Path) { + return stringContains(path, "/node_modules/."); + } + export const maxNumberOfFilesToIterateForInvalidation = 256; type GetResolutionWithResolvedFileName = @@ -688,6 +692,9 @@ namespace ts { isChangedFailedLookupLocation = location => isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); } else { + // If something to do with folder/file starting with "." in node_modules folder, skip it + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return false; + // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path const dirOfFileOrDirectory = getDirectoryPath(fileOrDirectoryPath); diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 1a7e668b25e..64549c50b94 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -2040,6 +2040,8 @@ namespace ts.server { watchDir, (fileOrDirectory) => { const fileOrDirectoryPath = this.toPath(fileOrDirectory); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; + // Has extension Debug.assert(result.refCount > 0); if (watchDir === fileOrDirectoryPath) { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 38d2d4867a0..a348656c24c 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -9039,6 +9039,33 @@ export const x = 10;` verifyModuleResolution(/*useNodeFile*/ false); }); }); + + it("ignores files/folder changes in node_modules that start with '.'", () => { + const projectPath = "/user/username/projects/project"; + const file1: File = { + path: `${projectPath}/test.js`, + content: `import { x } from "somemodule";` + }; + const file2: File = { + path: `${projectPath}/node_modules/somemodule/index.d.ts`, + content: `export const x = 10;` + }; + const files = [libFile, file1, file2]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + checkNumberOfProjects(service, { inferredProjects: 1 }); + const project = service.inferredProjects[0]; + (project as ResolutionCacheHost).maxNumberOfFilesToIterateForInvalidation = 1; + host.checkTimeoutQueueLength(0); + + const npmCacheFile: File = { + path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.json`, + content: JSON.stringify({ something: 10 }) + }; + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); }); describe("tsserverProjectSystem watchDirectories implementation", () => { From 60efb659313f92982ab84e33cc695304c277e392 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 29 Oct 2018 13:23:33 -0700 Subject: [PATCH 140/262] infer-from-usage suggestions can't be ignored, and always do something when invoked. (#28206) * Do not ts-ignore noImplicitAny suggestions Still need to write tests. * Add tests * More tests * Update baselines --- src/compiler/checker.ts | 10 +-- src/compiler/diagnosticMessages.json | 33 ++++++++ src/services/codefixes/inferFromUsage.ts | 75 +++++++++++++++---- .../fourslash/annotateWithTypeFromJSDoc1.ts | 3 +- .../fourslash/annotateWithTypeFromJSDoc10.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc12.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc15.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc17.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc18.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc19.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc22.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc3.ts | 9 ++- .../fourslash/annotateWithTypeFromJSDoc4.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc6.ts | 1 + .../fourslash/annotateWithTypeFromJSDoc7.ts | 1 + .../codeFixConvertToMappedObjectType12.ts | 4 +- .../codeFixForgottenThisPropertyAccess02.ts | 1 + .../codeFixInferFromUsageAlwaysInfer.ts | 11 +++ .../codeFixInferFromUsageAlwaysInferJS.ts | 18 +++++ .../codeFixInferFromUsageVariable2.ts | 2 +- .../codeFixInferFromUsageVariable3.ts | 13 ++++ .../codeFixInferFromUsageVariable3JS.ts | 22 ++++++ .../codeFixUnusedIdentifier_suggestion.ts | 12 ++- .../incompleteFunctionCallCodefix.ts | 5 +- .../incompleteFunctionCallCodefix2.ts | 4 +- .../noSuggestionDiagnosticsOnParseError.ts | 4 +- .../fourslash/unusedClassInNamespace2.ts | 2 +- .../fourslash/unusedLocalsInFunction4.ts | 2 +- .../fourslash/unusedLocalsInMethodFS1.ts | 2 +- .../fourslash/unusedLocalsInMethodFS2.ts | 2 +- .../cases/fourslash/unusedVariableInClass2.ts | 1 + .../fourslash/unusedVariableInNamespace2.ts | 1 + .../fourslash/unusedVariableInNamespace3.ts | 1 + 33 files changed, 210 insertions(+), 37 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageAlwaysInfer.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageAlwaysInferJS.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageVariable3.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageVariable3JS.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 197dc4ccbd5..d2464652919 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13367,12 +13367,12 @@ namespace ts { case SyntaxKind.BinaryExpression: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - diagnostic = Diagnostics.Member_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.Parameter: diagnostic = (declaration).dotDotDotToken ? - Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - Diagnostics.Parameter_0_implicitly_has_an_1_type; + noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : + noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.BindingElement: diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type; @@ -13388,7 +13388,7 @@ namespace ts { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } - diagnostic = Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + diagnostic = noImplicitAny ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type : Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.MappedType: if (noImplicitAny) { @@ -13396,7 +13396,7 @@ namespace ts { } return; default: - diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; + diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; } errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 558c45bf2af..37cab0359d4 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -4041,6 +4041,39 @@ "category": "Error", "code": 7042 }, + "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7043 + }, + "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7044 + }, + "Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7045 + }, + "Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7046 + }, + "Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7047 + }, + "Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage.": { + "category": "Suggestion", + "code": 7048 + }, + "Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage.": { + "category": "Suggestion", + "code": 7049 + }, + "'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage.": { + "category": "Suggestion", + "code": 7050 + }, + "You cannot rename this element.": { "category": "Error", "code": 8000 diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 997f0988c33..834228f7884 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -21,6 +21,27 @@ namespace ts.codefix { // Property declarations Diagnostics.Member_0_implicitly_has_an_1_type.code, + + //// Suggestions + // Variable declarations + Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + + // Variable uses + Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Parameter declarations + Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Get Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + + // Set Accessor declarations + Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + + // Property declarations + Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, ]; registerCodeFix({ errorCodes, @@ -47,20 +68,46 @@ namespace ts.codefix { function getDiagnostic(errorCode: number, token: Node): DiagnosticMessage { switch (errorCode) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return isSetAccessorDeclaration(getContainingFunction(token)!) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Infer_parameter_types_from_usage; default: return Diagnostics.Infer_type_of_0_from_usage; } } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode: number) { + switch (errorCode) { + case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } const { parent } = token; + errorCode = mapSuggestionDiagnostic(errorCode); switch (errorCode) { // Variable and Property declarations case Diagnostics.Member_0_implicitly_has_an_1_type.code: @@ -71,7 +118,7 @@ namespace ts.codefix { } if (isPropertyAccessExpression(parent)) { const type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); - const typeNode = type && getTypeNodeIfAccessible(type, parent, program, host); + const typeNode = getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags const typeTag = createJSDocTypeTag(createJSDocTypeExpression(typeNode), /*comment*/ ""); @@ -107,7 +154,7 @@ namespace ts.codefix { case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); - annotateParameters(changes, param, containingFunction, sourceFile, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); return param; } return undefined; @@ -152,7 +199,7 @@ namespace ts.codefix { return false; } - function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { + function annotateParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } @@ -160,7 +207,7 @@ namespace ts.codefix { const parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || containingFunction.parameters.map(p => ({ declaration: p, - type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : undefined + type: isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() })); Debug.assert(containingFunction.parameters.length === parameterInferences.length); @@ -179,8 +226,10 @@ namespace ts.codefix { function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { - const type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken) || - inferTypeForVariableFromUsage(param.name, program, cancellationToken); + let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } if (isInJSFile(setAccessorDeclaration)) { annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); } @@ -190,8 +239,8 @@ namespace ts.codefix { } } - function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type | undefined, program: Program, host: LanguageServiceHost): void { - const typeNode = type && getTypeNodeIfAccessible(type, declaration, program, host); + function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost): void { + const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { const parent = isVariableDeclaration(declaration) ? tryCast(declaration.parent.parent, isVariableStatement) : declaration; @@ -285,7 +334,7 @@ namespace ts.codefix { entry.kind !== FindAllReferences.EntryKind.Span ? tryCast(entry.node, isIdentifier) : undefined); } - function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type | undefined { + function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type { return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); } @@ -307,7 +356,7 @@ namespace ts.codefix { interface ParameterInference { readonly declaration: ParameterDeclaration; - readonly type?: Type; + readonly type: Type; readonly isOptional?: boolean; } @@ -329,13 +378,13 @@ namespace ts.codefix { stringIndexContext?: UsageContext; } - export function inferTypeFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type | undefined { + export function inferTypeFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type { const usageContext: UsageContext = {}; for (const reference of references) { cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - return getTypeFromUsageContext(usageContext, checker); + return getTypeFromUsageContext(usageContext, checker) || checker.getAnyType(); } export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): ParameterInference[] | undefined { @@ -374,7 +423,7 @@ namespace ts.codefix { } } if (!types.length) { - return { declaration: parameter }; + return { declaration: parameter, type: checker.getAnyType() }; } const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); return { diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts index 5e18925fdfe..f57c1a8101b 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc1.ts @@ -6,10 +6,11 @@ verify.getSuggestionDiagnostics([ { message: "JSDoc types may be moved to TypeScript types.", code: 80004 }, - { message: "Variable 'x' implicitly has an 'any' type.", code: 7005 }]); + { message: "Variable 'x' implicitly has an 'any' type, but a better type may be inferred from usage.", code: 7043 }]); verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `/** @type {number} */ var x: number;`, diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc10.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc10.ts index 2bd1df5c6e6..98cc31e3207 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc10.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc10.ts @@ -8,6 +8,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `/** * @param {?} x diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc12.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc12.ts index 2152355df8b..ec1ab370222 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc12.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc12.ts @@ -11,6 +11,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `class C { /** diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc15.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc15.ts index 9d26eaa8cde..b278b50d6e1 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc15.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc15.ts @@ -17,6 +17,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 9, newFileContent: `/** * @param {Boolean} x diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc17.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc17.ts index a4453da8825..c452dd4516f 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc17.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc17.ts @@ -9,6 +9,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `class C { /** diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc18.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc18.ts index 685287f2092..9fc2e966028 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc18.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc18.ts @@ -6,6 +6,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `class C { /** @param {number} value */ diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc19.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc19.ts index 754d29d0e46..cdb057d8baa 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc19.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc19.ts @@ -11,6 +11,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 2, newFileContent: `/** * @template T diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc22.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc22.ts index 9163805bfcf..98ccf84c3d6 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc22.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc22.ts @@ -9,6 +9,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 2, newFileContent: ` /** @param {Object} sb diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts index 7e064f8dae4..f7d0522018a 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc3.ts @@ -13,13 +13,14 @@ const [r0, r1, r2, r3, r4] = test.ranges(); verify.getSuggestionDiagnostics([ {message: "JSDoc types may be moved to TypeScript types.", code: 80004, range: r0}, - {message: "Parameter 'x' implicitly has an 'any' type.", code: 7006, range: r1 }, - {message: "Parameter 'y' implicitly has an 'any' type.", code: 7006, range: r2 }, - {message: "Parameter 'alpha' implicitly has an 'any' type.", code: 7006, range: r3 }, - {message: "Parameter 'beta' implicitly has an 'any' type.", code: 7006, range: r4 }]); + {message: "Parameter 'x' implicitly has an 'any' type, but a better type may be inferred from usage.", code: 7044, range: r1 }, + {message: "Parameter 'y' implicitly has an 'any' type, but a better type may be inferred from usage.", code: 7044, range: r2 }, + {message: "Parameter 'alpha' implicitly has an 'any' type, but a better type may be inferred from usage.", code: 7044, range: r3 }, + {message: "Parameter 'beta' implicitly has an 'any' type, but a better type may be inferred from usage.", code: 7044, range: r4 }]); verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: // TODO: GH#22358 `/** diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc4.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc4.ts index c6010bf6cd0..4421afbd867 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc4.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc4.ts @@ -15,6 +15,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 7, newFileContent: `/** * @param {*} x diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc6.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc6.ts index 9d11eb8d445..dbb75590fb2 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc6.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc6.ts @@ -7,6 +7,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `declare class C { /** @type {number | null} */ diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc7.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc7.ts index ba3bd7d47a0..0d43bde45d4 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc7.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc7.ts @@ -10,6 +10,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `/** * @param {number} x diff --git a/tests/cases/fourslash/codeFixConvertToMappedObjectType12.ts b/tests/cases/fourslash/codeFixConvertToMappedObjectType12.ts index 6374dc43dac..d4014463ab2 100644 --- a/tests/cases/fourslash/codeFixConvertToMappedObjectType12.ts +++ b/tests/cases/fourslash/codeFixConvertToMappedObjectType12.ts @@ -9,4 +9,6 @@ //// readonly [prop: K]?: any; //// } -verify.not.codeFixAvailable() +verify.codeFixAvailable([ + { "description": "Infer type of 'any' from usage" } +]) diff --git a/tests/cases/fourslash/codeFixForgottenThisPropertyAccess02.ts b/tests/cases/fourslash/codeFixForgottenThisPropertyAccess02.ts index 60d15fb259c..6f6c6f5510d 100644 --- a/tests/cases/fourslash/codeFixForgottenThisPropertyAccess02.ts +++ b/tests/cases/fourslash/codeFixForgottenThisPropertyAccess02.ts @@ -8,5 +8,6 @@ verify.codeFix({ description: "Add 'this.' to unresolved variable", + index: 0, newRangeContent: "this.foo = 10", }); diff --git a/tests/cases/fourslash/codeFixInferFromUsageAlwaysInfer.ts b/tests/cases/fourslash/codeFixInferFromUsageAlwaysInfer.ts new file mode 100644 index 00000000000..7e83eb68fbe --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageAlwaysInfer.ts @@ -0,0 +1,11 @@ +/// +// @noImplicitAny: false +////function coll(callback) { +////} + verify.codeFix({ + description: "Infer parameter types from usage", + index: 0, + newFileContent: +`function coll(callback: any) { +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageAlwaysInferJS.ts b/tests/cases/fourslash/codeFixInferFromUsageAlwaysInferJS.ts new file mode 100644 index 00000000000..53482451d84 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageAlwaysInferJS.ts @@ -0,0 +1,18 @@ +/// +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: false +// @Filename: important.js +////function coll(callback) { +////} + verify.codeFix({ + description: "Infer parameter types from usage", + index: 0, + newFileContent: +`/** + * @param {any} callback + */ +function coll(callback) { +}`, +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable2.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable2.ts index bf8e2bb07e5..6034adef2d7 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageVariable2.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable2.ts @@ -10,4 +10,4 @@ verify.rangeAfterCodeFix(`var x: number; function f() { x++; } -`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 1); \ No newline at end of file +`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 1); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable3.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable3.ts new file mode 100644 index 00000000000..390d8c962fb --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable3.ts @@ -0,0 +1,13 @@ +/// + +// @noImplicitAny: false +////[|var x; +////function f() { +//// x++; +////}|] + +verify.rangeAfterCodeFix(`var x: number; +function f() { + x++; +} +`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable3JS.ts new file mode 100644 index 00000000000..83a40c396b0 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable3JS.ts @@ -0,0 +1,22 @@ +/// + +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @noImplicitAny: false +// @Filename: important.js + +////[|function f(foo) { +//// foo += 2 +//// return foo +////}|] + + +verify.rangeAfterCodeFix(`/** + * @param {number} foo + */ +function f(foo) { + foo += 2 + return foo +} +`); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts index a456299c68a..9f9eb992ade 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_suggestion.ts @@ -7,9 +7,9 @@ const [r0, r1] = test.ranges(); verify.getSuggestionDiagnostics([ { - message: "Parameter 'p' implicitly has an 'any' type.", + message: "Parameter 'p' implicitly has an 'any' type, but a better type may be inferred from usage.", range: r0, - code: 7006, + code: 7044, }, { message: "'p' is declared but its value is never read.", @@ -26,5 +26,9 @@ verify.getSuggestionDiagnostics([ ]); verify.codeFixAvailable( - ["Remove declaration for: 'p'", "Prefix 'p' with an underscore", "Remove declaration for: 'x'"] - .map(description => ({ description }))); + [ + "Infer parameter types from usage", + "Remove declaration for: 'p'", + "Prefix 'p' with an underscore", + "Remove declaration for: 'x'" + ].map(description => ({ description }))); diff --git a/tests/cases/fourslash/incompleteFunctionCallCodefix.ts b/tests/cases/fourslash/incompleteFunctionCallCodefix.ts index 9935ee854f3..c501a450204 100644 --- a/tests/cases/fourslash/incompleteFunctionCallCodefix.ts +++ b/tests/cases/fourslash/incompleteFunctionCallCodefix.ts @@ -6,4 +6,7 @@ ////} ////f( -verify.not.codeFixAvailable(); +goTo.marker('1'); +verify.codeFixAvailable([ + { "description": "Infer parameter types from usage" } +]); diff --git a/tests/cases/fourslash/incompleteFunctionCallCodefix2.ts b/tests/cases/fourslash/incompleteFunctionCallCodefix2.ts index bfea758b2da..540cb0c626a 100644 --- a/tests/cases/fourslash/incompleteFunctionCallCodefix2.ts +++ b/tests/cases/fourslash/incompleteFunctionCallCodefix2.ts @@ -3,4 +3,6 @@ // @noImplicitAny: true ////function f(new C(100, 3, undefined) -verify.codeFixAvailable([]); // Parse error, so no unused diagnostics +verify.codeFixAvailable([ + { "description": "Infer parameter types from usage" } +]); // Parse error, so no unused diagnostics diff --git a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts index f992f4c8e8e..c36d5352e7f 100644 --- a/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts +++ b/tests/cases/fourslash/noSuggestionDiagnosticsOnParseError.ts @@ -6,8 +6,8 @@ // Only give suggestions for nodes that do NOT have parse errors verify.getSuggestionDiagnostics([{ - message: "Variable 'd' implicitly has an 'any' type.", - code: 7005, + message: "Variable 'd' implicitly has an 'any' type, but a better type may be inferred from usage.", + code: 7043, range: { fileName: "/a.ts", pos: 23, diff --git a/tests/cases/fourslash/unusedClassInNamespace2.ts b/tests/cases/fourslash/unusedClassInNamespace2.ts index 0b6b7504633..0f87f9f2938 100644 --- a/tests/cases/fourslash/unusedClassInNamespace2.ts +++ b/tests/cases/fourslash/unusedClassInNamespace2.ts @@ -11,5 +11,5 @@ verify.rangeAfterCodeFix(`namespace greeter { export class class2 { } -}`); +}`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/unusedLocalsInFunction4.ts b/tests/cases/fourslash/unusedLocalsInFunction4.ts index 62d128ea9e7..2c511f456d7 100644 --- a/tests/cases/fourslash/unusedLocalsInFunction4.ts +++ b/tests/cases/fourslash/unusedLocalsInFunction4.ts @@ -6,4 +6,4 @@ //// use(y, z); ////} -verify.rangeAfterCodeFix("var y = 0,z = 1;"); +verify.rangeAfterCodeFix("var y = 0,z = 1;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/unusedLocalsInMethodFS1.ts b/tests/cases/fourslash/unusedLocalsInMethodFS1.ts index ecfb7455276..1eb261ee777 100644 --- a/tests/cases/fourslash/unusedLocalsInMethodFS1.ts +++ b/tests/cases/fourslash/unusedLocalsInMethodFS1.ts @@ -9,4 +9,4 @@ //// } ////} -verify.rangeAfterCodeFix("var y = 10;"); +verify.rangeAfterCodeFix("var y = 10;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/unusedLocalsInMethodFS2.ts b/tests/cases/fourslash/unusedLocalsInMethodFS2.ts index d06e803bf7f..095e80e9fe9 100644 --- a/tests/cases/fourslash/unusedLocalsInMethodFS2.ts +++ b/tests/cases/fourslash/unusedLocalsInMethodFS2.ts @@ -9,4 +9,4 @@ //// } ////} -verify.rangeAfterCodeFix("var y;"); +verify.rangeAfterCodeFix("var y;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/unusedVariableInClass2.ts b/tests/cases/fourslash/unusedVariableInClass2.ts index 2e6b382698c..1fde857253a 100644 --- a/tests/cases/fourslash/unusedVariableInClass2.ts +++ b/tests/cases/fourslash/unusedVariableInClass2.ts @@ -8,5 +8,6 @@ verify.codeFix({ description: "Remove declaration for: 'greeting'", + index: 0, newRangeContent: "public greeting1;\n", }); diff --git a/tests/cases/fourslash/unusedVariableInNamespace2.ts b/tests/cases/fourslash/unusedVariableInNamespace2.ts index 2719fea1b21..6123555fc8a 100644 --- a/tests/cases/fourslash/unusedVariableInNamespace2.ts +++ b/tests/cases/fourslash/unusedVariableInNamespace2.ts @@ -10,5 +10,6 @@ verify.codeFix({ description: "Remove declaration for: 'b'", + index: 0, newRangeContent: 'let a = "dummy entry", c = 0;', }); diff --git a/tests/cases/fourslash/unusedVariableInNamespace3.ts b/tests/cases/fourslash/unusedVariableInNamespace3.ts index a542b531410..3503bae4e6a 100644 --- a/tests/cases/fourslash/unusedVariableInNamespace3.ts +++ b/tests/cases/fourslash/unusedVariableInNamespace3.ts @@ -10,5 +10,6 @@ verify.codeFix({ description: "Remove declaration for: 'c'", + index: 0, newRangeContent: 'let a = "dummy entry", b;', }); From 1fbabd5534c707fc74c37583c8a05d507238d87a Mon Sep 17 00:00:00 2001 From: Mine Starks <16928427+minestarks@users.noreply.github.com> Date: Mon, 29 Oct 2018 13:56:51 -0700 Subject: [PATCH 141/262] Merge pull request #28106 from minestarks/configure-plugins configurePlugins command for tsserver --- src/harness/client.ts | 4 ++ src/harness/fourslash.ts | 18 +++++- src/harness/harnessLanguageService.ts | 30 +++++++++ src/server/editorServices.ts | 16 ++++- src/server/project.ts | 63 ++++++++++++------- src/server/protocol.ts | 11 ++++ src/server/session.ts | 8 +++ .../reference/api/tsserverlibrary.d.ts | 26 ++++++-- tests/cases/fourslash/fourslash.ts | 4 ++ .../cases/fourslash/server/configurePlugin.ts | 22 +++++++ 10 files changed, 172 insertions(+), 30 deletions(-) create mode 100644 tests/cases/fourslash/server/configurePlugin.ts diff --git a/src/harness/client.ts b/src/harness/client.ts index f59a9ca3188..2035802ca67 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -694,6 +694,10 @@ namespace ts.server { return response.body!.map(entry => this.decodeSpan(entry, fileName)); // TODO: GH#18217 } + configurePlugin(pluginName: string, configuration: any): void { + this.processRequest("configurePlugin", { pluginName, configuration }); + } + getIndentationAtPosition(_fileName: string, _position: number, _options: EditorOptions): number { return notImplemented(); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a3721dd29f4..6a1aa70bf3e 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3076,6 +3076,10 @@ Actual: ${stringify(fullActual)}`); } } } + + public configurePlugin(pluginName: string, configuration: any): void { + (this.languageService).configurePlugin(pluginName, configuration); + } } function updateTextRangeForTextChanges({ pos, end }: ts.TextRange, textChanges: ReadonlyArray): ts.TextRange { @@ -3139,19 +3143,20 @@ Actual: ${stringify(fullActual)}`); function runCode(code: string, state: TestState): void { // Compile and execute the test const wrappedCode = - `(function(test, goTo, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) { + `(function(test, goTo, plugins, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) { ${code} })`; try { const test = new FourSlashInterface.Test(state); const goTo = new FourSlashInterface.GoTo(state); + const plugins = new FourSlashInterface.Plugins(state); const verify = new FourSlashInterface.Verify(state); const edit = new FourSlashInterface.Edit(state); const debug = new FourSlashInterface.Debug(state); const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); const f = eval(wrappedCode); - f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); + f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); } catch (err) { throw err; @@ -3651,6 +3656,15 @@ namespace FourSlashInterface { } } + export class Plugins { + constructor (private state: FourSlash.TestState) { + } + + public configurePlugin(pluginName: string, configuration: any): void { + this.state.configurePlugin(pluginName, configuration); + } + } + export class GoTo { constructor(private state: FourSlash.TestState) { } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index e90f29446c3..ee35ab360ca 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -833,6 +833,36 @@ namespace Harness.LanguageService { error: undefined }; + // Accepts configurations + case "configurable-diagnostic-adder": + let customMessage = "default message"; + return { + module: () => ({ + create(info: ts.server.PluginCreateInfo) { + customMessage = info.config.message; + const proxy = makeDefaultProxy(info); + proxy.getSemanticDiagnostics = filename => { + const prev = info.languageService.getSemanticDiagnostics(filename); + const sourceFile: ts.SourceFile = info.project.getSourceFile(ts.toPath(filename, /*basePath*/ undefined, ts.createGetCanonicalFileName(info.serverHost.useCaseSensitiveFileNames)))!; + prev.push({ + category: ts.DiagnosticCategory.Error, + file: sourceFile, + code: 9999, + length: 3, + messageText: customMessage, + start: 0 + }); + return prev; + }; + return proxy; + }, + onConfigurationChanged(config: any) { + customMessage = config.message; + } + }), + error: undefined + }; + default: return { module: undefined, diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 1a7e668b25e..4e4f8ca6d78 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -509,6 +509,8 @@ namespace ts.server { public readonly globalPlugins: ReadonlyArray; public readonly pluginProbeLocations: ReadonlyArray; public readonly allowLocalPluginLoads: boolean; + private currentPluginConfigOverrides: Map | undefined; + public readonly typesMapLocation: string | undefined; public readonly syntaxOnly?: boolean; @@ -1742,7 +1744,7 @@ namespace ts.server { project.enableLanguageService(); project.watchWildcards(createMapFromTemplate(parsedCommandLine.wildcardDirectories!)); // TODO: GH#18217 } - project.enablePluginsWithOptions(compilerOptions); + project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition!, parsedCommandLine.compileOnSave!); // TODO: GH#18217 } @@ -1932,7 +1934,7 @@ namespace ts.server { private createInferredProject(currentDirectory: string | undefined, isSingleInferredProject?: boolean, projectRootPath?: NormalizedPath): InferredProject { const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - const project = new InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory); + const project = new InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -2880,6 +2882,16 @@ namespace ts.server { return false; } + + configurePlugin(args: protocol.ConfigurePluginRequestArguments) { + // For any projects that already have the plugin loaded, configure the plugin + this.forEachEnabledProject(project => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); + + // Also save the current configuration to pass on to any projects that are yet to be loaded. + // If a plugin is configured twice, only the latest configuration will be remembered. + this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || createMap(); + this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); + } } /* @internal */ diff --git a/src/server/project.ts b/src/server/project.ts index ecf62b724ec..fb6ec4b80fc 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -72,6 +72,12 @@ namespace ts.server { export interface PluginModule { create(createInfo: PluginCreateInfo): LanguageService; getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + + export interface PluginModuleWithName { + name: string; + module: PluginModule; } export type PluginModuleFactory = (mod: { typescript: typeof ts }) => PluginModule; @@ -92,7 +98,7 @@ namespace ts.server { private program: Program; private externalFiles: SortedReadonlyArray; private missingFilesMap: Map; - private plugins: PluginModule[] = []; + private plugins: PluginModuleWithName[] = []; /*@internal*/ /** @@ -549,9 +555,9 @@ namespace ts.server { getExternalFiles(): SortedReadonlyArray { return toSortedArray(flatMapToMutable(this.plugins, plugin => { - if (typeof plugin.getExternalFiles !== "function") return; + if (typeof plugin.module.getExternalFiles !== "function") return; try { - return plugin.getExternalFiles(this); + return plugin.module.getExternalFiles(this); } catch (e) { this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); @@ -1111,7 +1117,7 @@ namespace ts.server { this.rootFilesMap.delete(info.path); } - protected enableGlobalPlugins(options: CompilerOptions) { + protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined) { const host = this.projectService.host; if (!host.require) { @@ -1134,12 +1140,13 @@ namespace ts.server { // Provide global: true so plugins can detect why they can't find their config this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths); + + this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths, pluginConfigOverrides); } } } - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]) { + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined) { this.projectService.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); const log = (message: string) => { @@ -1149,6 +1156,14 @@ namespace ts.server { const resolvedModule = firstDefined(searchPaths, searchPath => Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log)); if (resolvedModule) { + const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); + if (configurationOverride) { + // Preserve the name property since it's immutable + const pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + this.enableProxy(resolvedModule, pluginConfigEntry); } else { @@ -1156,11 +1171,6 @@ namespace ts.server { } } - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics() { - this.projectService.sendProjectsUpdatedInBackgroundEvent(); - } - private enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) { try { if (typeof pluginModuleFactory !== "function") { @@ -1186,12 +1196,26 @@ namespace ts.server { } this.projectService.logger.info(`Plugin validation succeded`); this.languageService = newLS; - this.plugins.push(pluginModule); + this.plugins.push({ name: configEntry.name, module: pluginModule }); } catch (e) { this.projectService.logger.info(`Plugin activation failed: ${e}`); } } + + /*@internal*/ + onPluginConfigurationChanged(pluginName: string, configuration: any) { + this.plugins.filter(plugin => plugin.name === pluginName).forEach(plugin => { + if (plugin.module.onConfigurationChanged) { + plugin.module.onConfigurationChanged(configuration); + } + }); + } + + /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ + refreshDiagnostics() { + this.projectService.sendProjectsUpdatedInBackgroundEvent(); + } } /** @@ -1247,7 +1271,8 @@ namespace ts.server { documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, projectRootPath: NormalizedPath | undefined, - currentDirectory: string | undefined) { + currentDirectory: string | undefined, + pluginConfigOverrides: Map | undefined) { super(InferredProject.newName(), ProjectKind.Inferred, projectService, @@ -1263,7 +1288,7 @@ namespace ts.server { if (!projectRootPath && !projectService.useSingleInferredProject) { this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); } - this.enableGlobalPlugins(this.getCompilerOptions()); + this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); } addRoot(info: ScriptInfo) { @@ -1419,12 +1444,8 @@ namespace ts.server { return program && program.forEachResolvedProjectReference(cb); } - enablePlugins() { - this.enablePluginsWithOptions(this.getCompilerOptions()); - } - /*@internal*/ - enablePluginsWithOptions(options: CompilerOptions) { + enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: Map | undefined) { const host = this.projectService.host; if (!host.require) { @@ -1445,11 +1466,11 @@ namespace ts.server { // Enable tsconfig-specified plugins if (options.plugins) { for (const pluginConfigEntry of options.plugins) { - this.enablePlugin(pluginConfigEntry, searchPaths); + this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } - this.enableGlobalPlugins(options); + this.enableGlobalPlugins(options, pluginConfigOverrides); } /** diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 81b7af72e5b..aad7ba085de 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -129,6 +129,7 @@ namespace ts.server.protocol { GetEditsForFileRename = "getEditsForFileRename", /* @internal */ GetEditsForFileRenameFull = "getEditsForFileRename-full", + ConfigurePlugin = "configurePlugin" // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`. } @@ -1375,6 +1376,16 @@ namespace ts.server.protocol { export interface ConfigureResponse extends Response { } + export interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + + export interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } + /** * Information found in an "open" request. */ diff --git a/src/server/session.ts b/src/server/session.ts index 54caf953ee6..49db5562992 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1983,6 +1983,10 @@ namespace ts.server { this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false); } + private configurePlugin(args: protocol.ConfigurePluginRequestArguments) { + this.projectService.configurePlugin(args); + } + getCanonicalFileName(fileName: string) { const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); return normalizePath(name); @@ -2304,6 +2308,10 @@ namespace ts.server { [CommandNames.GetEditsForFileRenameFull]: (request: protocol.GetEditsForFileRenameRequest) => { return this.requiredResponse(this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false)); }, + [CommandNames.ConfigurePlugin]: (request: protocol.ConfigurePluginRequest) => { + this.configurePlugin(request.arguments); + return this.notRequired(); + } }); public addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse) { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 87bbf1a1cd2..ae04e45229a 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -5685,7 +5685,8 @@ declare namespace ts.server.protocol { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename" + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" } /** * A TypeScript Server message @@ -6634,6 +6635,14 @@ declare namespace ts.server.protocol { */ interface ConfigureResponse extends Response { } + interface ConfigurePluginRequestArguments { + pluginName: string; + configuration: any; + } + interface ConfigurePluginRequest extends Request { + command: CommandTypes.ConfigurePlugin; + arguments: ConfigurePluginRequestArguments; + } /** * Information found in an "open" request. */ @@ -8080,6 +8089,11 @@ declare namespace ts.server { interface PluginModule { create(createInfo: PluginCreateInfo): LanguageService; getExternalFiles?(proj: Project): string[]; + onConfigurationChanged?(config: any): void; + } + interface PluginModuleWithName { + name: string; + module: PluginModule; } type PluginModuleFactory = (mod: { typescript: typeof ts; @@ -8218,11 +8232,11 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(options: CompilerOptions): void; - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; + protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined): void; + protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined): void; + private enableProxy; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; - private enableProxy; } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -8263,7 +8277,6 @@ declare namespace ts.server { getConfigFilePath(): NormalizedPath; getProjectReferences(): ReadonlyArray | undefined; updateReferences(refs: ReadonlyArray | undefined): void; - enablePlugins(): void; /** * Get the errors that dont have any file name associated */ @@ -8523,6 +8536,7 @@ declare namespace ts.server { readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; + private currentPluginConfigOverrides; readonly typesMapLocation: string | undefined; readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ @@ -8698,6 +8712,7 @@ declare namespace ts.server { applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; hasDeferredExtension(): boolean; + configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; } } declare namespace ts.server { @@ -8870,6 +8885,7 @@ declare namespace ts.server { private convertTextChangeToCodeEdit; private getBraceMatching; private getDiagnosticsForProject; + private configurePlugin; getCanonicalFileName(fileName: string): string; exit(): void; private notRequired; diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index dd6d5fce273..d1979265548 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -124,6 +124,9 @@ declare namespace FourSlashInterface { symbolsInScope(range: Range): any[]; setTypesRegistry(map: { [key: string]: void }): void; } + class plugins { + configurePlugin(pluginName: string, configuration: any): void; + } class goTo { marker(name?: string | Marker): void; eachMarker(markers: ReadonlyArray, action: (marker: Marker, index: number) => void): void; @@ -636,6 +639,7 @@ declare namespace FourSlashInterface { } declare function verifyOperationIsCancelled(f: any): void; declare var test: FourSlashInterface.test_; +declare var plugins: FourSlashInterface.plugins; declare var goTo: FourSlashInterface.goTo; declare var verify: FourSlashInterface.verify; declare var edit: FourSlashInterface.edit; diff --git a/tests/cases/fourslash/server/configurePlugin.ts b/tests/cases/fourslash/server/configurePlugin.ts new file mode 100644 index 00000000000..90745f93146 --- /dev/null +++ b/tests/cases/fourslash/server/configurePlugin.ts @@ -0,0 +1,22 @@ +/// + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "plugins": [ +//// { "name": "configurable-diagnostic-adder" , "message": "configured error" } +//// ] +//// }, +//// "files": ["a.ts"] +//// } + +// @Filename: a.ts +//// let x = [1, 2]; +//// /**/ +//// + +// Test that plugin adds an error message which is able to be configured +goTo.marker(); +verify.getSemanticDiagnostics([{ message: "configured error", code: 9999, range: { pos: 0, end: 3, fileName: "a.ts" } }]); +plugins.configurePlugin("configurable-diagnostic-adder", { message: "new error" }); +verify.getSemanticDiagnostics([{ message: "new error", code: 9999, range: { pos: 0, end: 3, fileName: "a.ts" } }]); From 64ff1954260b153bd2d174bfb9f1866eda61a10c Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 29 Oct 2018 14:51:12 -0700 Subject: [PATCH 142/262] Set-only accessors spread to undefined (#28213) * Set-only accessors spread to undefined Previously they were skipped. The runtime behaviour is to create a property of type undefined, unlike (for example) spreading numbers or other primitives. So now spreading a set-only accessor creates a property of type undefined: ```ts const o: { foo: undefined } = { ...{ set foo(v: number) { } } } ``` Notably, `o.foo: undefined` not `number`. Fixes #26337 * Fix isSpreadableProperty oversimplification --- src/compiler/checker.ts | 19 ++++++++-------- .../reference/objectSpreadNegative.errors.txt | 6 ++--- .../reference/objectSpreadNegative.symbols | 2 ++ .../reference/objectSpreadNegative.types | 10 ++++----- .../reference/objectSpreadSetonlyAccessor.js | 9 ++++++++ .../objectSpreadSetonlyAccessor.symbols | 16 ++++++++++++++ .../objectSpreadSetonlyAccessor.types | 22 +++++++++++++++++++ .../spread/objectSpreadSetonlyAccessor.ts | 4 ++++ 8 files changed, 71 insertions(+), 17 deletions(-) create mode 100644 tests/baselines/reference/objectSpreadSetonlyAccessor.js create mode 100644 tests/baselines/reference/objectSpreadSetonlyAccessor.symbols create mode 100644 tests/baselines/reference/objectSpreadSetonlyAccessor.types create mode 100644 tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d2464652919..418be79878e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4608,7 +4608,7 @@ namespace ts { if (!names.has(prop.escapedName) && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getNonReadonlySymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop)); } } const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); @@ -9887,7 +9887,7 @@ namespace ts { skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } @@ -9911,7 +9911,7 @@ namespace ts { } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } @@ -9929,18 +9929,19 @@ namespace ts { /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop: Symbol): boolean { - return prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor) - ? !prop.declarations.some(decl => isClassLike(decl.parent)) - : !(prop.flags & SymbolFlags.SetAccessor); // Setter without getter is not spreadable + return !(prop.flags & (SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) || + !prop.declarations.some(decl => isClassLike(decl.parent)); } - function getNonReadonlySymbol(prop: Symbol) { - if (!isReadonlySymbol(prop)) { + function getSpreadSymbol(prop: Symbol) { + const isReadonly = isReadonlySymbol(prop); + const isSetonlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor); + if (!isReadonly && !isSetonlyAccessor) { return prop; } const flags = SymbolFlags.Property | (prop.flags & SymbolFlags.Optional); const result = createSymbol(flags, prop.escapedName); - result.type = getTypeOfSymbol(prop); + result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; diff --git a/tests/baselines/reference/objectSpreadNegative.errors.txt b/tests/baselines/reference/objectSpreadNegative.errors.txt index 1af05906873..2f195640871 100644 --- a/tests/baselines/reference/objectSpreadNegative.errors.txt +++ b/tests/baselines/reference/objectSpreadNegative.errors.txt @@ -13,7 +13,7 @@ tests/cases/conformance/types/spread/objectSpreadNegative.ts(34,20): error TS269 tests/cases/conformance/types/spread/objectSpreadNegative.ts(36,20): error TS2698: Spread types may only be created from object types. tests/cases/conformance/types/spread/objectSpreadNegative.ts(38,19): error TS2698: Spread types may only be created from object types. tests/cases/conformance/types/spread/objectSpreadNegative.ts(43,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures. -tests/cases/conformance/types/spread/objectSpreadNegative.ts(47,12): error TS2339: Property 'b' does not exist on type '{}'. +tests/cases/conformance/types/spread/objectSpreadNegative.ts(47,1): error TS2322: Type '12' is not assignable to type 'undefined'. tests/cases/conformance/types/spread/objectSpreadNegative.ts(53,9): error TS2339: Property 'm' does not exist on type '{ p: number; }'. tests/cases/conformance/types/spread/objectSpreadNegative.ts(58,11): error TS2339: Property 'a' does not exist on type '{}'. tests/cases/conformance/types/spread/objectSpreadNegative.ts(62,14): error TS2698: Spread types may only be created from object types. @@ -95,8 +95,8 @@ tests/cases/conformance/types/spread/objectSpreadNegative.ts(65,14): error TS269 // write-only properties get skipped let setterOnly = { ...{ set b (bad: number) { } } }; setterOnly.b = 12; // error, 'b' does not exist - ~ -!!! error TS2339: Property 'b' does not exist on type '{}'. + ~~~~~~~~~~~~ +!!! error TS2322: Type '12' is not assignable to type 'undefined'. // methods are skipped because they aren't enumerable class C { p = 1; m() { } } diff --git a/tests/baselines/reference/objectSpreadNegative.symbols b/tests/baselines/reference/objectSpreadNegative.symbols index 4bff16d9be6..110d4557d2a 100644 --- a/tests/baselines/reference/objectSpreadNegative.symbols +++ b/tests/baselines/reference/objectSpreadNegative.symbols @@ -132,7 +132,9 @@ let setterOnly = { ...{ set b (bad: number) { } } }; >bad : Symbol(bad, Decl(objectSpreadNegative.ts, 45, 31)) setterOnly.b = 12; // error, 'b' does not exist +>setterOnly.b : Symbol(b, Decl(objectSpreadNegative.ts, 45, 23)) >setterOnly : Symbol(setterOnly, Decl(objectSpreadNegative.ts, 45, 3)) +>b : Symbol(b, Decl(objectSpreadNegative.ts, 45, 23)) // methods are skipped because they aren't enumerable class C { p = 1; m() { } } diff --git a/tests/baselines/reference/objectSpreadNegative.types b/tests/baselines/reference/objectSpreadNegative.types index 26fd5642d23..837670d58ca 100644 --- a/tests/baselines/reference/objectSpreadNegative.types +++ b/tests/baselines/reference/objectSpreadNegative.types @@ -173,17 +173,17 @@ spreadFunc(); // error, no call signature // write-only properties get skipped let setterOnly = { ...{ set b (bad: number) { } } }; ->setterOnly : {} ->{ ...{ set b (bad: number) { } } } : {} +>setterOnly : { b: undefined; } +>{ ...{ set b (bad: number) { } } } : { b: undefined; } >{ set b (bad: number) { } } : { b: number; } >b : number >bad : number setterOnly.b = 12; // error, 'b' does not exist >setterOnly.b = 12 : 12 ->setterOnly.b : any ->setterOnly : {} ->b : any +>setterOnly.b : undefined +>setterOnly : { b: undefined; } +>b : undefined >12 : 12 // methods are skipped because they aren't enumerable diff --git a/tests/baselines/reference/objectSpreadSetonlyAccessor.js b/tests/baselines/reference/objectSpreadSetonlyAccessor.js new file mode 100644 index 00000000000..17b854e85e5 --- /dev/null +++ b/tests/baselines/reference/objectSpreadSetonlyAccessor.js @@ -0,0 +1,9 @@ +//// [objectSpreadSetonlyAccessor.ts] +const o1: { foo: number, bar: undefined } = { foo: 1, ... { set bar(_v: number) { } } } +const o2: { foo: undefined } = { foo: 1, ... { set foo(_v: number) { } } } + + +//// [objectSpreadSetonlyAccessor.js] +"use strict"; +const o1 = { foo: 1, ...{ set bar(_v) { } } }; +const o2 = { foo: 1, ...{ set foo(_v) { } } }; diff --git a/tests/baselines/reference/objectSpreadSetonlyAccessor.symbols b/tests/baselines/reference/objectSpreadSetonlyAccessor.symbols new file mode 100644 index 00000000000..d8f0281c6c0 --- /dev/null +++ b/tests/baselines/reference/objectSpreadSetonlyAccessor.symbols @@ -0,0 +1,16 @@ +=== tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts === +const o1: { foo: number, bar: undefined } = { foo: 1, ... { set bar(_v: number) { } } } +>o1 : Symbol(o1, Decl(objectSpreadSetonlyAccessor.ts, 0, 5)) +>foo : Symbol(foo, Decl(objectSpreadSetonlyAccessor.ts, 0, 11)) +>bar : Symbol(bar, Decl(objectSpreadSetonlyAccessor.ts, 0, 24)) +>foo : Symbol(foo, Decl(objectSpreadSetonlyAccessor.ts, 0, 45)) +>bar : Symbol(bar, Decl(objectSpreadSetonlyAccessor.ts, 0, 59)) +>_v : Symbol(_v, Decl(objectSpreadSetonlyAccessor.ts, 0, 68)) + +const o2: { foo: undefined } = { foo: 1, ... { set foo(_v: number) { } } } +>o2 : Symbol(o2, Decl(objectSpreadSetonlyAccessor.ts, 1, 5)) +>foo : Symbol(foo, Decl(objectSpreadSetonlyAccessor.ts, 1, 11)) +>foo : Symbol(foo, Decl(objectSpreadSetonlyAccessor.ts, 1, 32)) +>foo : Symbol(foo, Decl(objectSpreadSetonlyAccessor.ts, 1, 46)) +>_v : Symbol(_v, Decl(objectSpreadSetonlyAccessor.ts, 1, 55)) + diff --git a/tests/baselines/reference/objectSpreadSetonlyAccessor.types b/tests/baselines/reference/objectSpreadSetonlyAccessor.types new file mode 100644 index 00000000000..f9e482f008b --- /dev/null +++ b/tests/baselines/reference/objectSpreadSetonlyAccessor.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts === +const o1: { foo: number, bar: undefined } = { foo: 1, ... { set bar(_v: number) { } } } +>o1 : { foo: number; bar: undefined; } +>foo : number +>bar : undefined +>{ foo: 1, ... { set bar(_v: number) { } } } : { bar: undefined; foo: number; } +>foo : number +>1 : 1 +>{ set bar(_v: number) { } } : { bar: number; } +>bar : number +>_v : number + +const o2: { foo: undefined } = { foo: 1, ... { set foo(_v: number) { } } } +>o2 : { foo: undefined; } +>foo : undefined +>{ foo: 1, ... { set foo(_v: number) { } } } : { foo: undefined; } +>foo : number +>1 : 1 +>{ set foo(_v: number) { } } : { foo: number; } +>foo : number +>_v : number + diff --git a/tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts b/tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts new file mode 100644 index 00000000000..1a783230b59 --- /dev/null +++ b/tests/cases/conformance/types/spread/objectSpreadSetonlyAccessor.ts @@ -0,0 +1,4 @@ +// @strict: true +// @target: esnext +const o1: { foo: number, bar: undefined } = { foo: 1, ... { set bar(_v: number) { } } } +const o2: { foo: undefined } = { foo: 1, ... { set foo(_v: number) { } } } From 5c42c5a5a232ad4aee0325ea21c3eee9ce73ac97 Mon Sep 17 00:00:00 2001 From: csigs Date: Mon, 29 Oct 2018 22:10:53 +0000 Subject: [PATCH 143/262] LEGO: check in for master to temporary branch. --- .../diagnosticMessages/diagnosticMessages.generated.json.lcl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 087c7c6a051..ec3ab3244b0 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3766,7 +3766,7 @@ - + @@ -3775,7 +3775,7 @@ - + From 7a47248f304647c21d3511a073e5cbd0d428e986 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 29 Oct 2018 16:02:34 -0700 Subject: [PATCH 144/262] Produce intersection types for spreads with generic types --- src/compiler/checker.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 197dc4ccbd5..2a27a7a7e8a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9840,6 +9840,10 @@ namespace ts { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } + function isNonGenericObjectType(type: Type) { + return !!(type.flags & TypeFlags.Object) && !isGenericMappedType(type); + } + /** * Since the source of spread types are object literals, which are not binary, * this function should be called in a left folding style, with left = previous result of getSpreadType @@ -9868,6 +9872,23 @@ namespace ts { return left; } + if (isGenericObjectType(left) || isGenericObjectType(right)) { + if (isEmptyObjectType(left)) { + return right; + } + // When the left type is an intersection, we may need to merge the last constituent of the + // intersection with the right type. For example when the left type is 'T & { a: string }' + // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'. + if (left.flags & TypeFlags.Intersection) { + const types = (left).types; + const lastLeft = types[types.length - 1]; + if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { + return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + } + } + return getIntersectionType([left, right]); + } + const members = createSymbolTable(); const skippedPrivateMembers = createUnderscoreEscapedMap(); let stringIndexInfo: IndexInfo | undefined; @@ -17697,9 +17718,8 @@ namespace ts { } function isValidSpreadType(type: Type): boolean { - return !!(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.NonPrimitive) || + return !!(type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.NonPrimitive | TypeFlags.Object | TypeFlags.InstantiableNonPrimitive) || getFalsyFlags(type) & TypeFlags.DefinitelyFalsy && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & TypeFlags.Object && !isGenericMappedType(type) || type.flags & TypeFlags.UnionOrIntersection && every((type).types, isValidSpreadType)); } From 00c30156c613ef9348a6402f7d33d201c14caeef Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 29 Oct 2018 16:07:42 -0700 Subject: [PATCH 145/262] Accept new baselines --- .../reference/objectRestNegative.errors.txt | 5 +--- .../reference/objectRestNegative.types | 6 ++--- .../reference/objectSpreadNegative.errors.txt | 8 +------ .../reference/objectSpreadNegative.types | 22 ++++++++--------- .../restInvalidArgumentType.errors.txt | 20 +--------------- .../reference/restInvalidArgumentType.types | 12 +++++----- .../spreadInvalidArgumentType.errors.txt | 20 +--------------- .../reference/spreadInvalidArgumentType.types | 24 +++++++++---------- 8 files changed, 36 insertions(+), 81 deletions(-) diff --git a/tests/baselines/reference/objectRestNegative.errors.txt b/tests/baselines/reference/objectRestNegative.errors.txt index fef99187d55..42b25d137ef 100644 --- a/tests/baselines/reference/objectRestNegative.errors.txt +++ b/tests/baselines/reference/objectRestNegative.errors.txt @@ -5,11 +5,10 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Ty tests/cases/conformance/types/rest/objectRestNegative.ts(9,31): error TS2462: A rest element must be last in a destructuring pattern. tests/cases/conformance/types/rest/objectRestNegative.ts(11,30): error TS7008: Member 'x' implicitly has an 'any' type. tests/cases/conformance/types/rest/objectRestNegative.ts(11,33): error TS7008: Member 'y' implicitly has an 'any' type. -tests/cases/conformance/types/rest/objectRestNegative.ts(12,17): error TS2700: Rest types may only be created from object types. tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: The target of an object rest assignment must be a variable or a property access. -==== tests/cases/conformance/types/rest/objectRestNegative.ts (7 errors) ==== +==== tests/cases/conformance/types/rest/objectRestNegative.ts (6 errors) ==== let o = { a: 1, b: 'no' }; var { ...mustBeLast, a } = o; ~~~~~~~~~~ @@ -34,8 +33,6 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: Th ~ !!! error TS7008: Member 'y' implicitly has an 'any' type. let { x, ...rest } = t; - ~~~~ -!!! error TS2700: Rest types may only be created from object types. return rest; } diff --git a/tests/baselines/reference/objectRestNegative.types b/tests/baselines/reference/objectRestNegative.types index dff6388d609..f032dbe7d5b 100644 --- a/tests/baselines/reference/objectRestNegative.types +++ b/tests/baselines/reference/objectRestNegative.types @@ -36,18 +36,18 @@ function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { >b : string } function generic(t: T) { ->generic : (t: T) => any +>generic : (t: T) => { y: any; } >x : any >y : any >t : T let { x, ...rest } = t; >x : any ->rest : any +>rest : { y: any; } >t : T return rest; ->rest : any +>rest : { y: any; } } let rest: { b: string } diff --git a/tests/baselines/reference/objectSpreadNegative.errors.txt b/tests/baselines/reference/objectSpreadNegative.errors.txt index 1af05906873..c7f33d2d61b 100644 --- a/tests/baselines/reference/objectSpreadNegative.errors.txt +++ b/tests/baselines/reference/objectSpreadNegative.errors.txt @@ -16,11 +16,9 @@ tests/cases/conformance/types/spread/objectSpreadNegative.ts(43,1): error TS2349 tests/cases/conformance/types/spread/objectSpreadNegative.ts(47,12): error TS2339: Property 'b' does not exist on type '{}'. tests/cases/conformance/types/spread/objectSpreadNegative.ts(53,9): error TS2339: Property 'm' does not exist on type '{ p: number; }'. tests/cases/conformance/types/spread/objectSpreadNegative.ts(58,11): error TS2339: Property 'a' does not exist on type '{}'. -tests/cases/conformance/types/spread/objectSpreadNegative.ts(62,14): error TS2698: Spread types may only be created from object types. -tests/cases/conformance/types/spread/objectSpreadNegative.ts(65,14): error TS2698: Spread types may only be created from object types. -==== tests/cases/conformance/types/spread/objectSpreadNegative.ts (17 errors) ==== +==== tests/cases/conformance/types/spread/objectSpreadNegative.ts (15 errors) ==== let o = { a: 1, b: 'no' } /// private propagates @@ -116,13 +114,9 @@ tests/cases/conformance/types/spread/objectSpreadNegative.ts(65,14): error TS269 // generics function f(t: T, u: U) { return { ...t, ...u, id: 'id' }; - ~~~~ -!!! error TS2698: Spread types may only be created from object types. } function override(initial: U, override: U): U { return { ...initial, ...override }; - ~~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. } let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = f({ a: 1, b: 'yes' }, { c: 'no', d: false }) diff --git a/tests/baselines/reference/objectSpreadNegative.types b/tests/baselines/reference/objectSpreadNegative.types index 26fd5642d23..ed2d996af9d 100644 --- a/tests/baselines/reference/objectSpreadNegative.types +++ b/tests/baselines/reference/objectSpreadNegative.types @@ -228,12 +228,12 @@ spreadObj.a; // error 'a' is not in {} // generics function f(t: T, u: U) { ->f : (t: T, u: U) => any +>f : (t: T, u: U) => T & U & { id: string; } >t : T >u : U return { ...t, ...u, id: 'id' }; ->{ ...t, ...u, id: 'id' } : any +>{ ...t, ...u, id: 'id' } : T & U & { id: string; } >t : T >u : U >id : string @@ -245,7 +245,7 @@ function override(initial: U, override: U): U { >override : U return { ...initial, ...override }; ->{ ...initial, ...override } : any +>{ ...initial, ...override } : U >initial : U >override : U } @@ -258,8 +258,8 @@ let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = >d : boolean f({ a: 1, b: 'yes' }, { c: 'no', d: false }) ->f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : any ->f : (t: T, u: U) => any +>f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : { a: number; b: string; } & { c: string; d: boolean; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } >{ a: 1, b: 'yes' } : { a: number; b: string; } >a : number >1 : 1 @@ -278,8 +278,8 @@ let overlap: { id: string, a: number, b: string } = >b : string f({ a: 1 }, { a: 2, b: 'extra' }) ->f({ a: 1 }, { a: 2, b: 'extra' }) : any ->f : (t: T, u: U) => any +>f({ a: 1 }, { a: 2, b: 'extra' }) : { a: number; } & { a: number; b: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } >{ a: 1 } : { a: number; } >a : number >1 : 1 @@ -295,8 +295,8 @@ let overlapConflict: { id:string, a: string } = >a : string f({ a: 1 }, { a: 'mismatch' }) ->f({ a: 1 }, { a: 'mismatch' }) : any ->f : (t: T, u: U) => any +>f({ a: 1 }, { a: 'mismatch' }) : { a: number; } & { a: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } >{ a: 1 } : { a: number; } >a : number >1 : 1 @@ -312,8 +312,8 @@ let overwriteId: { id: string, a: number, c: number, d: string } = >d : string f({ a: 1, id: true }, { c: 1, d: 'no' }) ->f({ a: 1, id: true }, { c: 1, d: 'no' }) : any ->f : (t: T, u: U) => any +>f({ a: 1, id: true }, { c: 1, d: 'no' }) : { a: number; id: boolean; } & { c: number; d: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } >{ a: 1, id: true } : { a: number; id: true; } >a : number >1 : 1 diff --git a/tests/baselines/reference/restInvalidArgumentType.errors.txt b/tests/baselines/reference/restInvalidArgumentType.errors.txt index 0cc4faea557..7e0c852316a 100644 --- a/tests/baselines/reference/restInvalidArgumentType.errors.txt +++ b/tests/baselines/reference/restInvalidArgumentType.errors.txt @@ -1,11 +1,5 @@ -tests/cases/compiler/restInvalidArgumentType.ts(27,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(29,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(30,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(31,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(33,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(36,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(37,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(39,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(40,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(42,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(43,13): error TS2700: Rest types may only be created from object types. @@ -16,7 +10,7 @@ tests/cases/compiler/restInvalidArgumentType.ts(51,13): error TS2700: Rest types tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types may only be created from object types. -==== tests/cases/compiler/restInvalidArgumentType.ts (16 errors) ==== +==== tests/cases/compiler/restInvalidArgumentType.ts (10 errors) ==== enum E { v1, v2 }; function f(p1: T, p2: T[]) { @@ -44,34 +38,22 @@ tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types var a: any; var {...r1} = p1; // Error, generic type paramterre - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r2} = p2; // OK var {...r3} = t; // Error, generic type paramter - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r4} = i; // Error, index access - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r5} = k; // Error, index ~~ !!! error TS2700: Rest types may only be created from object types. var {...r6} = mapped_generic; // Error, generic mapped object type - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r7} = mapped; // OK, non-generic mapped type var {...r8} = union_generic; // Error, union with generic type parameter - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r9} = union_primitive; // Error, union with generic type parameter ~~ !!! error TS2700: Rest types may only be created from object types. var {...r10} = intersection_generic; // Error, intersection with generic type parameter - ~~~ -!!! error TS2700: Rest types may only be created from object types. var {...r11} = intersection_primitive; // Error, intersection with generic type parameter ~~~ !!! error TS2700: Rest types may only be created from object types. diff --git a/tests/baselines/reference/restInvalidArgumentType.types b/tests/baselines/reference/restInvalidArgumentType.types index ce59fb145f9..cd598247193 100644 --- a/tests/baselines/reference/restInvalidArgumentType.types +++ b/tests/baselines/reference/restInvalidArgumentType.types @@ -67,7 +67,7 @@ function f(p1: T, p2: T[]) { >a : any var {...r1} = p1; // Error, generic type paramterre ->r1 : any +>r1 : { b: string; } >p1 : T var {...r2} = p2; // OK @@ -75,11 +75,11 @@ function f(p1: T, p2: T[]) { >p2 : T[] var {...r3} = t; // Error, generic type paramter ->r3 : any +>r3 : { b: string; } >t : T var {...r4} = i; // Error, index access ->r4 : any +>r4 : { readonly [index: number]: string; toString(): string; charAt(pos: number): string; charCodeAt(index: number): number; concat(...strings: string[]): string; indexOf(searchString: string, position?: number): number; lastIndexOf(searchString: string, position?: number): number; localeCompare(that: string): number; localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; match(regexp: string | RegExp): RegExpMatchArray; replace(searchValue: string | RegExp, replaceValue: string): string; replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; search(regexp: string | RegExp): number; slice(start?: number, end?: number): string; split(separator: string | RegExp, limit?: number): string[]; substring(start: number, end?: number): string; toLowerCase(): string; toLocaleLowerCase(): string; toUpperCase(): string; toLocaleUpperCase(): string; trim(): string; length: number; substr(from: number, length?: number): string; valueOf(): string; } >i : T["b"] var {...r5} = k; // Error, index @@ -87,7 +87,7 @@ function f(p1: T, p2: T[]) { >k : keyof T var {...r6} = mapped_generic; // Error, generic mapped object type ->r6 : any +>r6 : { b: T["b"]; } >mapped_generic : { [P in keyof T]: T[P]; } var {...r7} = mapped; // OK, non-generic mapped type @@ -95,7 +95,7 @@ function f(p1: T, p2: T[]) { >mapped : { b: T["b"]; } var {...r8} = union_generic; // Error, union with generic type parameter ->r8 : any +>r8 : { b: string; } | { a: number; } >union_generic : T | { a: number; } var {...r9} = union_primitive; // Error, union with generic type parameter @@ -103,7 +103,7 @@ function f(p1: T, p2: T[]) { >union_primitive : number | { a: number; } var {...r10} = intersection_generic; // Error, intersection with generic type parameter ->r10 : any +>r10 : { b: string; a: number; } >intersection_generic : T & { a: number; } var {...r11} = intersection_primitive; // Error, intersection with generic type parameter diff --git a/tests/baselines/reference/spreadInvalidArgumentType.errors.txt b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt index 4c1aa286aad..50caa0e76bb 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.errors.txt +++ b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt @@ -1,11 +1,5 @@ -tests/cases/compiler/spreadInvalidArgumentType.ts(30,16): error TS2698: Spread types may only be created from object types. -tests/cases/compiler/spreadInvalidArgumentType.ts(32,16): error TS2698: Spread types may only be created from object types. -tests/cases/compiler/spreadInvalidArgumentType.ts(33,16): error TS2698: Spread types may only be created from object types. tests/cases/compiler/spreadInvalidArgumentType.ts(34,16): error TS2698: Spread types may only be created from object types. -tests/cases/compiler/spreadInvalidArgumentType.ts(35,16): error TS2698: Spread types may only be created from object types. -tests/cases/compiler/spreadInvalidArgumentType.ts(38,16): error TS2698: Spread types may only be created from object types. tests/cases/compiler/spreadInvalidArgumentType.ts(39,16): error TS2698: Spread types may only be created from object types. -tests/cases/compiler/spreadInvalidArgumentType.ts(41,17): error TS2698: Spread types may only be created from object types. tests/cases/compiler/spreadInvalidArgumentType.ts(42,17): error TS2698: Spread types may only be created from object types. tests/cases/compiler/spreadInvalidArgumentType.ts(44,17): error TS2698: Spread types may only be created from object types. tests/cases/compiler/spreadInvalidArgumentType.ts(45,17): error TS2698: Spread types may only be created from object types. @@ -16,7 +10,7 @@ tests/cases/compiler/spreadInvalidArgumentType.ts(53,17): error TS2698: Spread t tests/cases/compiler/spreadInvalidArgumentType.ts(55,17): error TS2698: Spread types may only be created from object types. -==== tests/cases/compiler/spreadInvalidArgumentType.ts (16 errors) ==== +==== tests/cases/compiler/spreadInvalidArgumentType.ts (10 errors) ==== enum E { v1, v2 }; function f(p1: T, p2: T[]) { @@ -47,33 +41,21 @@ tests/cases/compiler/spreadInvalidArgumentType.ts(55,17): error TS2698: Spread t var e: E; var o1 = { ...p1 }; // Error, generic type paramterre - ~~~~~ -!!! error TS2698: Spread types may only be created from object types. var o2 = { ...p2 }; // OK var o3 = { ...t }; // Error, generic type paramter - ~~~~ -!!! error TS2698: Spread types may only be created from object types. var o4 = { ...i }; // Error, index access - ~~~~ -!!! error TS2698: Spread types may only be created from object types. var o5 = { ...k }; // Error, index ~~~~ !!! error TS2698: Spread types may only be created from object types. var o6 = { ...mapped_generic }; // Error, generic mapped object type - ~~~~~~~~~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. var o7 = { ...mapped }; // OK, non-generic mapped type var o8 = { ...union_generic }; // Error, union with generic type parameter - ~~~~~~~~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. var o9 = { ...union_primitive }; // Error, union with generic type parameter ~~~~~~~~~~~~~~~~~~ !!! error TS2698: Spread types may only be created from object types. var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter - ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2698: Spread types may only be created from object types. var o11 = { ...intersection_primitive }; // Error, intersection with generic type parameter ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2698: Spread types may only be created from object types. diff --git a/tests/baselines/reference/spreadInvalidArgumentType.types b/tests/baselines/reference/spreadInvalidArgumentType.types index 1acb22419a9..13e22457e3b 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.types +++ b/tests/baselines/reference/spreadInvalidArgumentType.types @@ -68,8 +68,8 @@ function f(p1: T, p2: T[]) { >e : E var o1 = { ...p1 }; // Error, generic type paramterre ->o1 : any ->{ ...p1 } : any +>o1 : T +>{ ...p1 } : T >p1 : T var o2 = { ...p2 }; // OK @@ -78,13 +78,13 @@ function f(p1: T, p2: T[]) { >p2 : T[] var o3 = { ...t }; // Error, generic type paramter ->o3 : any ->{ ...t } : any +>o3 : T +>{ ...t } : T >t : T var o4 = { ...i }; // Error, index access ->o4 : any ->{ ...i } : any +>o4 : T["b"] +>{ ...i } : T["b"] >i : T["b"] var o5 = { ...k }; // Error, index @@ -93,8 +93,8 @@ function f(p1: T, p2: T[]) { >k : keyof T var o6 = { ...mapped_generic }; // Error, generic mapped object type ->o6 : any ->{ ...mapped_generic } : any +>o6 : { [P in keyof T]: T[P]; } +>{ ...mapped_generic } : { [P in keyof T]: T[P]; } >mapped_generic : { [P in keyof T]: T[P]; } var o7 = { ...mapped }; // OK, non-generic mapped type @@ -103,8 +103,8 @@ function f(p1: T, p2: T[]) { >mapped : { b: T["b"]; } var o8 = { ...union_generic }; // Error, union with generic type parameter ->o8 : any ->{ ...union_generic } : any +>o8 : T | { a: number; } +>{ ...union_generic } : T | { a: number; } >union_generic : T | { a: number; } var o9 = { ...union_primitive }; // Error, union with generic type parameter @@ -113,8 +113,8 @@ function f(p1: T, p2: T[]) { >union_primitive : number | { a: number; } var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter ->o10 : any ->{ ...intersection_generic } : any +>o10 : T & { a: number; } +>{ ...intersection_generic } : T & { a: number; } >intersection_generic : T & { a: number; } var o11 = { ...intersection_primitive }; // Error, intersection with generic type parameter From 1c4590341f927cea82c4bfa9748a08f61431d5e2 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 29 Oct 2018 16:40:30 -0700 Subject: [PATCH 146/262] Avoid reformatting body of arrow function with single unused parameter (#28217) --- src/services/textChanges.ts | 28 +++++++------------ .../codeFixUnusedIdentifier_all_delete.ts | 7 +++++ .../fourslash/unusedParameterInLambda1.ts | 3 +- .../fourslash/unusedParameterInLambda2.ts | 3 +- 4 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index cf850cd63ab..47d8d0784e3 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -276,11 +276,15 @@ namespace ts.textChanges { return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); } + public replaceNodeWithText(sourceFile: SourceFile, oldNode: Node, text: string): void { + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text); + } + public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: ReadonlyArray, options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions) { return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); } - private nextCommaToken (sourceFile: SourceFile, node: Node): Node | undefined { + private nextCommaToken(sourceFile: SourceFile, node: Node): Node | undefined { const next = findNextToken(node, node.parent, sourceFile); return next && next.kind === SyntaxKind.CommaToken ? next : undefined; } @@ -690,7 +694,7 @@ namespace ts.textChanges { } private finishDeleteDeclarations(): void { - const deletedNodesInLists = new NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + const deletedNodesInLists = new NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. for (const { sourceFile, node } of this.deletedNodes) { if (!this.deletedNodes.some(d => d.sourceFile === sourceFile && rangeContainsRangeExclusive(d.node, node))) { if (isArray(node)) { @@ -1053,25 +1057,13 @@ namespace ts.textChanges { switch (node.kind) { case SyntaxKind.Parameter: { const oldFunction = node.parent; - if (isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + if (isArrowFunction(oldFunction) && + oldFunction.parameters.length === 1 && + !findChildOfKind(oldFunction, SyntaxKind.OpenParenToken, sourceFile)) { // Lambdas with exactly one parameter are special because, after removal, there // must be an empty parameter list (i.e. `()`) and this won't necessarily be the // case if the parameter is simply removed (e.g. in `x => 1`). - const newFunction = updateArrowFunction( - oldFunction, - oldFunction.modifiers, - oldFunction.typeParameters, - /*parameters*/ undefined!, // TODO: GH#18217 - oldFunction.type, - oldFunction.equalsGreaterThanToken, - oldFunction.body); - - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - suppressLeadingAndTrailingTrivia(newFunction); - - changes.replaceNode(sourceFile, oldFunction, newFunction); + changes.replaceNodeWithText(sourceFile, node, "()"); } else { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts index 2f6ef293521..b169ffb8848 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_all_delete.ts @@ -31,6 +31,10 @@ ////takesCb((x, y) => { x; }); ////takesCb((x, y) => { y; }); //// +////x => { +//// const y = 0; +////}; +//// ////{ //// let a, b; ////} @@ -72,6 +76,9 @@ takesCb(() => {}); takesCb((x) => { x; }); takesCb((x, y) => { y; }); +() => { +}; + { } for (; ;) {} diff --git a/tests/cases/fourslash/unusedParameterInLambda1.ts b/tests/cases/fourslash/unusedParameterInLambda1.ts index fdb53a8a05f..60b7b3a9990 100644 --- a/tests/cases/fourslash/unusedParameterInLambda1.ts +++ b/tests/cases/fourslash/unusedParameterInLambda1.ts @@ -4,9 +4,8 @@ // @noUnusedParameters: true ////[|/*~a*/(/*~b*/x/*~c*/:/*~d*/number/*~e*/)/*~f*/ => /*~g*/{/*~h*/}/*~i*/|] -// In a perfect world, /*~f*/ and /*~h*/ would probably be retained. verify.codeFix({ description: "Remove declaration for: 'x'", index: 0, - newRangeContent: "/*~a*/() => /*~g*/ { }/*~i*/", + newRangeContent: "/*~a*/(/*~e*/)/*~f*/ => /*~g*/{/*~h*/}/*~i*/", }); diff --git a/tests/cases/fourslash/unusedParameterInLambda2.ts b/tests/cases/fourslash/unusedParameterInLambda2.ts index e2b1be346b8..b7c7da6dc26 100644 --- a/tests/cases/fourslash/unusedParameterInLambda2.ts +++ b/tests/cases/fourslash/unusedParameterInLambda2.ts @@ -4,9 +4,8 @@ // @noUnusedParameters: true ////[|/*~a*/x/*~b*/ /*~c*/=>/*~d*/ {/*~e*/}/*~f*/|] -// In a perfect world, /*~c*/ and /*~e*/ would probably be retained. verify.codeFix({ description: "Remove declaration for: 'x'", index: 0, - newRangeContent: "/*~a*/() => /*~d*/ { }/*~f*/", + newRangeContent: "/*~a*/()/*~b*/ /*~c*/=>/*~d*/ {/*~e*/}/*~f*/", }); From e98d8c3679353f0b5828e799b2f06581dd11adff Mon Sep 17 00:00:00 2001 From: Alexander T Date: Tue, 30 Oct 2018 16:25:42 +0200 Subject: [PATCH 147/262] remove unused 'debug' option. change 'jake runtests' description (#28226) --- CONTRIBUTING.md | 6 +++--- Gulpfile.js | 2 +- Jakefile.js | 5 ++--- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c937316603f..fbce8186fac 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -137,10 +137,10 @@ You can specify which browser to use for debugging. Currently Chrome and IE are jake runtests-browser tests=2dArrays browser=chrome ``` -You can debug with VS Code or Node instead with `jake runtests debug=true`: +You can debug with VS Code or Node instead with `jake runtests inspect=true`: ```Shell -jake runtests tests=2dArrays debug=true +jake runtests tests=2dArrays inspect=true ``` ## Adding a Test @@ -153,7 +153,7 @@ The supported names and values are the same as those supported in the compiler i They are useful for tests relating to modules. See below for examples. -**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in `tests\cases\conformance` in an appropriately-named subfolder. +**Note** that if you have a test corresponding to a specific spec compliance item, you can place it in `tests\cases\conformance` in an appropriately-named subfolder. **Note** that filenames here must be distinct from all other compiler testcase names, so you may have to work a bit to find a unique name if it's something common. ### Tests for multiple files diff --git a/Gulpfile.js b/Gulpfile.js index 704fbba4447..867f35d4ff7 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -26,7 +26,7 @@ const exec = require("./scripts/build/exec"); const browserify = require("./scripts/build/browserify"); const prepend = require("./scripts/build/prepend"); const { removeSourceMaps } = require("./scripts/build/sourcemaps"); -const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex"); +const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex"); const { libraryTargets, generateLibs } = require("./scripts/build/lib"); const { runConsoleTests, cleanTestDirs, writeTestConfigFile, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests"); diff --git a/Jakefile.js b/Jakefile.js index 6ecb67ab9ce..68cfbf7eef6 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -147,14 +147,14 @@ task(TaskNames.local, [ task("default", [TaskNames.local]); const RunTestsPrereqs = [TaskNames.lib, Paths.servicesDefinitionFile, Paths.typescriptDefinitionFile, Paths.tsserverLibraryDefinitionFile]; -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... d[ebug]=true."); +desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); task(TaskNames.runtestsParallel, RunTestsPrereqs, function () { tsbuild([ConfigFileFor.runjs], true, () => { runConsoleTests("min", /*parallel*/ true); }); }, { async: true }); -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... d[ebug]=true."); +desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); task(TaskNames.runtests, RunTestsPrereqs, function () { tsbuild([ConfigFileFor.runjs], true, () => { runConsoleTests('mocha-fivemat-progress-reporter', /*runInParallel*/ false); @@ -520,7 +520,6 @@ function runConsoleTests(defaultReporter, runInParallel) { } let testTimeout = process.env.timeout || defaultTestTimeout; - const debug = process.env.debug || process.env["debug-brk"] || process.env.d; const inspect = process.env.inspect || process.env["inspect-brk"] || process.env.i; const runners = process.env.runners || process.env.runner || process.env.ru; const tests = process.env.test || process.env.tests || process.env.t; From 513c6af4e0956762d3b1987efa4cad203602621c Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 30 Oct 2018 07:29:18 -0700 Subject: [PATCH 148/262] Update user baselines (#28228) --- tests/baselines/reference/user/bluebird.log | 44 +++++++------------ .../user/chrome-devtools-frontend.log | 2 - tests/baselines/reference/user/lodash.log | 1 - 3 files changed, 17 insertions(+), 30 deletions(-) diff --git a/tests/baselines/reference/user/bluebird.log b/tests/baselines/reference/user/bluebird.log index 4d7acc487ae..594d25e27ca 100644 --- a/tests/baselines/reference/user/bluebird.log +++ b/tests/baselines/reference/user/bluebird.log @@ -9,17 +9,12 @@ node_modules/bluebird/js/release/async.js(108,21): error TS2300: Duplicate ident node_modules/bluebird/js/release/async.js(118,21): error TS2300: Duplicate identifier 'settlePromises'. node_modules/bluebird/js/release/bluebird.js(5,15): error TS2367: This condition will always return 'false' since the types 'PromiseConstructor' and 'typeof Promise' have no overlap. node_modules/bluebird/js/release/bluebird.js(10,10): error TS2339: Property 'noConflict' does not exist on type 'typeof Promise'. -node_modules/bluebird/js/release/catch_filter.js(27,28): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: {}) => string[]) | ((o: any) => string[])' has no compatible call signatures. node_modules/bluebird/js/release/debuggability.js(19,20): error TS2367: This condition will always return 'true' since the types 'string | undefined' and 'number' have no overlap. node_modules/bluebird/js/release/debuggability.js(24,19): error TS2367: This condition will always return 'true' since the types 'string | undefined' and 'number' have no overlap. node_modules/bluebird/js/release/debuggability.js(27,26): error TS2367: This condition will always return 'true' since the types 'string | undefined' and 'number' have no overlap. node_modules/bluebird/js/release/debuggability.js(30,24): error TS2367: This condition will always return 'true' since the types 'string | undefined' and 'number' have no overlap. -node_modules/bluebird/js/release/debuggability.js(161,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/debuggability.js(163,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. node_modules/bluebird/js/release/debuggability.js(168,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'event' must be of type 'CustomEvent', but here has type 'Event'. node_modules/bluebird/js/release/debuggability.js(174,26): error TS2339: Property 'detail' does not exist on type 'Event'. -node_modules/bluebird/js/release/debuggability.js(175,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/debuggability.js(176,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. node_modules/bluebird/js/release/debuggability.js(199,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["multipleResolves", MultipleResolveListener]'. Property '0' is missing in type 'IArguments'. node_modules/bluebird/js/release/debuggability.js(242,56): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. @@ -32,12 +27,10 @@ node_modules/bluebird/js/release/debuggability.js(760,37): error TS2339: Propert node_modules/bluebird/js/release/debuggability.js(799,38): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. node_modules/bluebird/js/release/debuggability.js(808,25): error TS2554: Expected 0 arguments, but got 1. node_modules/bluebird/js/release/errors.js(10,49): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/errors.js(46,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. node_modules/bluebird/js/release/errors.js(92,18): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{ (a: T[]): ReadonlyArray; (f: T): T; (o: T): Readonly; } | ((obj: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/errors.js(99,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/generators.js(159,21): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/generators.js(190,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/generators.js(208,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/generators.js(159,21): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/generators.js(190,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/generators.js(208,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/generators.js(220,5): error TS2554: Expected 0 arguments, but got 1. node_modules/bluebird/js/release/map.js(30,10): error TS2551: Property '_init$' does not exist on type 'MappingPromiseArray'. Did you mean '_init'? node_modules/bluebird/js/release/map.js(36,23): error TS2339: Property '_values' does not exist on type 'MappingPromiseArray'. @@ -55,15 +48,13 @@ node_modules/bluebird/js/release/map.js(113,18): error TS2339: Property '_isReso node_modules/bluebird/js/release/map.js(127,10): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. node_modules/bluebird/js/release/map.js(156,66): error TS2339: Property 'promise' does not exist on type 'MappingPromiseArray'. node_modules/bluebird/js/release/method.js(15,46): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. -node_modules/bluebird/js/release/nodeback.js(21,20): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: {}) => string[]) | ((o: any) => string[])' has no compatible call signatures. node_modules/bluebird/js/release/nodeify.js(32,19): error TS2339: Property 'cause' does not exist on type 'Error'. -node_modules/bluebird/js/release/promise.js(4,12): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(4,12): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(7,24): error TS2339: Property 'PromiseInspection' does not exist on type 'typeof Promise'. -node_modules/bluebird/js/release/promise.js(10,27): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(10,27): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(20,32): error TS2322: Type 'null' is not assignable to type 'Domain'. -node_modules/bluebird/js/release/promise.js(33,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/promise.js(62,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/promise.js(65,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(62,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(65,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(123,14): error TS2339: Property '_warn' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(148,14): error TS2551: Property 'isFulfilled' does not exist on type 'Promise'. Did you mean '_setFulfilled'? node_modules/bluebird/js/release/promise.js(149,37): error TS2339: Property 'value' does not exist on type 'Promise'. @@ -72,7 +63,7 @@ node_modules/bluebird/js/release/promise.js(152,36): error TS2339: Property 'rea node_modules/bluebird/js/release/promise.js(160,14): error TS2339: Property '_warn' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(177,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(207,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(214,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(214,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(238,63): error TS2339: Property '_boundTo' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(241,14): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(253,20): error TS2339: Property '_unsetRejectionIsUnhandled' does not exist on type 'Promise'. @@ -92,7 +83,7 @@ node_modules/bluebird/js/release/promise.js(480,10): error TS2339: Property '_ca node_modules/bluebird/js/release/promise.js(481,10): error TS2339: Property '_pushContext' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(483,18): error TS2339: Property '_execute' does not exist on type 'Promise'. node_modules/bluebird/js/release/promise.js(489,10): error TS2339: Property '_popContext' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(506,19): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promise.js(506,19): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(558,22): error TS2339: Property '_promiseCancelled' does not exist on type '{}'. node_modules/bluebird/js/release/promise.js(572,23): error TS2339: Property '_isResolved' does not exist on type '{}'. node_modules/bluebird/js/release/promise.js(574,26): error TS2339: Property '_promiseFulfilled' does not exist on type '{}'. @@ -104,7 +95,7 @@ node_modules/bluebird/js/release/promise.js(699,10): error TS2339: Property '_cl node_modules/bluebird/js/release/promise_array.js(71,18): error TS2339: Property '_resolveEmptyArray' does not exist on type 'PromiseArray'. node_modules/bluebird/js/release/promise_array.js(109,30): error TS2554: Expected 0-1 arguments, but got 2. node_modules/bluebird/js/release/promise_array.js(111,30): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/promisify.js(54,27): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/promisify.js(54,27): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promisify.js(69,22): error TS2554: Expected 0-1 arguments, but got 3. node_modules/bluebird/js/release/promisify.js(93,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'any'. node_modules/bluebird/js/release/promisify.js(183,39): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. @@ -112,9 +103,8 @@ node_modules/bluebird/js/release/promisify.js(183,39): error TS2345: Argument of node_modules/bluebird/js/release/promisify.js(249,17): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/bluebird/js/release/promisify.js(252,24): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/bluebird/js/release/promisify.js(264,12): error TS2722: Cannot invoke an object which is possibly 'undefined'. -node_modules/bluebird/js/release/promisify.js(270,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/promisify.js(285,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/props.js(47,20): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: {}) => string[]) | ((o: any) => string[])' has no compatible call signatures. +node_modules/bluebird/js/release/promisify.js(270,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promisify.js(285,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/props.js(65,10): error TS2339: Property '_values' does not exist on type 'PropertiesPromiseArray'. node_modules/bluebird/js/release/props.js(66,32): error TS2339: Property '_totalResolved' does not exist on type 'PropertiesPromiseArray'. node_modules/bluebird/js/release/props.js(67,31): error TS2339: Property '_length' does not exist on type 'PropertiesPromiseArray'. @@ -166,16 +156,16 @@ node_modules/bluebird/js/release/some.js(107,10): error TS2339: Property '_value node_modules/bluebird/js/release/some.js(111,10): error TS2339: Property '_values' does not exist on type 'SomePromiseArray'. node_modules/bluebird/js/release/some.js(111,23): error TS2339: Property '_totalResolved' does not exist on type 'SomePromiseArray'. node_modules/bluebird/js/release/some.js(115,17): error TS2339: Property 'length' does not exist on type 'SomePromiseArray'. -node_modules/bluebird/js/release/some.js(121,12): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. +node_modules/bluebird/js/release/some.js(121,12): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/some.js(125,10): error TS2551: Property '_reject' does not exist on type 'SomePromiseArray'. Did you mean '_rejected'? node_modules/bluebird/js/release/some.js(133,23): error TS2339: Property 'promise' does not exist on type 'SomePromiseArray'. node_modules/bluebird/js/release/using.js(78,20): error TS2339: Property 'doDispose' does not exist on type 'Disposer'. node_modules/bluebird/js/release/using.js(97,23): error TS2339: Property 'data' does not exist on type 'FunctionDisposer'. -node_modules/bluebird/js/release/using.js(223,15): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. -node_modules/bluebird/js/release/util.js(97,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. +node_modules/bluebird/js/release/using.js(223,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/util.js(251,28): error TS2554: Expected 0 arguments, but got 2. -node_modules/bluebird/js/release/util.js(279,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any) | ((o: any, key: any, desc: any) => any)' has no compatible call signatures. -node_modules/bluebird/js/release/util.js(279,45): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((o: any, p: string | number | symbol) => PropertyDescriptor | undefined) | ((o: any, key: any) => { value: any; })' has no compatible call signatures. +node_modules/bluebird/js/release/util.js(279,45): error TS2345: Argument of type 'PropertyDescriptor | { value: any; } | undefined' is not assignable to parameter of type 'PropertyDescriptor & ThisType'. + Type 'undefined' is not assignable to type 'PropertyDescriptor & ThisType'. + Type 'undefined' is not assignable to type 'PropertyDescriptor'. node_modules/bluebird/js/release/util.js(367,25): error TS2304: Cannot find name 'chrome'. node_modules/bluebird/js/release/util.js(367,51): error TS2304: Cannot find name 'chrome'. node_modules/bluebird/js/release/util.js(368,25): error TS2304: Cannot find name 'chrome'. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 7e4641c5f1e..7841072577e 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -8939,7 +8939,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(198 node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(48,37): error TS2339: Property 'deoptReason' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(97,15): error TS2339: Property 'self' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. Property 'self' does not exist on type 'ProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(118,27): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((key: any) => any) | ((key: string) => ProfileDataGridNode)' has no compatible call signatures. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(131,19): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. Property '_populated' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileDataGrid.js(133,15): error TS2339: Property '_populated' does not exist on type 'ProfileDataGridNode | ProfileDataGridTree'. @@ -9077,7 +9076,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxControll node_modules/chrome-devtools-frontend/front_end/profiler/TargetsComboBoxController.js(97,25): error TS2339: Property 'selectedIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(63,17): error TS2339: Property 'populate' does not exist on type 'TopDownProfileDataGridTree | TopDownProfileDataGridNode'. Property 'populate' does not exist on type 'TopDownProfileDataGridTree'. -node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid.js(73,17): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((key: any) => any) | ((key: string) => ProfileDataGridNode)' has no compatible call signatures. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(168,40): error TS2345: Argument of type 'S' is not assignable to parameter of type 'S'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(170,24): error TS2345: Argument of type 'S' is not assignable to parameter of type 'T'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(194,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index 0418c19fe2c..f26218b780d 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -424,7 +424,6 @@ node_modules/lodash/throttle.js(62,31): error TS2345: Argument of type '{ 'leadi node_modules/lodash/toLower.js(11,21): error TS8024: JSDoc '@param' tag has name 'string', but there is no parameter with that name. node_modules/lodash/toUpper.js(11,21): error TS8024: JSDoc '@param' tag has name 'string', but there is no parameter with that name. node_modules/lodash/transform.js(46,14): error TS2554: Expected 0-1 arguments, but got 2. -node_modules/lodash/transform.js(59,3): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((array?: any[] | undefined, iteratee: Function) => any[]) | ((object: any, iteratee: Function) => any)' has no compatible call signatures. node_modules/lodash/transform.js(60,12): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/lodash/trim.js(20,10): error TS1003: Identifier expected. node_modules/lodash/trim.js(20,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. From e0d210d0279e69f0a3b60ef25df07b7670bccc73 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 08:18:18 -0700 Subject: [PATCH 149/262] Add tests --- .../conformance/types/spread/objectSpread.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/cases/conformance/types/spread/objectSpread.ts b/tests/cases/conformance/types/spread/objectSpread.ts index c7cf5e49eed..810a8f3d496 100644 --- a/tests/cases/conformance/types/spread/objectSpread.ts +++ b/tests/cases/conformance/types/spread/objectSpread.ts @@ -120,3 +120,24 @@ let a = 12; let shortCutted: { a: number, b: string } = { ...o, a } // non primitive let spreadNonPrimitive = { ...{}}; + +// generic spreads +function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { + let x01 = { ...t }; + let x02 = { ...t, ...t }; + let x03 = { ...t, ...u }; + let x04 = { ...u, ...t }; + let x05 = { a: 5, b: 'hi', ...t }; + let x06 = { ...t, a: 5, b: 'hi' }; + let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; + let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; + let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; + let x11 = { ...v }; + let x12 = { ...v, ...obj }; + let x13 = { ...w }; + let x14 = { ...w, ...obj }; + let x15 = { ...t, ...v }; + let x16 = { ...t, ...w }; + let x17 = { ...t, ...w, ...obj }; + let x18 = { ...t, ...v, ...w }; +} From 0f308f50744da64bce435c29e3ef522c82b41a07 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 08:18:25 -0700 Subject: [PATCH 150/262] Accept new baselines --- tests/baselines/reference/objectSpread.js | 41 ++++++ .../baselines/reference/objectSpread.symbols | 114 +++++++++++++++ tests/baselines/reference/objectSpread.types | 136 ++++++++++++++++++ 3 files changed, 291 insertions(+) diff --git a/tests/baselines/reference/objectSpread.js b/tests/baselines/reference/objectSpread.js index 1aef3a3bc99..c47cc649498 100644 --- a/tests/baselines/reference/objectSpread.js +++ b/tests/baselines/reference/objectSpread.js @@ -119,6 +119,27 @@ let a = 12; let shortCutted: { a: number, b: string } = { ...o, a } // non primitive let spreadNonPrimitive = { ...{}}; + +// generic spreads +function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { + let x01 = { ...t }; + let x02 = { ...t, ...t }; + let x03 = { ...t, ...u }; + let x04 = { ...u, ...t }; + let x05 = { a: 5, b: 'hi', ...t }; + let x06 = { ...t, a: 5, b: 'hi' }; + let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; + let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; + let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; + let x11 = { ...v }; + let x12 = { ...v, ...obj }; + let x13 = { ...w }; + let x14 = { ...w, ...obj }; + let x15 = { ...t, ...v }; + let x16 = { ...t, ...w }; + let x17 = { ...t, ...w, ...obj }; + let x18 = { ...t, ...v, ...w }; +} //// [objectSpread.js] @@ -214,3 +235,23 @@ var a = 12; var shortCutted = __assign({}, o, { a: a }); // non primitive var spreadNonPrimitive = __assign({}, {}); +// generic spreads +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 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 x11 = __assign({}, v); + var x12 = __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); +} diff --git a/tests/baselines/reference/objectSpread.symbols b/tests/baselines/reference/objectSpread.symbols index 0bbcd4a9f4b..6702ff5c909 100644 --- a/tests/baselines/reference/objectSpread.symbols +++ b/tests/baselines/reference/objectSpread.symbols @@ -452,3 +452,117 @@ let shortCutted: { a: number, b: string } = { ...o, a } let spreadNonPrimitive = { ...{}}; >spreadNonPrimitive : Symbol(spreadNonPrimitive, Decl(objectSpread.ts, 119, 3)) +// generic spreads +function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { +>genericSpread : Symbol(genericSpread, Decl(objectSpread.ts, 119, 42)) +>T : Symbol(T, Decl(objectSpread.ts, 122, 23)) +>U : Symbol(U, Decl(objectSpread.ts, 122, 25)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>T : Symbol(T, Decl(objectSpread.ts, 122, 23)) +>u : Symbol(u, Decl(objectSpread.ts, 122, 34)) +>U : Symbol(U, Decl(objectSpread.ts, 122, 25)) +>v : Symbol(v, Decl(objectSpread.ts, 122, 40)) +>T : Symbol(T, Decl(objectSpread.ts, 122, 23)) +>U : Symbol(U, Decl(objectSpread.ts, 122, 25)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) +>T : Symbol(T, Decl(objectSpread.ts, 122, 23)) +>s : Symbol(s, Decl(objectSpread.ts, 122, 59)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) +>x : Symbol(x, Decl(objectSpread.ts, 122, 79)) + + let x01 = { ...t }; +>x01 : Symbol(x01, Decl(objectSpread.ts, 123, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) + + let x02 = { ...t, ...t }; +>x02 : Symbol(x02, Decl(objectSpread.ts, 124, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) + + let x03 = { ...t, ...u }; +>x03 : Symbol(x03, Decl(objectSpread.ts, 125, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>u : Symbol(u, Decl(objectSpread.ts, 122, 34)) + + let x04 = { ...u, ...t }; +>x04 : Symbol(x04, Decl(objectSpread.ts, 126, 7)) +>u : Symbol(u, Decl(objectSpread.ts, 122, 34)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) + + let x05 = { a: 5, b: 'hi', ...t }; +>x05 : Symbol(x05, Decl(objectSpread.ts, 127, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 127, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 127, 21)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) + + let x06 = { ...t, a: 5, b: 'hi' }; +>x06 : Symbol(x06, Decl(objectSpread.ts, 128, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>a : Symbol(a, Decl(objectSpread.ts, 128, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 128, 27)) + + let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; +>x07 : Symbol(x07, Decl(objectSpread.ts, 129, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 129, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 129, 21)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>c : Symbol(c, Decl(objectSpread.ts, 129, 36)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; +>x09 : Symbol(x09, Decl(objectSpread.ts, 130, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 130, 15)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>b : Symbol(b, Decl(objectSpread.ts, 130, 27)) +>c : Symbol(c, Decl(objectSpread.ts, 130, 36)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; +>x10 : Symbol(x10, Decl(objectSpread.ts, 131, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 131, 15)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>b : Symbol(b, Decl(objectSpread.ts, 131, 27)) +>u : Symbol(u, Decl(objectSpread.ts, 122, 34)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x11 = { ...v }; +>x11 : Symbol(x11, Decl(objectSpread.ts, 132, 7)) +>v : Symbol(v, Decl(objectSpread.ts, 122, 40)) + + let x12 = { ...v, ...obj }; +>x12 : Symbol(x12, Decl(objectSpread.ts, 133, 7)) +>v : Symbol(v, Decl(objectSpread.ts, 122, 40)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x13 = { ...w }; +>x13 : Symbol(x13, Decl(objectSpread.ts, 134, 7)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) + + let x14 = { ...w, ...obj }; +>x14 : Symbol(x14, Decl(objectSpread.ts, 135, 7)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x15 = { ...t, ...v }; +>x15 : Symbol(x15, Decl(objectSpread.ts, 136, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>v : Symbol(v, Decl(objectSpread.ts, 122, 40)) + + let x16 = { ...t, ...w }; +>x16 : Symbol(x16, Decl(objectSpread.ts, 137, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) + + let x17 = { ...t, ...w, ...obj }; +>x17 : Symbol(x17, Decl(objectSpread.ts, 138, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) +>obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) + + let x18 = { ...t, ...v, ...w }; +>x18 : Symbol(x18, Decl(objectSpread.ts, 139, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +>v : Symbol(v, Decl(objectSpread.ts, 122, 40)) +>w : Symbol(w, Decl(objectSpread.ts, 122, 50)) +} + diff --git a/tests/baselines/reference/objectSpread.types b/tests/baselines/reference/objectSpread.types index fc60b0d88cf..8df457a162d 100644 --- a/tests/baselines/reference/objectSpread.types +++ b/tests/baselines/reference/objectSpread.types @@ -578,3 +578,139 @@ let spreadNonPrimitive = { ...{}}; >{} : object >{} : {} +// generic spreads +function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { +>genericSpread : (t: T, u: U, v: T | U, w: T | { s: string; }, obj: { x: number; }) => void +>t : T +>u : U +>v : T | U +>w : T | { s: string; } +>s : string +>obj : { x: number; } +>x : number + + let x01 = { ...t }; +>x01 : T +>{ ...t } : T +>t : T + + let x02 = { ...t, ...t }; +>x02 : T +>{ ...t, ...t } : T +>t : T +>t : T + + let x03 = { ...t, ...u }; +>x03 : T & U +>{ ...t, ...u } : T & U +>t : T +>u : U + + let x04 = { ...u, ...t }; +>x04 : U & T +>{ ...u, ...t } : U & T +>u : U +>t : T + + let x05 = { a: 5, b: 'hi', ...t }; +>x05 : { a: number; b: string; } & T +>{ a: 5, b: 'hi', ...t } : { a: number; b: string; } & T +>a : number +>5 : 5 +>b : string +>'hi' : "hi" +>t : T + + let x06 = { ...t, a: 5, b: 'hi' }; +>x06 : T & { a: number; b: string; } +>{ ...t, a: 5, b: 'hi' } : T & { a: number; b: string; } +>t : T +>a : number +>5 : 5 +>b : string +>'hi' : "hi" + + let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; +>x07 : { a: number; b: string; } & T & { x: number; c: boolean; } +>{ a: 5, b: 'hi', ...t, c: true, ...obj } : { a: number; b: string; } & T & { x: number; c: boolean; } +>a : number +>5 : 5 +>b : string +>'hi' : "hi" +>t : T +>c : boolean +>true : true +>obj : { x: number; } + + let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; +>x09 : { a: number; } & T & { x: number; b: string; c: boolean; } +>{ a: 5, ...t, b: 'hi', c: true, ...obj } : { a: number; } & T & { x: number; b: string; c: boolean; } +>a : number +>5 : 5 +>t : T +>b : string +>'hi' : "hi" +>c : boolean +>true : true +>obj : { x: number; } + + let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; +>x10 : { a: number; } & T & { b: string; } & U & { x: number; } +>{ a: 5, ...t, b: 'hi', ...u, ...obj } : { a: number; } & T & { b: string; } & U & { x: number; } +>a : number +>5 : 5 +>t : T +>b : string +>'hi' : "hi" +>u : U +>obj : { x: number; } + + let x11 = { ...v }; +>x11 : T | U +>{ ...v } : T | U +>v : T | U + + let x12 = { ...v, ...obj }; +>x12 : (T & { x: number; }) | (U & { x: number; }) +>{ ...v, ...obj } : (T & { x: number; }) | (U & { x: number; }) +>v : T | U +>obj : { x: number; } + + let x13 = { ...w }; +>x13 : T | { s: string; } +>{ ...w } : T | { s: string; } +>w : T | { s: string; } + + let x14 = { ...w, ...obj }; +>x14 : (T & { x: number; }) | { x: number; s: string; } +>{ ...w, ...obj } : (T & { x: number; }) | { x: number; s: string; } +>w : T | { s: string; } +>obj : { x: number; } + + let x15 = { ...t, ...v }; +>x15 : T | (T & U) +>{ ...t, ...v } : T | (T & U) +>t : T +>v : T | U + + let x16 = { ...t, ...w }; +>x16 : T | (T & { s: string; }) +>{ ...t, ...w } : T | (T & { s: string; }) +>t : T +>w : T | { s: string; } + + let x17 = { ...t, ...w, ...obj }; +>x17 : (T & { x: number; }) | (T & { x: number; s: string; }) +>{ ...t, ...w, ...obj } : (T & { x: number; }) | (T & { x: number; s: string; }) +>t : T +>w : T | { s: string; } +>obj : { x: number; } + + let x18 = { ...t, ...v, ...w }; +>x18 : T | (T & U) | (T & { s: string; }) | (T & U & { s: string; }) +>{ ...t, ...v, ...w } : T | (T & U) | (T & { s: string; }) | (T & U & { s: string; }) +>t : T +>v : T | U +>w : T | { s: string; } +} + From 7c515bf6e86c3598ba7e14e10e00c62a06da789b Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 08:41:31 -0700 Subject: [PATCH 151/262] Remove `toSortedArray` and `toDeduplicatedSortedArray`, use `sort` and `sortAndDeduplicate` (#28214) --- src/compiler/commandLineParser.ts | 2 +- src/compiler/core.ts | 20 ++++++++++++------- src/compiler/program.ts | 6 +++--- src/compiler/utilities.ts | 2 +- src/harness/compiler.ts | 2 +- src/jsTyping/types.ts | 4 ---- src/server/project.ts | 8 ++++---- src/server/typingsCache.ts | 2 +- src/server/utilities.ts | 16 --------------- src/testRunner/projectsRunner.ts | 6 ++---- .../unittests/tsserverProjectSystem.ts | 2 +- src/testRunner/unittests/typingsInstaller.ts | 6 +++--- .../reference/api/tsserverlibrary.d.ts | 10 +++++----- tests/baselines/reference/api/typescript.d.ts | 10 +++++----- 14 files changed, 40 insertions(+), 56 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 968e5bb756e..782f76b3d1f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1146,7 +1146,7 @@ namespace ts { } /* @internal */ - export function printHelp(optionsList: CommandLineOption[], syntaxPrefix = "") { + export function printHelp(optionsList: ReadonlyArray, syntaxPrefix = "") { const output: string[] = []; // We want to align our "syntax" and "examples" commands to a certain margin. diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 6288f30b144..8c976cee9ee 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -16,6 +16,10 @@ namespace ts { [index: string]: T; } + export interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + export interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -815,8 +819,8 @@ namespace ts { /** * Deduplicates an array that has already been sorted. */ - function deduplicateSorted(array: ReadonlyArray, comparer: EqualityComparer | Comparer): T[] { - if (array.length === 0) return []; + function deduplicateSorted(array: SortedReadonlyArray, comparer: EqualityComparer | Comparer): SortedReadonlyArray { + if (array.length === 0) return emptyArray as any as SortedReadonlyArray; let last = array[0]; const deduplicated: T[] = [last]; @@ -838,7 +842,7 @@ namespace ts { deduplicated.push(last = next); } - return deduplicated; + return deduplicated as any as SortedReadonlyArray; } export function insertSorted(array: SortedArray, insert: T, compare: Comparer): void { @@ -853,8 +857,10 @@ namespace ts { } } - export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + export function sortAndDeduplicate(array: ReadonlyArray): SortedReadonlyArray; + export function sortAndDeduplicate(array: ReadonlyArray, comparer: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray; + export function sortAndDeduplicate(array: ReadonlyArray, comparer?: Comparer, equalityComparer?: EqualityComparer): SortedReadonlyArray { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive as any as Comparer); } export function arrayIsEqualTo(array1: ReadonlyArray | undefined, array2: ReadonlyArray | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { @@ -1035,8 +1041,8 @@ namespace ts { /** * Returns a new sorted array. */ - export function sort(array: ReadonlyArray, comparer: Comparer): T[] { - return array.slice().sort(comparer); + export function sort(array: ReadonlyArray, comparer?: Comparer): SortedReadonlyArray { + return (array.length === 0 ? array : array.slice().sort(comparer)) as SortedReadonlyArray; } export function arrayIterator(array: ReadonlyArray): Iterator { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 85c6b27f4ec..997bdaa80c7 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -198,7 +198,7 @@ namespace ts { }; } - export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { + export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray { const diagnostics = [ ...program.getConfigFileParsingDiagnostics(), ...program.getOptionsDiagnostics(cancellationToken), @@ -1817,7 +1817,7 @@ namespace ts { return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } - function getOptionsDiagnostics(): Diagnostic[] { + function getOptionsDiagnostics(): SortedReadonlyArray { return sortAndDeduplicateDiagnostics(concatenate( fileProcessingDiagnostics.getGlobalDiagnostics(), concatenate( @@ -1838,7 +1838,7 @@ namespace ts { return diagnostics; } - function getGlobalDiagnostics(): Diagnostic[] { + function getGlobalDiagnostics(): SortedReadonlyArray { return sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 96b9c3c2f67..a969d580b86 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7,7 +7,7 @@ namespace ts { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } - export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[] { + export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray { return sortAndDeduplicate(diagnostics, compareDiagnostics); } } diff --git a/src/harness/compiler.ts b/src/harness/compiler.ts index 7d41545708b..532a2d65578 100644 --- a/src/harness/compiler.ts +++ b/src/harness/compiler.ts @@ -58,7 +58,7 @@ namespace compiler { private _inputs: documents.TextDocument[] = []; private _inputsAndOutputs: collections.SortedMap; - constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: ts.Diagnostic[]) { + constructor(host: fakes.CompilerHost, options: ts.CompilerOptions, program: ts.Program | undefined, result: ts.EmitResult | undefined, diagnostics: ReadonlyArray) { this.host = host; this.program = program; this.result = result; diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index 408d30a6511..6bc3e667f87 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -8,10 +8,6 @@ declare namespace ts.server { export type EventEndInstallTypes = "event::endInstallTypes"; export type EventInitializationFailed = "event::initializationFailed"; - export interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } - export interface TypingInstallerResponse { readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } diff --git a/src/server/project.ts b/src/server/project.ts index fb6ec4b80fc..ff2e3539b6b 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -554,7 +554,7 @@ namespace ts.server { } getExternalFiles(): SortedReadonlyArray { - return toSortedArray(flatMapToMutable(this.plugins, plugin => { + return sort(flatMap(this.plugins, plugin => { if (typeof plugin.module.getExternalFiles !== "function") return; try { return plugin.module.getExternalFiles(this); @@ -871,7 +871,7 @@ namespace ts.server { (result || (result = [])).push(...unResolved); } } - this.lastCachedUnresolvedImportsList = result ? toDeduplicatedSortedArray(result) : emptyArray; + this.lastCachedUnresolvedImportsList = result ? sortAndDeduplicate(result) : emptyArray; } this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); @@ -888,7 +888,7 @@ namespace ts.server { /*@internal*/ updateTypingFiles(typingFiles: SortedReadonlyArray) { - enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), + enumerateInsertsAndDeletes(typingFiles, this.typingFiles, getStringComparer(!this.useCaseSensitiveFileNames()), /*inserted*/ noop, removed => this.detachScriptInfoFromProject(removed) ); @@ -959,7 +959,7 @@ namespace ts.server { const oldExternalFiles = this.externalFiles || emptyArray as SortedReadonlyArray; this.externalFiles = this.getExternalFiles(); - enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), + enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, getStringComparer(!this.useCaseSensitiveFileNames()), // Ensure a ScriptInfo is created for new external files. This is performed indirectly // by the LSHost for files in the program when the program is retrieved above but // the program doesn't contain external files so this must be done explicitly. diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index 64a117bbe25..d3b6e21a21c 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -130,7 +130,7 @@ namespace ts.server { } updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, newTypings: string[]) { - const typings = toSortedArray(newTypings); + const typings = sort(newTypings); this.perProjectCache.set(projectName, { compilerOptions, typeAcquisition, diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 6dcfff6f7e2..4eac1730b77 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -206,22 +206,6 @@ namespace ts.server { } } - export function toSortedArray(arr: string[]): SortedArray; - export function toSortedArray(arr: T[], comparer: Comparer): SortedArray; - export function toSortedArray(arr: T[], comparer?: Comparer): SortedArray { - arr.sort(comparer); - return arr as SortedArray; - } - - export function toDeduplicatedSortedArray(arr: string[]): SortedArray { - arr.sort(); - filterMutate(arr, isNonDuplicateInSortedArray); - return arr as SortedArray; - } - function isNonDuplicateInSortedArray(value: T, index: number, array: T[]) { - return index === 0 || value !== array[index - 1]; - } - const indentStr = "\n "; /* @internal */ diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index 3dcf1911dde..2d15133f399 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -310,9 +310,7 @@ namespace project { const program = ts.createProgram(getInputFiles(), compilerOptions, compilerHost); const errors = ts.getPreEmitDiagnostics(program); - const emitResult = program.emit(); - ts.addRange(errors, emitResult.diagnostics); - const sourceMapData = emitResult.sourceMaps; + const { sourceMaps: sourceMapData, diagnostics: emitDiagnostics } = program.emit(); // Clean up source map data that will be used in baselining if (sourceMapData) { @@ -329,7 +327,7 @@ namespace project { configFileSourceFiles, moduleKind, program, - errors, + errors: ts.concatenate(errors, emitDiagnostics), sourceMapData }; } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 38d2d4867a0..3ffd28702a2 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -118,7 +118,7 @@ namespace ts.projectSystem { this.projectService.updateTypingsForProject(response); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation); this.install(request); } diff --git a/src/testRunner/unittests/typingsInstaller.ts b/src/testRunner/unittests/typingsInstaller.ts index a718a12f548..b06c22d5d79 100644 --- a/src/testRunner/unittests/typingsInstaller.ts +++ b/src/testRunner/unittests/typingsInstaller.ts @@ -310,7 +310,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { enqueueIsCalled = true; super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } @@ -409,7 +409,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { @@ -451,7 +451,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index ae04e45229a..2ea0d677709 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -27,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -3126,7 +3129,7 @@ declare namespace ts { /** Non-internal stuff goes here */ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -4153,7 +4156,7 @@ declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; interface FormatDiagnosticsHost { getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -4457,9 +4460,6 @@ declare namespace ts.server { type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } interface TypingInstallerResponse { readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index fd4f5752614..91c8c397501 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -27,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } interface SortedArray extends Array { " __sortedArrayBrand": any; } @@ -3126,7 +3129,7 @@ declare namespace ts { /** Non-internal stuff goes here */ declare namespace ts { function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -4153,7 +4156,7 @@ declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; interface FormatDiagnosticsHost { getCurrentDirectory(): string; getCanonicalFileName(fileName: string): string; @@ -4457,9 +4460,6 @@ declare namespace ts.server { type EventBeginInstallTypes = "event::beginInstallTypes"; type EventEndInstallTypes = "event::endInstallTypes"; type EventInitializationFailed = "event::initializationFailed"; - interface SortedReadonlyArray extends ReadonlyArray { - " __sortedArrayBrand": any; - } interface TypingInstallerResponse { readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | ActionValueInspected | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; } From acc34bd95dafe84c4e8f47a48809666e3e160006 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 10:15:01 -0700 Subject: [PATCH 152/262] Miscellaneous code cleanup relating to module resolution (#28092) * Miscellaneous code cleanup relating to module resolution * Revert if condition --- src/compiler/resolutionCache.ts | 8 +-- src/harness/virtualFileSystemWithWatch.ts | 8 +-- src/server/project.ts | 64 +++++++---------------- 3 files changed, 28 insertions(+), 52 deletions(-) diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index b22d90a76f6..6c8c79adefb 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -79,7 +79,7 @@ namespace ts { export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache { let filesWithChangedSetOfUnresolvedImports: Path[] | undefined; let filesWithInvalidatedResolutions: Map | undefined; - let filesWithInvalidatedNonRelativeUnresolvedImports: Map> | undefined; + let filesWithInvalidatedNonRelativeUnresolvedImports: ReadonlyMap> | undefined; let allFilesHaveInvalidatedResolution = false; const nonRelativeExternalModuleResolutions = createMultiMap(); @@ -241,14 +241,14 @@ namespace ts { } function resolveNamesWithLocalCache( - names: string[], + names: ReadonlyArray, containingFile: string, redirectedReference: ResolvedProjectReference | undefined, cache: Map>, perDirectoryCacheWithRedirects: CacheWithRedirects>, loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, - reusedNames: string[] | undefined, + reusedNames: ReadonlyArray | undefined, logChanges: boolean): (R | undefined)[] { const path = resolutionHost.toPath(containingFile); @@ -675,7 +675,7 @@ namespace ts { ); } - function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: Map>) { + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap: ReadonlyMap>) { Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index d2b7c7869c5..bd31a04a0df 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -128,7 +128,7 @@ interface Array {}` return s && isString((s).symLink); } - function invokeWatcherCallbacks(callbacks: T[], invokeCallback: (cb: T) => void): void { + function invokeWatcherCallbacks(callbacks: ReadonlyArray | undefined, invokeCallback: (cb: T) => void): void { if (callbacks) { // The array copy is made to ensure that even if one of the callback removes the callbacks, // we dont miss any callbacks following it @@ -650,15 +650,15 @@ interface Array {}` // For overriding the methods invokeWatchedDirectoriesCallback(folderFullPath: string, relativePath: string) { - invokeWatcherCallbacks(this.watchedDirectories.get(this.toPath(folderFullPath))!, cb => this.directoryCallback(cb, relativePath)); + invokeWatcherCallbacks(this.watchedDirectories.get(this.toPath(folderFullPath)), cb => this.directoryCallback(cb, relativePath)); } invokeWatchedDirectoriesRecursiveCallback(folderFullPath: string, relativePath: string) { - invokeWatcherCallbacks(this.watchedDirectoriesRecursive.get(this.toPath(folderFullPath))!, cb => this.directoryCallback(cb, relativePath)); + invokeWatcherCallbacks(this.watchedDirectoriesRecursive.get(this.toPath(folderFullPath)), cb => this.directoryCallback(cb, relativePath)); } private invokeFileWatcher(fileFullPath: string, eventKind: FileWatcherEventKind, useFileNameInCallback?: boolean) { - invokeWatcherCallbacks(this.watchedFiles.get(this.toPath(fileFullPath))!, ({ cb, fileName }) => cb(useFileNameInCallback ? fileName : fileFullPath, eventKind)); + invokeWatcherCallbacks(this.watchedFiles.get(this.toPath(fileFullPath)), ({ cb, fileName }) => cb(useFileNameInCallback ? fileName : fileFullPath, eventKind)); } private getRelativePathToDirectory(directoryFullPath: string, fileFullPath: string) { diff --git a/src/server/project.ts b/src/server/project.ts index ff2e3539b6b..35ccea66008 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -795,41 +795,6 @@ namespace ts.server { } } - /* @internal */ - private extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: string[]): ReadonlyArray { - const cached = this.cachedUnresolvedImportsPerFile.get(file.path); - if (cached) { - // found cached result, return - return cached; - } - let unresolvedImports: string[] | undefined; - if (file.resolvedModules) { - file.resolvedModules.forEach((resolvedModule, name) => { - // pick unresolved non-relative names - if (!resolvedModule && !isExternalModuleNameRelative(name) && !isAmbientlyDeclaredModule(name)) { - // for non-scoped names extract part up-to the first slash - // for scoped names - extract up to the second slash - let trimmed = name.trim(); - let i = trimmed.indexOf("/"); - if (i !== -1 && trimmed.charCodeAt(0) === CharacterCodes.at) { - i = trimmed.indexOf("/", i + 1); - } - if (i !== -1) { - trimmed = trimmed.substr(0, i); - } - (unresolvedImports || (unresolvedImports = [])).push(trimmed); - } - }); - } - - this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || emptyArray); - return unresolvedImports || emptyArray; - - function isAmbientlyDeclaredModule(name: string) { - return ambientModules.some(m => m === name); - } - } - /* @internal */ onFileAddedOrRemoved() { this.hasAddedorRemovedFiles = true; @@ -863,15 +828,7 @@ namespace ts.server { // (can reuse cached imports for files that were not changed) // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch if (hasNewProgram || changedFiles.length) { - let result: string[] | undefined; - const ambientModules = this.program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); - for (const sourceFile of this.program.getSourceFiles()) { - const unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules); - if (unResolved !== emptyArray) { - (result || (result = [])).push(...unResolved); - } - } - this.lastCachedUnresolvedImportsList = result ? sortAndDeduplicate(result) : emptyArray; + this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); } this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); @@ -1218,6 +1175,25 @@ namespace ts.server { } } + function getUnresolvedImports(program: Program, cachedUnresolvedImportsPerFile: Map>): SortedReadonlyArray { + const ambientModules = program.getTypeChecker().getAmbientModules().map(mod => stripQuotes(mod.getName())); + return sortAndDeduplicate(flatMap(program.getSourceFiles(), sourceFile => + extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules, cachedUnresolvedImportsPerFile))); + } + function extractUnresolvedImportsFromSourceFile(file: SourceFile, ambientModules: ReadonlyArray, cachedUnresolvedImportsPerFile: Map>): ReadonlyArray { + return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { + if (!file.resolvedModules) return emptyArray; + let unresolvedImports: string[] | undefined; + file.resolvedModules.forEach((resolvedModule, name) => { + // pick unresolved non-relative names + if (!resolvedModule && !isExternalModuleNameRelative(name) && !ambientModules.some(m => m === name)) { + unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); + } + }); + return unresolvedImports || emptyArray; + }); + } + /** * If a file is opened and no tsconfig (or jsconfig) is found, * the file and its imports/references are put into an InferredProject. From c9fadf1f46bbc49fee342eef90c416dc81e5d635 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 30 Oct 2018 11:06:13 -0700 Subject: [PATCH 153/262] Ignore wild card directory watchers with node_modules file or folder starting with . --- src/compiler/watch.ts | 2 + src/harness/virtualFileSystemWithWatch.ts | 4 +- src/server/editorServices.ts | 1 + src/testRunner/unittests/tscWatchMode.ts | 46 ++++++++++++- .../unittests/tsserverProjectSystem.ts | 66 ++++++++++++------- 5 files changed, 92 insertions(+), 27 deletions(-) diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 427ec1e4bac..f9ce3055f63 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -938,6 +938,8 @@ namespace ts { } nextSourceFileVersion(fileOrDirectoryPath); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; + // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (fileOrDirectoryPath !== directory && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index d2b7c7869c5..b21ba06c111 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -587,8 +587,8 @@ interface Array {}` } this.invokeFileWatcher(fileOrDirectory.fullPath, FileWatcherEventKind.Created); if (isFsFolder(fileOrDirectory)) { - this.invokeDirectoryWatcher(fileOrDirectory.fullPath, ""); - this.invokeWatchedDirectoriesRecursiveCallback(fileOrDirectory.fullPath, ""); + this.invokeDirectoryWatcher(fileOrDirectory.fullPath, fileOrDirectory.fullPath); + this.invokeWatchedDirectoriesRecursiveCallback(fileOrDirectory.fullPath, fileOrDirectory.fullPath); } this.invokeDirectoryWatcher(folder.fullPath, fileOrDirectory.fullPath); } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 64549c50b94..fcc4407e315 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -962,6 +962,7 @@ namespace ts.server { fileOrDirectory => { const fileOrDirectoryPath = this.toPath(fileOrDirectory); project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return; const configFilename = project.getConfigFilePath(); // If the the added or created file or directory is not supported file name, ignore the file diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index 552b3053df3..ca00e08fdd2 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -34,8 +34,10 @@ namespace ts.tscWatch { return () => watch.getCurrentProgram().getProgram(); } - function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}) { - const watch = createWatchProgram(createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host)); + function createWatchOfFilesAndCompilerOptions(rootFiles: string[], host: WatchedSystem, options: CompilerOptions = {}, maxNumberOfFilesToIterateForInvalidation?: number) { + const compilerHost = createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, host); + compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; + const watch = createWatchProgram(compilerHost); return () => watch.getCurrentProgram().getProgram(); } @@ -2467,6 +2469,46 @@ declare module "fs" { checkProgramActualFiles(watch(), [file.path, libFile.path, `${currentDirectory}/node_modules/@types/qqq/index.d.ts`]); checkOutputErrorsIncremental(host, emptyArray); }); + + describe("ignores files/folder changes in node_modules that start with '.'", () => { + const projectPath = "/user/username/projects/project"; + const npmCacheFile: File = { + path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + content: JSON.stringify({ something: 10 }) + }; + const file1: File = { + path: `${projectPath}/test.ts`, + content: `import { x } from "somemodule";` + }; + const file2: File = { + path: `${projectPath}/node_modules/somemodule/index.d.ts`, + content: `export const x = 10;` + }; + const files = [libFile, file1, file2]; + const expectedFiles = files.map(f => f.path); + it("when watching node_modules in inferred project for failed lookup", () => { + const host = createWatchedSystem(files); + const watch = createWatchOfFilesAndCompilerOptions([file1.path], host, {}, /*maxNumberOfFilesToIterateForInvalidation*/ 1); + checkProgramActualFiles(watch(), expectedFiles); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + it("when watching node_modules as part of wild card directories in config project", () => { + const config: File = { + path: `${projectPath}/tsconfig.json`, + content: "{}" + }; + const host = createWatchedSystem(files.concat(config)); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), expectedFiles); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + }); }); describe("tsc-watch with when module emit is specified as node", () => { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index a348656c24c..a2229dd8b5b 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -7389,7 +7389,7 @@ namespace ts.projectSystem { const recursiveWatchedDirectories: string[] = [`${appFolder}`, `${appFolder}/node_modules`].concat(getNodeModuleDirectories(getDirectoryPath(appFolder))); verifyProject(); - let timeoutAfterReloadFs = timeoutDuringPartialInstallation; + let npmInstallComplete = false; // Simulate npm install const filesAndFoldersToAdd: File[] = [ @@ -7418,8 +7418,8 @@ namespace ts.projectSystem { { path: "/a/b/node_modules/.staging/lodash-b0733faa/index.js", content: "module.exports = require('./lodash');" }, { path: "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594" } ].map(getRootedFileOrFolder)); - // Since we added/removed folder, scheduled project update - verifyAfterPartialOrCompleteNpmInstall(2); + // Since we added/removed in .staging no timeout + verifyAfterPartialOrCompleteNpmInstall(0); // Remove file "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594" filesAndFoldersToAdd.length--; @@ -7431,7 +7431,7 @@ namespace ts.projectSystem { { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/add/observable/dom" }, { path: "/a/b/node_modules/.staging/@types/lodash-e56c4fe7/index.d.ts", content: "\n// Stub for lodash\nexport = _;\nexport as namespace _;\ndeclare var _: _.LoDashStatic;\ndeclare namespace _ {\n interface LoDashStatic {\n someProp: string;\n }\n class SomeClass {\n someMethod(): void;\n }\n}" } ].map(getRootedFileOrFolder)); - verifyAfterPartialOrCompleteNpmInstall(2); + verifyAfterPartialOrCompleteNpmInstall(0); filesAndFoldersToAdd.push(...[ { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/scheduler" }, @@ -7440,7 +7440,7 @@ namespace ts.projectSystem { { path: "/a/b/node_modules/.staging/rxjs-22375c61/testing" }, { path: "/a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041", content: "{\n \"_args\": [\n [\n {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\"\n ]\n ],\n \"_from\": \"rxjs@>=5.4.2 <6.0.0\",\n \"_id\": \"rxjs@5.4.3\",\n \"_inCache\": true,\n \"_location\": \"/rxjs\",\n \"_nodeVersion\": \"7.7.2\",\n \"_npmOperationalInternal\": {\n \"host\": \"s3://npm-registry-packages\",\n \"tmp\": \"tmp/rxjs-5.4.3.tgz_1502407898166_0.6800217325799167\"\n },\n \"_npmUser\": {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"_npmVersion\": \"5.3.0\",\n \"_phantomChildren\": {},\n \"_requested\": {\n \"raw\": \"rxjs@^5.4.2\",\n \"scope\": null,\n \"escapedName\": \"rxjs\",\n \"name\": \"rxjs\",\n \"rawSpec\": \"^5.4.2\",\n \"spec\": \">=5.4.2 <6.0.0\",\n \"type\": \"range\"\n },\n \"_requiredBy\": [\n \"/\"\n ],\n \"_resolved\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\",\n \"_shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"_shrinkwrap\": null,\n \"_spec\": \"rxjs@^5.4.2\",\n \"_where\": \"C:\\\\Users\\\\shkamat\\\\Desktop\\\\app\",\n \"author\": {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/ReactiveX/RxJS/issues\"\n },\n \"config\": {\n \"commitizen\": {\n \"path\": \"cz-conventional-changelog\"\n }\n },\n \"contributors\": [\n {\n \"name\": \"Ben Lesh\",\n \"email\": \"ben@benlesh.com\"\n },\n {\n \"name\": \"Paul Taylor\",\n \"email\": \"paul.e.taylor@me.com\"\n },\n {\n \"name\": \"Jeff Cross\",\n \"email\": \"crossj@google.com\"\n },\n {\n \"name\": \"Matthew Podwysocki\",\n \"email\": \"matthewp@microsoft.com\"\n },\n {\n \"name\": \"OJ Kwon\",\n \"email\": \"kwon.ohjoong@gmail.com\"\n },\n {\n \"name\": \"Andre Staltz\",\n \"email\": \"andre@staltz.com\"\n }\n ],\n \"dependencies\": {\n \"symbol-observable\": \"^1.0.1\"\n },\n \"description\": \"Reactive Extensions for modern JavaScript\",\n \"devDependencies\": {\n \"babel-polyfill\": \"^6.23.0\",\n \"benchmark\": \"^2.1.0\",\n \"benchpress\": \"2.0.0-beta.1\",\n \"chai\": \"^3.5.0\",\n \"color\": \"^0.11.1\",\n \"colors\": \"1.1.2\",\n \"commitizen\": \"^2.8.6\",\n \"coveralls\": \"^2.11.13\",\n \"cz-conventional-changelog\": \"^1.2.0\",\n \"danger\": \"^1.1.0\",\n \"doctoc\": \"^1.0.0\",\n \"escape-string-regexp\": \"^1.0.5 \",\n \"esdoc\": \"^0.4.7\",\n \"eslint\": \"^3.8.0\",\n \"fs-extra\": \"^2.1.2\",\n \"get-folder-size\": \"^1.0.0\",\n \"glob\": \"^7.0.3\",\n \"gm\": \"^1.22.0\",\n \"google-closure-compiler-js\": \"^20170218.0.0\",\n \"gzip-size\": \"^3.0.0\",\n \"http-server\": \"^0.9.0\",\n \"husky\": \"^0.13.3\",\n \"lint-staged\": \"3.2.5\",\n \"lodash\": \"^4.15.0\",\n \"madge\": \"^1.4.3\",\n \"markdown-doctest\": \"^0.9.1\",\n \"minimist\": \"^1.2.0\",\n \"mkdirp\": \"^0.5.1\",\n \"mocha\": \"^3.0.2\",\n \"mocha-in-sauce\": \"0.0.1\",\n \"npm-run-all\": \"^4.0.2\",\n \"npm-scripts-info\": \"^0.3.4\",\n \"nyc\": \"^10.2.0\",\n \"opn-cli\": \"^3.1.0\",\n \"platform\": \"^1.3.1\",\n \"promise\": \"^7.1.1\",\n \"protractor\": \"^3.1.1\",\n \"rollup\": \"0.36.3\",\n \"rollup-plugin-inject\": \"^2.0.0\",\n \"rollup-plugin-node-resolve\": \"^2.0.0\",\n \"rx\": \"latest\",\n \"rxjs\": \"latest\",\n \"shx\": \"^0.2.2\",\n \"sinon\": \"^2.1.0\",\n \"sinon-chai\": \"^2.9.0\",\n \"source-map-support\": \"^0.4.0\",\n \"tslib\": \"^1.5.0\",\n \"tslint\": \"^4.4.2\",\n \"typescript\": \"~2.0.6\",\n \"typings\": \"^2.0.0\",\n \"validate-commit-msg\": \"^2.14.0\",\n \"watch\": \"^1.0.1\",\n \"webpack\": \"^1.13.1\",\n \"xmlhttprequest\": \"1.8.0\"\n },\n \"directories\": {},\n \"dist\": {\n \"integrity\": \"sha512-fSNi+y+P9ss+EZuV0GcIIqPUK07DEaMRUtLJvdcvMyFjc9dizuDjere+A4V7JrLGnm9iCc+nagV/4QdMTkqC4A==\",\n \"shasum\": \"0758cddee6033d68e0fd53676f0f3596ce3d483f\",\n \"tarball\": \"https://registry.npmjs.org/rxjs/-/rxjs-5.4.3.tgz\"\n },\n \"engines\": {\n \"npm\": \">=2.0.0\"\n },\n \"homepage\": \"https://github.com/ReactiveX/RxJS\",\n \"keywords\": [\n \"Rx\",\n \"RxJS\",\n \"ReactiveX\",\n \"ReactiveExtensions\",\n \"Streams\",\n \"Observables\",\n \"Observable\",\n \"Stream\",\n \"ES6\",\n \"ES2015\"\n ],\n \"license\": \"Apache-2.0\",\n \"lint-staged\": {\n \"*.@(js)\": [\n \"eslint --fix\",\n \"git add\"\n ],\n \"*.@(ts)\": [\n \"tslint --fix\",\n \"git add\"\n ]\n },\n \"main\": \"Rx.js\",\n \"maintainers\": [\n {\n \"name\": \"blesh\",\n \"email\": \"ben@benlesh.com\"\n }\n ],\n \"name\": \"rxjs\",\n \"optionalDependencies\": {},\n \"readme\": \"ERROR: No README data found!\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+ssh://git@github.com/ReactiveX/RxJS.git\"\n },\n \"scripts-info\": {\n \"info\": \"List available script\",\n \"build_all\": \"Build all packages (ES6, CJS, UMD) and generate packages\",\n \"build_cjs\": \"Build CJS package with clean up existing build, copy source into dist\",\n \"build_es6\": \"Build ES6 package with clean up existing build, copy source into dist\",\n \"build_closure_core\": \"Minify Global core build using closure compiler\",\n \"build_global\": \"Build Global package, then minify build\",\n \"build_perf\": \"Build CJS & Global build, run macro performance test\",\n \"build_test\": \"Build CJS package & test spec, execute mocha test runner\",\n \"build_cover\": \"Run lint to current code, build CJS & test spec, execute test coverage\",\n \"build_docs\": \"Build ES6 & global package, create documentation using it\",\n \"build_spec\": \"Build test specs\",\n \"check_circular_dependencies\": \"Check codebase has circular dependencies\",\n \"clean_spec\": \"Clean up existing test spec build output\",\n \"clean_dist_cjs\": \"Clean up existing CJS package output\",\n \"clean_dist_es6\": \"Clean up existing ES6 package output\",\n \"clean_dist_global\": \"Clean up existing Global package output\",\n \"commit\": \"Run git commit wizard\",\n \"compile_dist_cjs\": \"Compile codebase into CJS module\",\n \"compile_module_es6\": \"Compile codebase into ES6\",\n \"cover\": \"Execute test coverage\",\n \"lint_perf\": \"Run lint against performance test suite\",\n \"lint_spec\": \"Run lint against test spec\",\n \"lint_src\": \"Run lint against source\",\n \"lint\": \"Run lint against everything\",\n \"perf\": \"Run macro performance benchmark\",\n \"perf_micro\": \"Run micro performance benchmark\",\n \"test_mocha\": \"Execute mocha test runner against existing test spec build\",\n \"test_browser\": \"Execute mocha test runner on browser against existing test spec build\",\n \"test\": \"Clean up existing test spec build, build test spec and execute mocha test runner\",\n \"tests2png\": \"Generate marble diagram image from test spec\",\n \"watch\": \"Watch codebase, trigger compile when source code changes\"\n },\n \"typings\": \"Rx.d.ts\",\n \"version\": \"5.4.3\"\n}\n" } ].map(getRootedFileOrFolder)); - verifyAfterPartialOrCompleteNpmInstall(2); + verifyAfterPartialOrCompleteNpmInstall(0); // remove /a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041 filesAndFoldersToAdd.length--; @@ -7468,12 +7468,12 @@ namespace ts.projectSystem { // we would now not have failed lookup in the parent of appFolder since lodash is available recursiveWatchedDirectories.length = 2; // npm installation complete, timeout after reload fs - timeoutAfterReloadFs = true; + npmInstallComplete = true; verifyAfterPartialOrCompleteNpmInstall(2); function verifyAfterPartialOrCompleteNpmInstall(timeoutQueueLengthWhenRunningTimeouts: number) { host.reloadFS(projectFiles.concat(otherFiles, filesAndFoldersToAdd)); - if (timeoutAfterReloadFs) { + if (npmInstallComplete || timeoutDuringPartialInstallation) { host.checkTimeoutQueueLengthAndRun(timeoutQueueLengthWhenRunningTimeouts); } else { @@ -9040,31 +9040,51 @@ export const x = 10;` }); }); - it("ignores files/folder changes in node_modules that start with '.'", () => { + describe("ignores files/folder changes in node_modules that start with '.'", () => { const projectPath = "/user/username/projects/project"; + const npmCacheFile: File = { + path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + content: JSON.stringify({ something: 10 }) + }; const file1: File = { - path: `${projectPath}/test.js`, + path: `${projectPath}/test.ts`, content: `import { x } from "somemodule";` }; const file2: File = { path: `${projectPath}/node_modules/somemodule/index.d.ts`, content: `export const x = 10;` }; - const files = [libFile, file1, file2]; - const host = createServerHost(files); - const service = createProjectService(host); - service.openClientFile(file1.path); - checkNumberOfProjects(service, { inferredProjects: 1 }); - const project = service.inferredProjects[0]; - (project as ResolutionCacheHost).maxNumberOfFilesToIterateForInvalidation = 1; - host.checkTimeoutQueueLength(0); + it("when watching node_modules in inferred project for failed lookup/closed script infos", () => { + const files = [libFile, file1, file2]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + checkNumberOfProjects(service, { inferredProjects: 1 }); + const project = service.inferredProjects[0]; + checkProjectActualFiles(project, files.map(f => f.path)); + (project as ResolutionCacheHost).maxNumberOfFilesToIterateForInvalidation = 1; + host.checkTimeoutQueueLength(0); - const npmCacheFile: File = { - path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.json`, - content: JSON.stringify({ something: 10 }) - }; - host.ensureFileOrFolder(npmCacheFile); - host.checkTimeoutQueueLength(0); + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + it("when watching node_modules as part of wild card directories in config project", () => { + const config: File = { + path: `${projectPath}/tsconfig.json`, + content: "{}" + }; + const files = [libFile, file1, file2, config]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project = Debug.assertDefined(service.configuredProjects.get(config.path)); + checkProjectActualFiles(project, files.map(f => f.path)); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); }); }); From 176627c818dbec1c2e4341f12afcd8bd8d7b447d Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 11:16:26 -0700 Subject: [PATCH 154/262] Support augmenting module with `export as namespace` (#27281) * Support augmenting module with `export as namespace` * Warn on use of merged symbol containing 'export as namespace' --- src/compiler/checker.ts | 10 +-- .../duplicateVarsAcrossFileBoundaries.symbols | 6 +- .../exportAsNamespace_augment.errors.txt | 50 ++++++++++++ .../reference/exportAsNamespace_augment.js | 32 ++++++++ .../exportAsNamespace_augment.symbols | 66 ++++++++++++++++ .../reference/exportAsNamespace_augment.types | 78 +++++++++++++++++++ .../compiler/exportAsNamespace_augment.ts | 22 ++++++ 7 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 tests/baselines/reference/exportAsNamespace_augment.errors.txt create mode 100644 tests/baselines/reference/exportAsNamespace_augment.js create mode 100644 tests/baselines/reference/exportAsNamespace_augment.symbols create mode 100644 tests/baselines/reference/exportAsNamespace_augment.types create mode 100644 tests/cases/compiler/exportAsNamespace_augment.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 418be79878e..cd51a14fb32 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -854,7 +854,7 @@ namespace ts { (source.flags | target.flags) & SymbolFlags.Assignment) { Debug.assert(source !== target); if (!(target.flags & SymbolFlags.Transient)) { - target = cloneSymbol(target); + target = cloneSymbol(resolveSymbol(target)); } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & SymbolFlags.ValueModule && target.flags & SymbolFlags.ValueModule && target.constEnumOnlyModule && !source.constEnumOnlyModule) { @@ -883,7 +883,7 @@ namespace ts { else if (target.flags & SymbolFlags.NamespaceModule) { error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } - else { + else { // error const isEitherEnum = !!(target.flags & SymbolFlags.Enum || source.flags & SymbolFlags.Enum); const isEitherBlockScoped = !!(target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable); const message = isEitherEnum @@ -947,7 +947,8 @@ namespace ts { function mergeSymbolTable(target: SymbolTable, source: SymbolTable) { source.forEach((sourceSymbol, id) => { - target.set(id, target.has(id) ? mergeSymbol(target.get(id)!, sourceSymbol) : sourceSymbol); + const targetSymbol = target.get(id); + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol) : sourceSymbol); }); } @@ -1549,8 +1550,7 @@ namespace ts { // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value && !(originalLocation!.flags & NodeFlags.JSDoc)) { - const decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) { + if (some(result.declarations, d => isNamespaceExportDeclaration(d) || isSourceFile(d) && !!d.symbol.globalExports)) { error(errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } diff --git a/tests/baselines/reference/duplicateVarsAcrossFileBoundaries.symbols b/tests/baselines/reference/duplicateVarsAcrossFileBoundaries.symbols index a1f6cdf1b38..9cedc15a75a 100644 --- a/tests/baselines/reference/duplicateVarsAcrossFileBoundaries.symbols +++ b/tests/baselines/reference/duplicateVarsAcrossFileBoundaries.symbols @@ -34,10 +34,10 @@ var z = 0; === tests/cases/compiler/duplicateVarsAcrossFileBoundaries_4.ts === module P { } ->P : Symbol(P, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 0)) +>P : Symbol(P, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 0), Decl(duplicateVarsAcrossFileBoundaries_5.ts, 2, 3)) import p = P; ->p : Symbol(p, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 12), Decl(duplicateVarsAcrossFileBoundaries_5.ts, 2, 3)) +>p : Symbol(p, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 12)) >P : Symbol(P, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 0)) var q; @@ -52,5 +52,5 @@ import q = Q; >Q : Symbol(Q, Decl(duplicateVarsAcrossFileBoundaries_5.ts, 0, 0)) var p; ->p : Symbol(p, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 12), Decl(duplicateVarsAcrossFileBoundaries_5.ts, 2, 3)) +>p : Symbol(P, Decl(duplicateVarsAcrossFileBoundaries_4.ts, 0, 0), Decl(duplicateVarsAcrossFileBoundaries_5.ts, 2, 3)) diff --git a/tests/baselines/reference/exportAsNamespace_augment.errors.txt b/tests/baselines/reference/exportAsNamespace_augment.errors.txt new file mode 100644 index 00000000000..76cb643d62a --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace_augment.errors.txt @@ -0,0 +1,50 @@ +/a.d.ts(3,14): error TS2451: Cannot redeclare block-scoped variable 'conflict'. +/b.ts(6,22): error TS2451: Cannot redeclare block-scoped variable 'conflict'. +/b.ts(12,18): error TS2451: Cannot redeclare block-scoped variable 'conflict'. +/b.ts(15,1): error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. +/b.ts(15,7): error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. +/b.ts(15,13): error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. +/b.ts(15,19): error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. + + +==== /a.d.ts (1 errors) ==== + export as namespace a; + export const x = 0; + export const conflict = 0; + ~~~~~~~~ +!!! error TS2451: Cannot redeclare block-scoped variable 'conflict'. +!!! related TS6203 /b.ts:6:22: 'conflict' was also declared here. +!!! related TS6204 /b.ts:6:22: and here. + +==== /b.ts (6 errors) ==== + import * as a2 from "./a"; + + declare global { + namespace a { + export const y = 0; + export const conflict = 0; + ~~~~~~~~ +!!! error TS2451: Cannot redeclare block-scoped variable 'conflict'. +!!! related TS6203 /a.d.ts:3:14: 'conflict' was also declared here. + } + } + + declare module "./a" { + export const z = 0; + export const conflict = 0; + ~~~~~~~~ +!!! error TS2451: Cannot redeclare block-scoped variable 'conflict'. +!!! related TS6203 /a.d.ts:3:14: 'conflict' was also declared here. + } + + a.x + a.y + a.z + a.conflict; + ~ +!!! error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. + ~ +!!! error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. + ~ +!!! error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. + ~ +!!! error TS2686: 'a' refers to a UMD global, but the current file is a module. Consider adding an import instead. + a2.x + a2.y + a2.z + a2.conflict; + \ No newline at end of file diff --git a/tests/baselines/reference/exportAsNamespace_augment.js b/tests/baselines/reference/exportAsNamespace_augment.js new file mode 100644 index 00000000000..6186d698791 --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace_augment.js @@ -0,0 +1,32 @@ +//// [tests/cases/compiler/exportAsNamespace_augment.ts] //// + +//// [a.d.ts] +export as namespace a; +export const x = 0; +export const conflict = 0; + +//// [b.ts] +import * as a2 from "./a"; + +declare global { + namespace a { + export const y = 0; + export const conflict = 0; + } +} + +declare module "./a" { + export const z = 0; + export const conflict = 0; +} + +a.x + a.y + a.z + a.conflict; +a2.x + a2.y + a2.z + a2.conflict; + + +//// [b.js] +"use strict"; +exports.__esModule = true; +var a2 = require("./a"); +a.x + a.y + a.z + a.conflict; +a2.x + a2.y + a2.z + a2.conflict; diff --git a/tests/baselines/reference/exportAsNamespace_augment.symbols b/tests/baselines/reference/exportAsNamespace_augment.symbols new file mode 100644 index 00000000000..27c45f371c7 --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace_augment.symbols @@ -0,0 +1,66 @@ +=== /a.d.ts === +export as namespace a; +>a : Symbol(a, Decl(a.d.ts, 0, 0)) + +export const x = 0; +>x : Symbol(x, Decl(a.d.ts, 1, 12)) + +export const conflict = 0; +>conflict : Symbol(conflict, Decl(a.d.ts, 2, 12)) + +=== /b.ts === +import * as a2 from "./a"; +>a2 : Symbol(a2, Decl(b.ts, 0, 6)) + +declare global { +>global : Symbol(global, Decl(b.ts, 0, 26)) + + namespace a { +>a : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) + + export const y = 0; +>y : Symbol(y, Decl(b.ts, 4, 20)) + + export const conflict = 0; +>conflict : Symbol(conflict, Decl(b.ts, 5, 20)) + } +} + +declare module "./a" { +>"./a" : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) + + export const z = 0; +>z : Symbol(z, Decl(b.ts, 10, 16)) + + export const conflict = 0; +>conflict : Symbol(conflict, Decl(b.ts, 11, 16)) +} + +a.x + a.y + a.z + a.conflict; +>a.x : Symbol(a2.x, Decl(a.d.ts, 1, 12)) +>a : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) +>x : Symbol(a2.x, Decl(a.d.ts, 1, 12)) +>a.y : Symbol(a2.y, Decl(b.ts, 4, 20)) +>a : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) +>y : Symbol(a2.y, Decl(b.ts, 4, 20)) +>a.z : Symbol(a2.z, Decl(b.ts, 10, 16)) +>a : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) +>z : Symbol(a2.z, Decl(b.ts, 10, 16)) +>a.conflict : Symbol(a2.conflict, Decl(a.d.ts, 2, 12)) +>a : Symbol(a2, Decl(a.d.ts, 0, 0), Decl(b.ts, 2, 16), Decl(b.ts, 7, 1)) +>conflict : Symbol(a2.conflict, Decl(a.d.ts, 2, 12)) + +a2.x + a2.y + a2.z + a2.conflict; +>a2.x : Symbol(a2.x, Decl(a.d.ts, 1, 12)) +>a2 : Symbol(a2, Decl(b.ts, 0, 6)) +>x : Symbol(a2.x, Decl(a.d.ts, 1, 12)) +>a2.y : Symbol(a2.y, Decl(b.ts, 4, 20)) +>a2 : Symbol(a2, Decl(b.ts, 0, 6)) +>y : Symbol(a2.y, Decl(b.ts, 4, 20)) +>a2.z : Symbol(a2.z, Decl(b.ts, 10, 16)) +>a2 : Symbol(a2, Decl(b.ts, 0, 6)) +>z : Symbol(a2.z, Decl(b.ts, 10, 16)) +>a2.conflict : Symbol(a2.conflict, Decl(a.d.ts, 2, 12)) +>a2 : Symbol(a2, Decl(b.ts, 0, 6)) +>conflict : Symbol(a2.conflict, Decl(a.d.ts, 2, 12)) + diff --git a/tests/baselines/reference/exportAsNamespace_augment.types b/tests/baselines/reference/exportAsNamespace_augment.types new file mode 100644 index 00000000000..0e186f57c6f --- /dev/null +++ b/tests/baselines/reference/exportAsNamespace_augment.types @@ -0,0 +1,78 @@ +=== /a.d.ts === +export as namespace a; +>a : typeof import("/a") + +export const x = 0; +>x : 0 +>0 : 0 + +export const conflict = 0; +>conflict : 0 +>0 : 0 + +=== /b.ts === +import * as a2 from "./a"; +>a2 : typeof a2 + +declare global { +>global : typeof global + + namespace a { +>a : typeof a2 + + export const y = 0; +>y : 0 +>0 : 0 + + export const conflict = 0; +>conflict : 0 +>0 : 0 + } +} + +declare module "./a" { +>"./a" : typeof a2 + + export const z = 0; +>z : 0 +>0 : 0 + + export const conflict = 0; +>conflict : 0 +>0 : 0 +} + +a.x + a.y + a.z + a.conflict; +>a.x + a.y + a.z + a.conflict : number +>a.x + a.y + a.z : number +>a.x + a.y : number +>a.x : 0 +>a : typeof a2 +>x : 0 +>a.y : 0 +>a : typeof a2 +>y : 0 +>a.z : 0 +>a : typeof a2 +>z : 0 +>a.conflict : 0 +>a : typeof a2 +>conflict : 0 + +a2.x + a2.y + a2.z + a2.conflict; +>a2.x + a2.y + a2.z + a2.conflict : number +>a2.x + a2.y + a2.z : number +>a2.x + a2.y : number +>a2.x : 0 +>a2 : typeof a2 +>x : 0 +>a2.y : 0 +>a2 : typeof a2 +>y : 0 +>a2.z : 0 +>a2 : typeof a2 +>z : 0 +>a2.conflict : 0 +>a2 : typeof a2 +>conflict : 0 + diff --git a/tests/cases/compiler/exportAsNamespace_augment.ts b/tests/cases/compiler/exportAsNamespace_augment.ts new file mode 100644 index 00000000000..2c972a32acc --- /dev/null +++ b/tests/cases/compiler/exportAsNamespace_augment.ts @@ -0,0 +1,22 @@ +// @Filename: /a.d.ts +export as namespace a; +export const x = 0; +export const conflict = 0; + +// @Filename: /b.ts +import * as a2 from "./a"; + +declare global { + namespace a { + export const y = 0; + export const conflict = 0; + } +} + +declare module "./a" { + export const z = 0; + export const conflict = 0; +} + +a.x + a.y + a.z + a.conflict; +a2.x + a2.y + a2.z + a2.conflict; From 33568795e05c7f9f08ed74e0b141834b5a56e92e Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 30 Oct 2018 19:33:05 +0100 Subject: [PATCH 155/262] Suggest adding to tsconfig after installing @types (#28211) Ref: https://github.com/Microsoft/TypeScript/pull/28168#issuecomment-433554228 --- src/compiler/checker.ts | 6 ++-- src/compiler/diagnosticMessages.json | 6 ++-- .../reference/anonymousModules.errors.txt | 12 +++---- ...onflictingCommonJSES2015Exports.errors.txt | 4 +-- ...torWithIncompleteTypeAnnotation.errors.txt | 4 +-- .../didYouMeanSuggestionErrors.errors.txt | 36 +++++++++---------- .../reference/externModule.errors.txt | 4 +-- .../reference/fixSignatureCaching.errors.txt | 12 +++---- .../reference/innerModExport1.errors.txt | 4 +-- .../reference/innerModExport2.errors.txt | 4 +-- .../reference/jsxAndTypeAssertion.errors.txt | 4 +-- .../reference/metadataImportType.errors.txt | 4 +-- .../reference/moduleExports1.errors.txt | 8 ++--- .../moduleKeywordRepeatError.errors.txt | 4 +-- .../noAssertForUnparseableTypedefs.errors.txt | 4 +-- ...adingStaticFunctionsInFunctions.errors.txt | 12 +++---- .../reference/parser509534.errors.txt | 8 ++--- .../reference/parser509693.errors.txt | 8 ++--- .../reference/parser519458.errors.txt | 4 +-- .../reference/parser521128.errors.txt | 4 +-- .../parserCommaInTypeMemberList2.errors.txt | 4 +-- .../reference/parserharness.errors.txt | 8 ++--- .../reference/reservedWords2.errors.txt | 8 ++--- .../reference/staticsInAFunction.errors.txt | 12 +++---- .../templateStringInModuleName.errors.txt | 8 ++--- .../templateStringInModuleNameES6.errors.txt | 8 ++--- .../reference/typecheckIfCondition.errors.txt | 8 ++--- tests/cases/user/prettier/prettier | 2 +- 28 files changed, 105 insertions(+), 105 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cd51a14fb32..f23e26f51fc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14172,17 +14172,17 @@ namespace ts { case "console": return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; case "$": - return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; case "describe": case "suite": case "it": case "test": - return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; case "process": case "require": case "Buffer": case "module": - return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; case "Map": case "Set": case "Promise": diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 37cab0359d4..1f1ee7a6948 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2088,15 +2088,15 @@ "category": "Error", "code": 2577 }, - "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": { + "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.": { "category": "Error", "code": 2580 }, - "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.": { + "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig.": { "category": "Error", "code": 2581 }, - "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.": { + "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.": { "category": "Error", "code": 2582 }, diff --git a/tests/baselines/reference/anonymousModules.errors.txt b/tests/baselines/reference/anonymousModules.errors.txt index b81513cfbbd..24468352d03 100644 --- a/tests/baselines/reference/anonymousModules.errors.txt +++ b/tests/baselines/reference/anonymousModules.errors.txt @@ -1,22 +1,22 @@ -tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. ==== tests/cases/compiler/anonymousModules.ts (6 errors) ==== module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. export var foo = 1; module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. export var bar = 1; @@ -26,7 +26,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. var x = bar; diff --git a/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt b/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt index 2f47712c9db..717ed95a505 100644 --- a/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt +++ b/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/salsa/bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/salsa/bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ==== tests/cases/conformance/salsa/bug24934.js (1 errors) ==== export function abc(a, b, c) { return 5; } module.exports = { abc }; ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ==== tests/cases/conformance/salsa/use.js (0 errors) ==== import { abc } from './bug24934'; abc(1, 2, 3); diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 1b0034a3063..d683899f41d 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2503: Cannot find namespace 'module'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -105,7 +105,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS ~~~~~~ !!! error TS2503: Cannot find namespace 'module'. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt b/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt index a41b19ecd9d..9bf043562d9 100644 --- a/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt +++ b/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt @@ -1,14 +1,14 @@ -tests/cases/compiler/didYouMeanSuggestionErrors.ts(1,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(2,5): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(3,19): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(7,1): error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(8,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(1,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(2,5): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(3,19): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(7,1): error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(8,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,9): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,21): error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,21): error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/didYouMeanSuggestionErrors.ts(10,9): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(12,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(13,19): error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/compiler/didYouMeanSuggestionErrors.ts(14,19): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(12,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(13,19): error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(14,19): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/didYouMeanSuggestionErrors.ts(16,23): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/compiler/didYouMeanSuggestionErrors.ts(17,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/compiler/didYouMeanSuggestionErrors.ts(18,23): error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. @@ -22,40 +22,40 @@ tests/cases/compiler/didYouMeanSuggestionErrors.ts(24,18): error TS2583: Cannot ==== tests/cases/compiler/didYouMeanSuggestionErrors.ts (19 errors) ==== describe("my test suite", () => { ~~~~~~~~ -!!! error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. it("should run", () => { ~~ -!!! error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. const a = $(".thing"); ~ -!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. +!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig. }); }); suite("another suite", () => { ~~~~~ -!!! error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. test("everything else", () => { ~~~~ -!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. console.log(process.env); ~~~~~~~ !!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. ~~~~~~~ -!!! error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. document.createElement("div"); ~~~~~~~~ !!! error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. const x = require("fs"); ~~~~~~~ -!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. const y = Buffer.from([]); ~~~~~~ -!!! error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. const z = module.exports; ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. const a = new Map(); ~~~ diff --git a/tests/baselines/reference/externModule.errors.txt b/tests/baselines/reference/externModule.errors.txt index e1077550985..377fe025cc6 100644 --- a/tests/baselines/reference/externModule.errors.txt +++ b/tests/baselines/reference/externModule.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/externModule.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/compiler/externModule.ts(1,9): error TS1005: ';' expected. -tests/cases/compiler/externModule.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/externModule.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/externModule.ts(1,16): error TS1005: ';' expected. tests/cases/compiler/externModule.ts(3,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(4,10): error TS2391: Function implementation is missing or not immediately following the declaration. @@ -21,7 +21,7 @@ tests/cases/compiler/externModule.ts(37,3): error TS2552: Cannot find name 'XDat ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. export class XDate { diff --git a/tests/baselines/reference/fixSignatureCaching.errors.txt b/tests/baselines/reference/fixSignatureCaching.errors.txt index bf4400313b2..ad992cae7db 100644 --- a/tests/baselines/reference/fixSignatureCaching.errors.txt +++ b/tests/baselines/reference/fixSignatureCaching.errors.txt @@ -50,9 +50,9 @@ tests/cases/conformance/fixSignatureCaching.ts(915,36): error TS2339: Property ' tests/cases/conformance/fixSignatureCaching.ts(915,53): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'. tests/cases/conformance/fixSignatureCaching.ts(955,42): error TS2339: Property 'mobileGrade' does not exist on type '{}'. tests/cases/conformance/fixSignatureCaching.ts(964,57): error TS2339: Property 'getDeviceSmallerSide' does not exist on type '{}'. -tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/fixSignatureCaching.ts(980,23): error TS2304: Cannot find name 'define'. tests/cases/conformance/fixSignatureCaching.ts(980,48): error TS2304: Cannot find name 'define'. tests/cases/conformance/fixSignatureCaching.ts(981,16): error TS2304: Cannot find name 'define'. @@ -1143,12 +1143,12 @@ tests/cases/conformance/fixSignatureCaching.ts(983,44): error TS2339: Property ' })((function (undefined) { if (typeof module !== 'undefined' && module.exports) { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. return function (factory) { module.exports = factory(); }; ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. } else if (typeof define === 'function' && define.amd) { ~~~~~~ !!! error TS2304: Cannot find name 'define'. diff --git a/tests/baselines/reference/innerModExport1.errors.txt b/tests/baselines/reference/innerModExport1.errors.txt index 29ce225dfa2..1278afcb4d3 100644 --- a/tests/baselines/reference/innerModExport1.errors.txt +++ b/tests/baselines/reference/innerModExport1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/innerModExport1.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/innerModExport1.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected. @@ -9,7 +9,7 @@ tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected. var non_export_var: number; module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. var non_export_var = 0; diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index 21cc583c5d3..ffd136f1a65 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/innerModExport2.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/innerModExport2.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. @@ -12,7 +12,7 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport var non_export_var: number; module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. var non_export_var = 0; diff --git a/tests/baselines/reference/jsxAndTypeAssertion.errors.txt b/tests/baselines/reference/jsxAndTypeAssertion.errors.txt index 6d3f6874a88..c67e9c70dfd 100644 --- a/tests/baselines/reference/jsxAndTypeAssertion.errors.txt +++ b/tests/baselines/reference/jsxAndTypeAssertion.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,6): error TS17008: JSX element 'any' has no corresponding closing tag. -tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,13): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,13): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,17): error TS1005: '}' expected. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(8,6): error TS17008: JSX element 'any' has no corresponding closing tag. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(10,6): error TS17008: JSX element 'foo' has no corresponding closing tag. @@ -24,7 +24,7 @@ tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(21,1): error TS1005: '({ workItem: this._workItem }, {}); ~ -!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. +!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig. \ No newline at end of file diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index 990fa5816c7..568eb370e0d 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -5,8 +5,8 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,21): er tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(21,29): error TS2694: Namespace 'Harness' has no exported member 'Assert'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(25,17): error TS2304: Cannot find name 'IIO'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(41,12): error TS2304: Cannot find name 'ActiveXObject'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(43,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(44,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(43,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(44,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(341,13): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(347,13): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(351,17): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? @@ -169,10 +169,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): eval(typescriptServiceFile); } else if (typeof require === "function") { ~~~~~~~ -!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. var vm = require('vm'); ~~~~~~~ -!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. vm.runInThisContext(typescriptServiceFile, 'typescriptServices.js'); } else { throw new Error('Unknown context'); diff --git a/tests/baselines/reference/reservedWords2.errors.txt b/tests/baselines/reference/reservedWords2.errors.txt index 437b414a69d..b4af3c52916 100644 --- a/tests/baselines/reference/reservedWords2.errors.txt +++ b/tests/baselines/reference/reservedWords2.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/reservedWords2.ts(1,8): error TS1109: Expression expected. tests/cases/compiler/reservedWords2.ts(1,14): error TS1005: '(' expected. -tests/cases/compiler/reservedWords2.ts(1,16): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/reservedWords2.ts(1,16): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/reservedWords2.ts(1,31): error TS1005: ')' expected. tests/cases/compiler/reservedWords2.ts(2,12): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(2,12): error TS2567: Enum declarations can only merge with namespace or other enum declarations. @@ -14,7 +14,7 @@ tests/cases/compiler/reservedWords2.ts(5,9): error TS2300: Duplicate identifier tests/cases/compiler/reservedWords2.ts(5,9): error TS2567: Enum declarations can only merge with namespace or other enum declarations. tests/cases/compiler/reservedWords2.ts(5,10): error TS1003: Identifier expected. tests/cases/compiler/reservedWords2.ts(5,18): error TS1005: '=>' expected. -tests/cases/compiler/reservedWords2.ts(6,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/reservedWords2.ts(6,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/reservedWords2.ts(6,8): error TS1005: ';' expected. tests/cases/compiler/reservedWords2.ts(7,11): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(7,11): error TS1005: ':' expected. @@ -39,7 +39,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. ~ !!! error TS1005: '(' expected. ~~~~~~~ -!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ')' expected. import * as while from "foo" @@ -72,7 +72,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. !!! error TS1005: '=>' expected. module void {} ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~~~~ !!! error TS1005: ';' expected. var {while, return} = { while: 1, return: 2 }; diff --git a/tests/baselines/reference/staticsInAFunction.errors.txt b/tests/baselines/reference/staticsInAFunction.errors.txt index 499ab91e93f..33ca824de99 100644 --- a/tests/baselines/reference/staticsInAFunction.errors.txt +++ b/tests/baselines/reference/staticsInAFunction.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/staticsInAFunction.ts(1,13): error TS1005: '(' expected. tests/cases/compiler/staticsInAFunction.ts(2,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(2,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/staticsInAFunction.ts(2,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. tests/cases/compiler/staticsInAFunction.ts(3,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. tests/cases/compiler/staticsInAFunction.ts(3,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(3,20): error TS1005: ',' expected. tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. tests/cases/compiler/staticsInAFunction.ts(4,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(4,21): error TS1109: Expression expected. tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2693: 'any' only refers to a type, but is being used as a value here. @@ -22,12 +22,12 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. static test(name:string) ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ @@ -38,7 +38,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ diff --git a/tests/baselines/reference/templateStringInModuleName.errors.txt b/tests/baselines/reference/templateStringInModuleName.errors.txt index f684b305c52..3236b6da81c 100644 --- a/tests/baselines/reference/templateStringInModuleName.errors.txt +++ b/tests/baselines/reference/templateStringInModuleName.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,21): error TS1005: ';' expected. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error TS1005: ';' expected. @@ -15,7 +15,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. } @@ -26,7 +26,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInModuleNameES6.errors.txt b/tests/baselines/reference/templateStringInModuleNameES6.errors.txt index ecd072a7579..4526bb0d792 100644 --- a/tests/baselines/reference/templateStringInModuleNameES6.errors.txt +++ b/tests/baselines/reference/templateStringInModuleNameES6.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,21): error TS1005: ';' expected. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): error TS1005: ';' expected. @@ -15,7 +15,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): er ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. } @@ -26,7 +26,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): er ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/typecheckIfCondition.errors.txt b/tests/baselines/reference/typecheckIfCondition.errors.txt index e9c3707583e..5a9255f7f85 100644 --- a/tests/baselines/reference/typecheckIfCondition.errors.txt +++ b/tests/baselines/reference/typecheckIfCondition.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. -tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ==== tests/cases/compiler/typecheckIfCondition.ts (2 errors) ==== @@ -8,9 +8,9 @@ tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2580: Cannot find na { if (!module.exports) module.exports = ""; ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. var x = null; // don't want to baseline output } \ No newline at end of file diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 67f1c4877ee..2402a2a07b4 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 67f1c4877ee1090b66d468a847caccca411a6f82 +Subproject commit 2402a2a07b434411dbc8a529b41d0d1d41befca5 From 437bc41e99c8457eaa4b9f14aa593a7c3aa139d0 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 11:56:34 -0700 Subject: [PATCH 156/262] For path completions, include extension as a kindModifier (#28148) --- src/harness/fourslash.ts | 14 ++-- src/services/completions.ts | 18 ++++- src/services/pathCompletions.ts | 70 ++++++++++--------- src/services/types.ts | 9 ++- .../reference/api/tsserverlibrary.d.ts | 8 ++- tests/baselines/reference/api/typescript.d.ts | 8 ++- .../completionEntryForClassMembers2.ts | 16 ++--- .../completionForStringLiteral_details.ts | 2 +- .../completionInJsDocQualifiedNames.ts | 11 ++- .../completionListOfGenericSymbol.ts | 2 + .../fourslash/completionsImportBaseUrl.ts | 1 + ...completionsImport_compilerOptionsModule.ts | 2 +- .../completionsImport_defaultFalsePositive.ts | 12 +++- ...letionsImport_default_addToNamedImports.ts | 1 + ...ionsImport_default_addToNamespaceImport.ts | 10 ++- ...Import_default_alreadyExistedWithRename.ts | 10 ++- .../completionsImport_default_anonymous.ts | 5 +- ...letionsImport_default_didNotExistBefore.ts | 10 ++- ...nsImport_default_fromMergedDeclarations.ts | 10 ++- .../fourslash/completionsImport_matching.ts | 2 +- .../completionsImport_multipleWithSameName.ts | 22 +++++- ...mpletionsImport_named_addToNamedImports.ts | 10 ++- ...mpletionsImport_named_didNotExistBefore.ts | 2 +- ...tionsImport_named_exportEqualsNamespace.ts | 10 ++- ...port_named_exportEqualsNamespace_merged.ts | 10 ++- ...tionsImport_named_namespaceImportExists.ts | 10 ++- .../completionsImport_notFromIndex.ts | 10 ++- ...mpletionsImport_ofAlias_preferShortPath.ts | 2 +- ...pletionsImport_previousTokenIsSemicolon.ts | 10 ++- .../completionsImport_reExportDefault.ts | 19 ++++- .../fourslash/completionsImport_require.ts | 10 ++- tests/cases/fourslash/completionsInJsxTag.ts | 11 ++- .../fourslash/completionsJsxAttribute.ts | 4 +- .../completionsOptionalKindModifier.ts | 4 +- tests/cases/fourslash/completionsPaths.ts | 12 +++- .../fourslash/completionsPathsJsonModule.ts | 6 +- .../completionsPathsRelativeJsonModule.ts | 6 +- .../fourslash/completionsPaths_fromTypings.ts | 7 +- .../fourslash/completionsPaths_importType.ts | 18 ++++- .../cases/fourslash/completionsPaths_kinds.ts | 5 +- .../fourslash/completionsPaths_pathMapping.ts | 16 ++++- ...etionsPaths_pathMapping_parentDirectory.ts | 6 +- ...mpletionsPaths_pathMapping_relativePath.ts | 6 +- .../completionsPaths_pathMapping_topLevel.ts | 6 +- .../completionsRecommended_import.ts | 1 + .../fourslash/completionsRecommended_local.ts | 1 + .../completionsRecommended_namespace.ts | 16 ++++- tests/cases/fourslash/exportDefaultClass.ts | 2 +- .../cases/fourslash/exportDefaultFunction.ts | 2 +- .../fourslash/getJavaScriptCompletions1.ts | 2 +- .../fourslash/getJavaScriptCompletions10.ts | 2 +- .../fourslash/getJavaScriptCompletions11.ts | 4 +- .../fourslash/getJavaScriptCompletions12.ts | 4 +- .../fourslash/getJavaScriptCompletions16.ts | 4 +- .../fourslash/getJavaScriptCompletions18.ts | 4 +- .../fourslash/getJavaScriptCompletions19.ts | 4 +- .../fourslash/getJavaScriptCompletions2.ts | 2 +- .../fourslash/getJavaScriptCompletions3.ts | 2 +- .../fourslash/getJavaScriptCompletions4.ts | 2 +- .../fourslash/getJavaScriptCompletions5.ts | 2 +- .../fourslash/getJavaScriptCompletions8.ts | 2 +- .../fourslash/getJavaScriptCompletions9.ts | 2 +- .../fourslash/getJavaScriptQuickInfo8.ts | 4 +- tests/cases/fourslash/importJsNodeModule1.ts | 2 +- tests/cases/fourslash/importJsNodeModule2.ts | 2 +- tests/cases/fourslash/importJsNodeModule3.ts | 4 +- tests/cases/fourslash/importJsNodeModule4.ts | 2 +- tests/cases/fourslash/javaScriptClass4.ts | 2 +- tests/cases/fourslash/javaScriptModules13.ts | 2 +- tests/cases/fourslash/javaScriptModules15.ts | 2 +- tests/cases/fourslash/javaScriptModules16.ts | 2 +- tests/cases/fourslash/javaScriptModules17.ts | 2 +- tests/cases/fourslash/javaScriptModules19.ts | 2 +- tests/cases/fourslash/javaScriptPrototype1.ts | 2 +- tests/cases/fourslash/javaScriptPrototype2.ts | 2 +- .../fourslash/jsDocFunctionSignatures3.ts | 4 +- tests/cases/fourslash/jsDocGenerics1.ts | 2 +- ...JsdocTypedefTagTypeExpressionCompletion.ts | 4 +- ...sdocTypedefTagTypeExpressionCompletion3.ts | 4 +- ...jsdocTypedefTagTypeExpressionCompletion.ts | 6 +- ...oImportCompletionsInOtherJavaScriptFile.ts | 1 + 81 files changed, 405 insertions(+), 147 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 6a1aa70bf3e..8f83f0bc3f0 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -796,8 +796,8 @@ namespace FourSlash { } private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) { - const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, tags, source, sourceDisplay } = typeof expected === "string" - ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined } + const { insertText, replacementSpan, hasAction, isRecommended, kind, kindModifiers, text, documentation, tags, source, sourceDisplay } = typeof expected === "string" + ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined } : expected; if (actual.insertText !== insertText) { @@ -811,8 +811,12 @@ namespace FourSlash { this.raiseError(`Expected completion replacementSpan to be ${stringify(convertedReplacementSpan)}, got ${stringify(actual.replacementSpan)}`); } - if (kind !== undefined) assert.equal(actual.kind, kind); - if (typeof expected !== "string" && "kindModifiers" in expected) assert.equal(actual.kindModifiers, expected.kindModifiers); + if (kind !== undefined || kindModifiers !== undefined) { + assert.equal(actual.kind, kind); + if (actual.kindModifiers !== (kindModifiers || "")) { + this.raiseError(`Bad kind modifiers for ${actual.name}: Expected ${kindModifiers || ""}, actual ${actual.kindModifiers}`); + } + } assert.equal(actual.hasAction, hasAction); assert.equal(actual.isRecommended, isRecommended); @@ -4916,7 +4920,7 @@ namespace FourSlashInterface { readonly hasAction?: boolean, // If not specified, will assert that this is false. readonly isRecommended?: boolean; // If not specified, will assert that this is false. readonly kind?: string, // If not specified, won't assert about this - readonly kindModifiers?: string; + readonly kindModifiers?: string, // Must be paired with 'kind' readonly text?: string; readonly documentation?: string; readonly sourceDisplay?: string; diff --git a/src/services/completions.ts b/src/services/completions.ts index 0e0bf50cf83..af9cc3d240a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -101,9 +101,23 @@ namespace ts.Completions { function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - const entries = pathCompletions.map(({ name, kind, span }) => ({ name, kind, kindModifiers: ScriptElementKindModifier.none, sortText: "0", replacementSpan: span })); + const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => + ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span })); return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; } + function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier { + switch (extension) { + case Extension.Dts: return ScriptElementKindModifier.dtsModifier; + case Extension.Js: return ScriptElementKindModifier.jsModifier; + case Extension.Json: return ScriptElementKindModifier.jsonModifier; + case Extension.Jsx: return ScriptElementKindModifier.jsxModifier; + case Extension.Ts: return ScriptElementKindModifier.tsModifier; + case Extension.Tsx: return ScriptElementKindModifier.tsxModifier; + case undefined: return ScriptElementKindModifier.none; + default: + return Debug.assertNever(extension); + } + } function jsdocCompletionInfo(entries: CompletionEntry[]): CompletionInfo { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; @@ -638,7 +652,7 @@ namespace ts.Completions { switch (completion.kind) { case StringLiteralCompletionKind.Paths: { const match = find(completion.paths, p => p.name === name); - return match && createCompletionDetails(name, ScriptElementKindModifier.none, match.kind, [textPart(name)]); + return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); } case StringLiteralCompletionKind.Properties: { const match = find(completion.symbols, s => s.name === name); diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index d1c365c7117..97ed722dd16 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -3,17 +3,22 @@ namespace ts.Completions.PathCompletions { export interface NameAndKind { readonly name: string; readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; + readonly extension: Extension | undefined; } export interface PathCompletion extends NameAndKind { readonly span: TextSpan | undefined; } - function nameAndKind(name: string, kind: NameAndKind["kind"]): NameAndKind { - return { name, kind }; + function nameAndKind(name: string, kind: NameAndKind["kind"], extension: Extension | undefined): NameAndKind { + return { name, kind, extension }; } + function directoryResult(name: string): NameAndKind { + return nameAndKind(name, ScriptElementKind.directory, /*extension*/ undefined); + } + function addReplacementSpans(text: string, textStart: number, names: ReadonlyArray): ReadonlyArray { const span = getDirectoryFragmentTextSpan(text, textStart); - return names.map(({ name, kind }): PathCompletion => ({ name, kind, span })); + return names.map(({ name, kind, extension }): PathCompletion => ({ name, kind, extension, span })); } export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { @@ -129,7 +134,7 @@ namespace ts.Completions.PathCompletions { * * both foo.ts and foo.tsx become foo */ - const foundFiles = createMap(); + const foundFiles = createMap(); // maps file to its extension for (let filePath of files) { filePath = normalizePath(filePath); if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) { @@ -137,14 +142,11 @@ namespace ts.Completions.PathCompletions { } const foundFileName = includeExtensions || fileExtensionIs(filePath, Extension.Json) ? getBaseFileName(filePath) : removeFileExtension(getBaseFileName(filePath)); - - if (!foundFiles.has(foundFileName)) { - foundFiles.set(foundFileName, true); - } + foundFiles.set(foundFileName, tryGetExtensionFromPath(filePath)); } - forEachKey(foundFiles, foundFile => { - result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement)); + foundFiles.forEach((ext, foundFile) => { + result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement, ext)); }); } @@ -155,7 +157,7 @@ namespace ts.Completions.PathCompletions { for (const directory of directories) { const directoryName = getBaseFileName(normalizePath(directory)); if (directoryName !== "@types") { - result.push(nameAndKind(directoryName, ScriptElementKind.directory)); + result.push(directoryResult(directoryName)); } } } @@ -183,10 +185,10 @@ namespace ts.Completions.PathCompletions { if (!hasProperty(paths, path)) continue; const patterns = paths[path]; if (patterns) { - for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)) { + for (const { name, kind, extension } of getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(entry => entry.name === name)) { - result.push(nameAndKind(name, kind)); + result.push(nameAndKind(name, kind, extension)); } } } @@ -200,7 +202,7 @@ namespace ts.Completions.PathCompletions { * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): NameAndKind[] { + function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { const { baseUrl, paths } = compilerOptions; const result: NameAndKind[] = []; @@ -217,7 +219,7 @@ namespace ts.Completions.PathCompletions { const fragmentDirectory = getFragmentDirectory(fragment); for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { - result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName)); + result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); @@ -230,7 +232,7 @@ namespace ts.Completions.PathCompletions { for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) { if (!result.some(entry => entry.name === moduleName)) { foundGlobal = true; - result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); + result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); } } } @@ -265,7 +267,7 @@ namespace ts.Completions.PathCompletions { getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host)); function justPathMappingName(name: string): ReadonlyArray { - return startsWith(name, fragment) ? [{ name, kind: ScriptElementKind.directory }] : emptyArray; + return startsWith(name, fragment) ? [directoryResult(name)] : emptyArray; } } @@ -301,15 +303,21 @@ namespace ts.Completions.PathCompletions { // doesn't support. For now, this is safer but slower const includeGlob = normalizedSuffix ? "**/*" : "./*"; - const matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]).map(name => ({ name, kind: ScriptElementKind.scriptElement })); - const directories = tryGetDirectories(host, baseDirectory).map(d => combinePaths(baseDirectory, d)).map(name => ({ name, kind: ScriptElementKind.directory })); - - // Trim away prefix and suffix - return mapDefined(concatenate(matches, directories), ({ name, kind }) => { - const normalizedMatch = normalizePath(name); - const inner = withoutStartAndEnd(normalizedMatch, completePrefix, normalizedSuffix); - return inner !== undefined ? { name: removeLeadingDirectorySeparator(removeFileExtension(inner)), kind } : undefined; + const matches = mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), match => { + const extension = tryGetExtensionFromPath(match); + const name = trimPrefixAndSuffix(match); + return name === undefined ? undefined : nameAndKind(removeFileExtension(name), ScriptElementKind.scriptElement, extension); }); + const directories = mapDefined(tryGetDirectories(host, baseDirectory).map(d => combinePaths(baseDirectory, d)), dir => { + const name = trimPrefixAndSuffix(dir); + return name === undefined ? undefined : directoryResult(name); + }); + return [...matches, ...directories]; + + function trimPrefixAndSuffix(path: string): string | undefined { + const inner = withoutStartAndEnd(normalizePath(path), completePrefix, normalizedSuffix); + return inner === undefined ? undefined : removeLeadingDirectorySeparator(inner); + } } function withoutStartAndEnd(s: string, start: string, end: string): string | undefined { @@ -382,7 +390,10 @@ namespace ts.Completions.PathCompletions { if (options.types && !contains(options.types, packageName)) continue; if (fragmentDirectory === undefined) { - pushResult(packageName); + if (!seen.has(packageName)) { + result.push(nameAndKind(packageName, ScriptElementKind.externalModuleName, /*extension*/ undefined)); + seen.set(packageName, true); + } } else { const baseDirectory = combinePaths(directory, typeDirectoryName); @@ -393,13 +404,6 @@ namespace ts.Completions.PathCompletions { } } } - - function pushResult(moduleName: string) { - if (!seen.has(moduleName)) { - result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName)); - seen.set(moduleName, true); - } - } } function findPackageJsons(directory: string, host: LanguageServiceHost): string[] { diff --git a/src/services/types.ts b/src/services/types.ts index a43da2b6465..d517c61906a 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -1126,7 +1126,14 @@ namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json", } export const enum ClassificationTypeNames { diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 2ea0d677709..ccc9557e948 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -5369,7 +5369,13 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" } enum ClassificationTypeNames { comment = "comment", diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 91c8c397501..8f047351750 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -5369,7 +5369,13 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional" + optionalModifier = "optional", + dtsModifier = ".d.ts", + tsModifier = ".ts", + tsxModifier = ".tsx", + jsModifier = ".js", + jsxModifier = ".jsx", + jsonModifier = ".json" } enum ClassificationTypeNames { comment = "comment", diff --git a/tests/cases/fourslash/completionEntryForClassMembers2.ts b/tests/cases/fourslash/completionEntryForClassMembers2.ts index 1048b5b47d0..2ea00966ad3 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers2.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers2.ts @@ -189,18 +189,18 @@ ////} const validInstanceMembersOfBaseClassB: ReadonlyArray = [ - { name: "protectedMethod", text: "(method) B.protectedMethod(): void" }, + { name: "protectedMethod", text: "(method) B.protectedMethod(): void", kindModifiers: "protected" }, { name: "getValue", text: "(method) B.getValue(): string | boolean" }, ]; const validStaticMembersOfBaseClassB: ReadonlyArray = [ - { name: "staticMethod", text: "(method) B.staticMethod(): void" }, + { name: "staticMethod", text: "(method) B.staticMethod(): void", kindModifiers: "static" }, ]; const privateMembersOfBaseClassB: ReadonlyArray = [ { name: "privateMethod", text: "(method) B.privateMethod(): void" }, ]; const protectedPropertiesOfBaseClassB0: ReadonlyArray = [ - { name: "protectedMethod", text: "(method) B0.protectedMethod(): void" }, - { name: "protectedMethod1", text: "(method) B0.protectedMethod1(): void" }, + { name: "protectedMethod", text: "(method) B0.protectedMethod(): void", kindModifiers: "protected" }, + { name: "protectedMethod1", text: "(method) B0.protectedMethod1(): void", kindModifiers: "protected" }, ]; const publicPropertiesOfBaseClassB0: ReadonlyArray = [ { name: "getValue", text: "(method) B0.getValue(): string | boolean" }, @@ -214,12 +214,12 @@ const validInstanceMembersOfBaseClassB0_2 : ReadonlyArray = [ - { name: "staticMethod", text: "(method) B0.staticMethod(): void" }, - { name: "staticMethod1", text: "(method) B0.staticMethod1(): void" }, + { name: "staticMethod", text: "(method) B0.staticMethod(): void", kindModifiers: "static" }, + { name: "staticMethod1", text: "(method) B0.staticMethod1(): void", kindModifiers: "static" }, ]; const privateMembersOfBaseClassB0: ReadonlyArray = [ - { name: "privateMethod", text: "(method) B0.privateMethod(): void" }, - { name: "privateMethod1", text: "(method) B0.privateMethod1(): void" }, + { name: "privateMethod", text: "(method) B0.privateMethod(): void", kindModifiers: "private" }, + { name: "privateMethod1", text: "(method) B0.privateMethod1(): void", kindModifiers: "private" }, ]; const membersOfI: ReadonlyArray = [ { name: "methodOfInterface", text: "(method) I.methodOfInterface(): number" }, diff --git a/tests/cases/fourslash/completionForStringLiteral_details.ts b/tests/cases/fourslash/completionForStringLiteral_details.ts index f7ef83f6f39..8c6e4d36481 100644 --- a/tests/cases/fourslash/completionForStringLiteral_details.ts +++ b/tests/cases/fourslash/completionForStringLiteral_details.ts @@ -18,7 +18,7 @@ ////o["/*prop*/"]; verify.completions( - { marker: "path", includes: { name: "other", text: "other", kind: "script" }, isNewIdentifierLocation: true }, + { marker: "path", includes: { name: "other", text: "other", kind: "script", kindModifiers: ".ts" }, isNewIdentifierLocation: true }, { marker: "type", exact: { name: "a", text: "a", kind: "string" } }, { marker: "prop", diff --git a/tests/cases/fourslash/completionInJsDocQualifiedNames.ts b/tests/cases/fourslash/completionInJsDocQualifiedNames.ts index f5ce027f131..eec6f18f592 100644 --- a/tests/cases/fourslash/completionInJsDocQualifiedNames.ts +++ b/tests/cases/fourslash/completionInJsDocQualifiedNames.ts @@ -11,4 +11,13 @@ /////** @type {Foo./**/} */ ////const x = 0; -verify.completions({ marker: "", includes: { name: "T", text: "type T = number", documentation: "tee", kind: "type" } }); +verify.completions({ + marker: "", + includes: { + name: "T", + text: "type T = number", + documentation: "tee", + kind: "type", + kindModifiers: "export,declare", + }, +}); diff --git a/tests/cases/fourslash/completionListOfGenericSymbol.ts b/tests/cases/fourslash/completionListOfGenericSymbol.ts index 804b2c1d297..380407d2390 100644 --- a/tests/cases/fourslash/completionListOfGenericSymbol.ts +++ b/tests/cases/fourslash/completionListOfGenericSymbol.ts @@ -13,12 +13,14 @@ verify.completions({ text: "(property) Array.length: number", documentation: "Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.", kind: "property", + kindModifiers: "declare", }, { name: "toString", text: "(method) Array.toString(): string", documentation: "Returns a string representation of an array.", kind: "method", + kindModifiers: "declare", }, ], }); diff --git a/tests/cases/fourslash/completionsImportBaseUrl.ts b/tests/cases/fourslash/completionsImportBaseUrl.ts index 413c7984215..d3fa4d7033e 100644 --- a/tests/cases/fourslash/completionsImportBaseUrl.ts +++ b/tests/cases/fourslash/completionsImportBaseUrl.ts @@ -23,6 +23,7 @@ verify.completions({ sourceDisplay: "./a", text: "const foo: 0", kind: "const", + kindModifiers: "export", hasAction: true, }, preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_compilerOptionsModule.ts b/tests/cases/fourslash/completionsImport_compilerOptionsModule.ts index a5b8b0c07c2..6d1c22aec0c 100644 --- a/tests/cases/fourslash/completionsImport_compilerOptionsModule.ts +++ b/tests/cases/fourslash/completionsImport_compilerOptionsModule.ts @@ -27,6 +27,6 @@ verify.completions({ marker: ["b", "c", "d"], excludes: "foo", preferences: { includeCompletionsForModuleExports: true } }); verify.completions({ marker: ["c2", "d2"], - includes: [{ name: "foo", source: "/node_modules/a/index", text: "const foo: 0", kind: "const", hasAction: true, sourceDisplay: "a" }], + includes: [{ name: "foo", source: "/node_modules/a/index", text: "const foo: 0", kind: "const", kindModifiers: "export,declare", hasAction: true, sourceDisplay: "a" }], preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_defaultFalsePositive.ts b/tests/cases/fourslash/completionsImport_defaultFalsePositive.ts index 65088dc7756..e077e18105b 100644 --- a/tests/cases/fourslash/completionsImport_defaultFalsePositive.ts +++ b/tests/cases/fourslash/completionsImport_defaultFalsePositive.ts @@ -14,9 +14,15 @@ goTo.file("/a.ts"); verify.completions({ marker: "", - includes: [ - { name: "concat", source: "/node_modules/bar/concat", sourceDisplay: "bar/concat", text: "const concat: 0", kind: "const", hasAction: true }, - ], + includes: { + name: "concat", + source: "/node_modules/bar/concat", + sourceDisplay: "bar/concat", + text: "const concat: 0", + kind: "const", + kindModifiers: "export,declare", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts b/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts index 35c06d5a550..8bd9f194758 100644 --- a/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts +++ b/tests/cases/fourslash/completionsImport_default_addToNamedImports.ts @@ -16,6 +16,7 @@ verify.completions({ sourceDisplay: "./a", text: "function foo(): void", kind: "function", + kindModifiers: "export", hasAction: true, }, preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts b/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts index 0a52a7103ee..8debd787641 100644 --- a/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts +++ b/tests/cases/fourslash/completionsImport_default_addToNamespaceImport.ts @@ -9,7 +9,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts b/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts index d3027bb18cf..b04a7cacffe 100644 --- a/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts +++ b/tests/cases/fourslash/completionsImport_default_alreadyExistedWithRename.ts @@ -9,7 +9,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_default_anonymous.ts b/tests/cases/fourslash/completionsImport_default_anonymous.ts index 46b333beb29..8aa9dfb5af6 100644 --- a/tests/cases/fourslash/completionsImport_default_anonymous.ts +++ b/tests/cases/fourslash/completionsImport_default_anonymous.ts @@ -14,10 +14,7 @@ goTo.marker("0"); const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; verify.completions( - { - marker: "0", - exact: ["undefined", ...completion.statementKeywordsWithTypes], - }, + { marker: "0", exact: ["undefined", ...completion.statementKeywordsWithTypes], preferences }, { marker: "1", includes: { name: "fooBar", source: "/src/foo-bar", sourceDisplay: "./foo-bar", text: "(property) default: 0", kind: "property", hasAction: true }, diff --git a/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts b/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts index 69138fa9815..259a22d637b 100644 --- a/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts +++ b/tests/cases/fourslash/completionsImport_default_didNotExistBefore.ts @@ -10,7 +10,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts b/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts index c4cfcb98531..551cfb54e75 100644 --- a/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts +++ b/tests/cases/fourslash/completionsImport_default_fromMergedDeclarations.ts @@ -17,7 +17,15 @@ verify.completions({ marker: "", - includes: { name: "M", source: "m", sourceDisplay: "m", text: "class M", kind: "class", hasAction: true }, + includes: { + name: "M", + source: "m", + sourceDisplay: "m", + text: "class M", + kind: "class", + kindModifiers: "export,declare", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_matching.ts b/tests/cases/fourslash/completionsImport_matching.ts index 92c09b49644..c6dbac369b9 100644 --- a/tests/cases/fourslash/completionsImport_matching.ts +++ b/tests/cases/fourslash/completionsImport_matching.ts @@ -17,7 +17,7 @@ verify.completions({ marker: "", includes: ["bdf", "abcdef", "BDF"].map(name => - ({ name, source: "/a", text: `function ${name}(): void`, hasAction: true, kind: "function", sourceDisplay: "./a" })), + ({ name, source: "/a", text: `function ${name}(): void`, hasAction: true, kind: "function", kindModifiers: "export", sourceDisplay: "./a" })), excludes: ["abcde", "dbf"], preferences: { includeCompletionsForModuleExports: true }, }) diff --git a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts index 7df6fbfd874..ae552f437fe 100644 --- a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts +++ b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts @@ -20,10 +20,26 @@ goTo.marker(""); verify.completions({ marker: "", exact: [ - { name: "foo", text: "var foo: number", kind: "var" }, + { name: "foo", text: "var foo: number", kind: "var", kindModifiers: "declare" }, "undefined", - { name: "foo", source: "/a", sourceDisplay: "./a", text: "const foo: 0", kind: "const", hasAction: true }, - { name: "foo", source: "/b", sourceDisplay: "./b", text: "const foo: 1", kind: "const", hasAction: true }, + { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "const foo: 0", + kind: "const", + kindModifiers: "export", + hasAction: true, + }, + { + name: "foo", + source: "/b", + sourceDisplay: "./b", + text: "const foo: 1", + kind: "const", + kindModifiers: "export", + hasAction: true, + }, ...completion.statementKeywordsWithTypes, ], preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts b/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts index 3442d90e05b..78df2659ade 100644 --- a/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts +++ b/tests/cases/fourslash/completionsImport_named_addToNamedImports.ts @@ -10,7 +10,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts index 321f27ce760..10a0c124e4d 100644 --- a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts +++ b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts @@ -15,7 +15,7 @@ verify.completions({ exact: [ { name: "Test2", text: "(alias) function Test2(): void\nimport Test2", kind: "alias" }, "undefined", - { name: "Test1", source: "/a", sourceDisplay: "./a", text: "function Test1(): void", kind: "function", hasAction: true }, + { name: "Test1", source: "/a", sourceDisplay: "./a", text: "function Test1(): void", kind: "function", kindModifiers: "export", hasAction: true }, ...completion.statementKeywordsWithTypes, ], preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts index c6c9bc45b2c..4f4b579fe49 100644 --- a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts +++ b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace.ts @@ -13,7 +13,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "const N.foo: 0", kind: "const", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "const N.foo: 0", + kind: "const", + kindModifiers: "export,declare", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts index f68c03f5602..ec70d205479 100644 --- a/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts +++ b/tests/cases/fourslash/completionsImport_named_exportEqualsNamespace_merged.ts @@ -18,6 +18,14 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "n", sourceDisplay: "n", text: "const N.foo: number", kind: "const", hasAction: true }, + includes: { + name: "foo", + source: "n", + sourceDisplay: "n", + text: "const N.foo: number", + kind: "const", + kindModifiers: "export,declare", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts b/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts index 4416b3703c9..52c33209ca3 100644 --- a/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts +++ b/tests/cases/fourslash/completionsImport_named_namespaceImportExists.ts @@ -9,7 +9,15 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("", { diff --git a/tests/cases/fourslash/completionsImport_notFromIndex.ts b/tests/cases/fourslash/completionsImport_notFromIndex.ts index 4ab8eaf1012..e6aa3e680b1 100644 --- a/tests/cases/fourslash/completionsImport_notFromIndex.ts +++ b/tests/cases/fourslash/completionsImport_notFromIndex.ts @@ -18,7 +18,15 @@ for (const [marker, sourceDisplay] of [["0", "./src"], ["1", "./a"], ["2", "../a"]]) { verify.completions({ marker, - includes: { name: "x", source: "/src/a", sourceDisplay, text: "const x: 0", kind: "const", hasAction: true }, + includes: { + name: "x", + source: "/src/a", + sourceDisplay, + text: "const x: 0", + kind: "const", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion(marker, { diff --git a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts index 81d195d0175..f5efa9cd912 100644 --- a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts +++ b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts @@ -20,7 +20,7 @@ verify.completions({ marker: "", exact: [ "undefined", - { name: "foo", source: "/foo/lib/foo", sourceDisplay: "./foo", text: "const foo: 0", kind: "const", hasAction: true }, + { name: "foo", source: "/foo/lib/foo", sourceDisplay: "./foo", text: "const foo: 0", kind: "const", kindModifiers: "export", hasAction: true }, ...completion.statementKeywordsWithTypes, ], preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts b/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts index 36649451530..7099c4b3072 100644 --- a/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts +++ b/tests/cases/fourslash/completionsImport_previousTokenIsSemicolon.ts @@ -9,6 +9,14 @@ verify.completions({ marker: "", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsImport_reExportDefault.ts b/tests/cases/fourslash/completionsImport_reExportDefault.ts index ae8af9c1d35..8e38faa0b05 100644 --- a/tests/cases/fourslash/completionsImport_reExportDefault.ts +++ b/tests/cases/fourslash/completionsImport_reExportDefault.ts @@ -17,8 +17,23 @@ verify.completions({ exact: [ ...completion.globalsVars, "undefined", - { name: "foo", source: "/a/b/impl", sourceDisplay: "./a", text: "function foo(): void", kind: "function", hasAction: true }, - { name: "foo", source: "/a/index", sourceDisplay: "./a", text: "(alias) function foo(): void\nexport foo", kind: "alias", hasAction: true }, + { + name: "foo", + source: "/a/b/impl", + sourceDisplay: "./a", + text: "function foo(): void", + kind: "function", + kindModifiers: "export", + hasAction: true, + }, + { + name: "foo", + source: "/a/index", + sourceDisplay: "./a", + text: "(alias) function foo(): void\nexport foo", + kind: "alias", + hasAction: true, + }, ...completion.globalKeywords, ], preferences: { includeCompletionsForModuleExports: true }, diff --git a/tests/cases/fourslash/completionsImport_require.ts b/tests/cases/fourslash/completionsImport_require.ts index 6002366ce02..892a2495485 100644 --- a/tests/cases/fourslash/completionsImport_require.ts +++ b/tests/cases/fourslash/completionsImport_require.ts @@ -11,7 +11,15 @@ verify.completions({ marker: "b", - includes: { name: "foo", source: "/a", sourceDisplay: "./a", text: "const foo: 0", kind: "const", hasAction: true }, + includes: { + name: "foo", + source: "/a", + sourceDisplay: "./a", + text: "const foo: 0", + kind: "const", + kindModifiers: "export", + hasAction: true, + }, preferences: { includeCompletionsForModuleExports: true }, }); verify.applyCodeActionFromCompletion("b", { diff --git a/tests/cases/fourslash/completionsInJsxTag.ts b/tests/cases/fourslash/completionsInJsxTag.ts index e2921aecd15..1977333b62b 100644 --- a/tests/cases/fourslash/completionsInJsxTag.ts +++ b/tests/cases/fourslash/completionsInJsxTag.ts @@ -19,4 +19,13 @@ //// } ////} -verify.completions({ marker: ["1", "2"], exact: { name: "foo", text: "(JSX attribute) foo: string", documentation: "Doc", kind: "JSX attribute" } }); +verify.completions({ + marker: ["1", "2"], + exact: { + name: "foo", + text: "(JSX attribute) foo: string", + documentation: "Doc", + kind: "JSX attribute", + kindModifiers: "declare", + }, +}); diff --git a/tests/cases/fourslash/completionsJsxAttribute.ts b/tests/cases/fourslash/completionsJsxAttribute.ts index c4d1513a6ee..4c02e1fd355 100644 --- a/tests/cases/fourslash/completionsJsxAttribute.ts +++ b/tests/cases/fourslash/completionsJsxAttribute.ts @@ -17,8 +17,8 @@ ////
; const exact: ReadonlyArray = [ - { name: "foo", kind: "JSX attribute", text: "(JSX attribute) foo: boolean", documentation: "Doc" }, - { name: "bar", kind: "JSX attribute", text: "(JSX attribute) bar: string" }, + { name: "foo", kind: "JSX attribute", kindModifiers: "declare", text: "(JSX attribute) foo: boolean", documentation: "Doc" }, + { name: "bar", kind: "JSX attribute", kindModifiers: "declare", text: "(JSX attribute) bar: string" }, ]; verify.completions({ marker: "", exact }); edit.insert("f"); diff --git a/tests/cases/fourslash/completionsOptionalKindModifier.ts b/tests/cases/fourslash/completionsOptionalKindModifier.ts index 1592fb5d10b..a8c2eb5d63b 100644 --- a/tests/cases/fourslash/completionsOptionalKindModifier.ts +++ b/tests/cases/fourslash/completionsOptionalKindModifier.ts @@ -8,7 +8,7 @@ verify.completions({ marker: "a", exact: [ - { name: "a", kindModifiers: "optional" }, - { name: "method", kindModifiers: "optional" }, + { name: "a", kind: "property", kindModifiers: "optional" }, + { name: "method", kind: "method", kindModifiers: "optional" }, ], }); diff --git a/tests/cases/fourslash/completionsPaths.ts b/tests/cases/fourslash/completionsPaths.ts index e875e3e2147..8dc33a5f45b 100644 --- a/tests/cases/fourslash/completionsPaths.ts +++ b/tests/cases/fourslash/completionsPaths.ts @@ -24,6 +24,14 @@ ////const foo = require(`x//*4*/`); verify.completions( - { marker: "1", exact: ["y", "x"], isNewIdentifierLocation: true }, - { marker: ["2", "3", "4"], exact: ["bar", "foo"], isNewIdentifierLocation: true }, + { + marker: "1", + exact: ["y", "x"].map(name => ({ name, kind: "directory" })), + isNewIdentifierLocation: true, + }, + { + marker: ["2", "3", "4"], + exact: ["bar", "foo"].map(name => ({ name, kind: "script", kindModifiers: ".d.ts" })), + isNewIdentifierLocation: true, + }, ); diff --git a/tests/cases/fourslash/completionsPathsJsonModule.ts b/tests/cases/fourslash/completionsPathsJsonModule.ts index fb3370c69c9..06600834a0b 100644 --- a/tests/cases/fourslash/completionsPathsJsonModule.ts +++ b/tests/cases/fourslash/completionsPathsJsonModule.ts @@ -9,4 +9,8 @@ // @Filename: /project/index.ts ////import { } from "/**/"; -verify.completions({ marker: "", exact: "test.json", isNewIdentifierLocation: true }); +verify.completions({ + marker: "", + exact: { name: "test.json", kind: "script", kindModifiers: ".json" }, + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts b/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts index a0c9f92e545..2f9c1bcf6e2 100644 --- a/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts +++ b/tests/cases/fourslash/completionsPathsRelativeJsonModule.ts @@ -9,4 +9,8 @@ // @Filename: /project/index.ts ////import { } from ".//**/"; -verify.completions({ marker: "", exact: "test.json", isNewIdentifierLocation: true }); +verify.completions({ + marker: "", + exact: { name: "test.json", kind: "script", kindModifiers: ".json" }, + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionsPaths_fromTypings.ts b/tests/cases/fourslash/completionsPaths_fromTypings.ts index 65547b3111d..c7382784cbf 100644 --- a/tests/cases/fourslash/completionsPaths_fromTypings.ts +++ b/tests/cases/fourslash/completionsPaths_fromTypings.ts @@ -13,6 +13,9 @@ verify.completions( { marker: "0", exact: [], isNewIdentifierLocation: true }, - { marker: "1", exact: ["bar", "index"], isNewIdentifierLocation: true }, - { marker: "2", exact: ["bar", "index"], isNewIdentifierLocation: true }, + { + marker: ["1", "2"], + exact: ["bar", "index"].map(name => ({ name, kind: "script", kindModifiers: ".d.ts" })), + isNewIdentifierLocation: true, + }, ); diff --git a/tests/cases/fourslash/completionsPaths_importType.ts b/tests/cases/fourslash/completionsPaths_importType.ts index 4d351f2494e..3541f2c39e7 100644 --- a/tests/cases/fourslash/completionsPaths_importType.ts +++ b/tests/cases/fourslash/completionsPaths_importType.ts @@ -17,7 +17,19 @@ /////** @type {import("/*3*/")} */ verify.completions( - { marker: "1", exact: "package", isNewIdentifierLocation: true }, - { marker: "2", exact: ["lib", "ns", "user", "node_modules"], isNewIdentifierLocation: true }, - { marker: "3", exact: ["package"], isNewIdentifierLocation: true }, + { + marker: ["1", "3"], + exact: { name: "package", kind: "directory" }, + isNewIdentifierLocation: true, + }, + { + marker: "2", + exact: [ + { name: "lib", kind: "script", kindModifiers: ".d.ts" }, + { name: "ns", kind: "script", kindModifiers: ".ts" }, + { name: "user", kind: "script", kindModifiers: ".js" }, + { name: "node_modules", kind: "directory" }, + ], + isNewIdentifierLocation: true + }, ); diff --git a/tests/cases/fourslash/completionsPaths_kinds.ts b/tests/cases/fourslash/completionsPaths_kinds.ts index 984ed17df22..e986457f7a0 100644 --- a/tests/cases/fourslash/completionsPaths_kinds.ts +++ b/tests/cases/fourslash/completionsPaths_kinds.ts @@ -22,6 +22,9 @@ verify.completions({ marker: ["0", "1"], - exact: [{ name: "b", kind: "script" }, { name: "dir", kind: "directory" }], + exact: [ + { name: "b", kind: "script", kindModifiers: ".ts" }, + { name: "dir", kind: "directory" }, + ], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping.ts b/tests/cases/fourslash/completionsPaths_pathMapping.ts index 9bff5424e5d..381fe5b7d38 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping.ts @@ -22,6 +22,18 @@ const [r0, r1] = test.ranges(); verify.completions( - { marker: "0", exact: ["a", "b", "dir"], isNewIdentifierLocation: true }, - { marker: "1", exact: "x", isNewIdentifierLocation: true }, + { + marker: "0", + exact: [ + { name: "a", kind: "script", kindModifiers: ".ts" }, + { name: "b", kind: "script", kindModifiers: ".ts" }, + { name: "dir", kind: "directory" }, + ], + isNewIdentifierLocation: true, + }, + { + marker: "1", + exact: { name: "x", kind: "script", kindModifiers: ".ts" }, + isNewIdentifierLocation: true, + }, ); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts index f870af30656..c34f6e5db88 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_parentDirectory.ts @@ -16,4 +16,8 @@ //// } ////} -verify.completions({ marker: "", exact: ["x"], isNewIdentifierLocation: true }); +verify.completions({ + marker: "", + exact: { name: "x", kind: "script", kindModifiers: ".ts" }, + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts index a86e5bcb0d3..b059a977eb9 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_relativePath.ts @@ -19,4 +19,8 @@ //// } ////} -verify.completions({ marker: "", exact: ["a", "b"], isNewIdentifierLocation: true }); +verify.completions({ + marker: "", + exact: ["a", "b"].map(name => ({ name, kind: "script", kindModifiers: ".ts" })), + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts index 9b9c67abbfc..a448abe2dff 100644 --- a/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts +++ b/tests/cases/fourslash/completionsPaths_pathMapping_topLevel.ts @@ -13,4 +13,8 @@ //// } ////} -verify.completions({ marker: "", exact: ["src", "foo/"], isNewIdentifierLocation: true }); +verify.completions({ + marker: "", + exact: ["src", "foo/"].map(name => ({ name, kind: "directory" })), + isNewIdentifierLocation: true, +}); diff --git a/tests/cases/fourslash/completionsRecommended_import.ts b/tests/cases/fourslash/completionsRecommended_import.ts index 4f58827f742..50e3c7b00aa 100644 --- a/tests/cases/fourslash/completionsRecommended_import.ts +++ b/tests/cases/fourslash/completionsRecommended_import.ts @@ -24,6 +24,7 @@ const classEntry = (isConstructor: boolean): FourSlashInterface.ExpectedCompleti source: "/a", sourceDisplay: "./a", kind: "class", + kindModifiers: "export", text: isConstructor ? "constructor Cls(): Cls" : "class Cls", hasAction: true, isRecommended: true, diff --git a/tests/cases/fourslash/completionsRecommended_local.ts b/tests/cases/fourslash/completionsRecommended_local.ts index 76690b7dbbd..51b43746a78 100644 --- a/tests/cases/fourslash/completionsRecommended_local.ts +++ b/tests/cases/fourslash/completionsRecommended_local.ts @@ -27,6 +27,7 @@ const abs = (ctr: boolean): FourSlashInterface.ExpectedCompletionEntry => ({ name: "Abs", text: ctr ? "constructor Abs(): Abs" : "class Abs", kind: "class", + kindModifiers: "abstract", }); verify.completions( diff --git a/tests/cases/fourslash/completionsRecommended_namespace.ts b/tests/cases/fourslash/completionsRecommended_namespace.ts index 9cf98f43b59..0d6e19e7106 100644 --- a/tests/cases/fourslash/completionsRecommended_namespace.ts +++ b/tests/cases/fourslash/completionsRecommended_namespace.ts @@ -23,10 +23,22 @@ ////alpha.f(new /*c1*/); verify.completions( - { marker: ["a0", "a1"], includes: { name: "Name", text: "namespace Name", kind: "module", isRecommended: true } }, + { + marker: ["a0", "a1"], + includes: { name: "Name", text: "namespace Name", kind: "module", kindModifiers: "export", isRecommended: true }, + }, { marker: ["b0", "b1"], - includes: { name: "Name", source: "/a", sourceDisplay: "./a", text: "namespace Name", kind: "module", hasAction: true, isRecommended: true, }, + includes: { + name: "Name", + source: "/a", + sourceDisplay: "./a", + text: "namespace Name", + kind: "module", + kindModifiers: "export", + hasAction: true, + isRecommended: true, + }, preferences: { includeCompletionsForModuleExports: true }, }, { marker: ["c0", "c1"], includes: { name: "alpha", text: "import alpha", kind: "alias", isRecommended: true } }, diff --git a/tests/cases/fourslash/exportDefaultClass.ts b/tests/cases/fourslash/exportDefaultClass.ts index da22984757a..5943eb75697 100644 --- a/tests/cases/fourslash/exportDefaultClass.ts +++ b/tests/cases/fourslash/exportDefaultClass.ts @@ -5,4 +5,4 @@ ////} //// /*2*/ -verify.completions({ marker: test.markers(), includes: { name: "C", text: "class C", kind: "class" } }); +verify.completions({ marker: test.markers(), includes: { name: "C", text: "class C", kind: "class", kindModifiers: "export" } }); diff --git a/tests/cases/fourslash/exportDefaultFunction.ts b/tests/cases/fourslash/exportDefaultFunction.ts index 3b7882e025d..4597c8a4e45 100644 --- a/tests/cases/fourslash/exportDefaultFunction.ts +++ b/tests/cases/fourslash/exportDefaultFunction.ts @@ -7,5 +7,5 @@ verify.completions({ marker: test.markers(), - includes: { name: "func", text: "function func(): void", kind: "function" }, + includes: { name: "func", text: "function func(): void", kind: "function", kindModifiers: "export" }, }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions1.ts b/tests/cases/fourslash/getJavaScriptCompletions1.ts index fd677b12354..51db240642b 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions1.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions1.ts @@ -6,4 +6,4 @@ ////var v; ////v./**/ -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions10.ts b/tests/cases/fourslash/getJavaScriptCompletions10.ts index 0eaccdb26b9..f12d5a5acf3 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions10.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions10.ts @@ -7,4 +7,4 @@ //// */ ////function f() { this./**/ } -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions11.ts b/tests/cases/fourslash/getJavaScriptCompletions11.ts index 9b15b09a277..e48beb09c3b 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions11.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions11.ts @@ -9,7 +9,7 @@ verify.completions({ marker: "", includes: [ - { name: "toExponential", kind: "method" }, - { name: "charCodeAt", kind: "method" }, + { name: "toExponential", kind: "method", kindModifiers: "declare" }, + { name: "charCodeAt", kind: "method", kindModifiers: "declare" }, ], }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions12.ts b/tests/cases/fourslash/getJavaScriptCompletions12.ts index a819f26e250..5534b20b8ea 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions12.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions12.ts @@ -24,7 +24,7 @@ ////var test1 = function(x) { return x./*4*/ }, test2 = function(a) { return a./*5*/ }; verify.completions( - { marker: "1", includes: { name: "charCodeAt", kind: "method" } }, - { marker: ["2", "3", "4"], includes: { name: "toExponential", kind: "method" } }, + { marker: "1", includes: { name: "charCodeAt", kind: "method", kindModifiers: "declare" } }, + { marker: ["2", "3", "4"], includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }, { marker: "5", includes: { name: "test1", kind: "warning" } }, ); diff --git a/tests/cases/fourslash/getJavaScriptCompletions16.ts b/tests/cases/fourslash/getJavaScriptCompletions16.ts index 8f698004eb4..112bef3c24b 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions16.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions16.ts @@ -24,7 +24,7 @@ goTo.marker('body'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); edit.backspace(); verify.signatureHelp({ @@ -35,4 +35,4 @@ verify.signatureHelp({ goTo.marker('method'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions18.ts b/tests/cases/fourslash/getJavaScriptCompletions18.ts index bad58889efb..efe0e7513d9 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions18.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions18.ts @@ -13,8 +13,8 @@ goTo.marker('a'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); goTo.marker('b'); edit.insert('.'); -verify.completions({ includes: { name: "substr", kind: "method" } }); +verify.completions({ includes: { name: "substr", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions19.ts b/tests/cases/fourslash/getJavaScriptCompletions19.ts index 0c90a32a322..54624eb3e4c 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions19.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions19.ts @@ -18,8 +18,8 @@ goTo.marker('str'); edit.insert('.'); -verify.completions({ includes: { name: "substr", kind: "method" } }); +verify.completions({ includes: { name: "substr", kind: "method", kindModifiers: "declare" } }); goTo.marker('num'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions2.ts b/tests/cases/fourslash/getJavaScriptCompletions2.ts index 4425e4a76e8..b7e4fa6a73a 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions2.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions2.ts @@ -6,4 +6,4 @@ ////var v; ////v./**/ -verify.completions({ marker: "", includes: { name: "valueOf", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "valueOf", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions3.ts b/tests/cases/fourslash/getJavaScriptCompletions3.ts index da2a05c0cfb..6f96d0dd324 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions3.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions3.ts @@ -6,4 +6,4 @@ ////var v; ////v./**/ -verify.completions({ marker: "", includes: { name: "concat", kind: "method" } }); \ No newline at end of file +verify.completions({ marker: "", includes: { name: "concat", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions4.ts b/tests/cases/fourslash/getJavaScriptCompletions4.ts index 841c60d91b4..8036493512d 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions4.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions4.ts @@ -6,4 +6,4 @@ ////function foo(a,b) { } ////foo(1,2)./**/ -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions5.ts b/tests/cases/fourslash/getJavaScriptCompletions5.ts index 85808d46626..937a3488016 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions5.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions5.ts @@ -10,4 +10,4 @@ //// let x = foo; //// foo(1)./**/ -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions8.ts b/tests/cases/fourslash/getJavaScriptCompletions8.ts index 6ac9387b10c..73673d878d3 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions8.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions8.ts @@ -8,4 +8,4 @@ ////var v; ////v()./**/ -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptCompletions9.ts b/tests/cases/fourslash/getJavaScriptCompletions9.ts index de9a9c068db..90500ed9d48 100644 --- a/tests/cases/fourslash/getJavaScriptCompletions9.ts +++ b/tests/cases/fourslash/getJavaScriptCompletions9.ts @@ -8,4 +8,4 @@ ////var v; ////new v()./**/ -verify.completions({ marker: "", includes: { name: "toExponential", kind: "method" } }); +verify.completions({ marker: "", includes: { name: "toExponential", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts index 9b047869896..76a4ea64a9b 100644 --- a/tests/cases/fourslash/getJavaScriptQuickInfo8.ts +++ b/tests/cases/fourslash/getJavaScriptQuickInfo8.ts @@ -21,9 +21,9 @@ goTo.marker('1'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.completions({ includes: { name: "substr", kind: "method" } }); +verify.completions({ includes: { name: "substr", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/importJsNodeModule1.ts b/tests/cases/fourslash/importJsNodeModule1.ts index e5177d19a88..c66a466781c 100644 --- a/tests/cases/fourslash/importJsNodeModule1.ts +++ b/tests/cases/fourslash/importJsNodeModule1.ts @@ -13,4 +13,4 @@ goTo.marker(); edit.insert('.'); verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/importJsNodeModule2.ts b/tests/cases/fourslash/importJsNodeModule2.ts index 34ed62814ad..0ceae59b215 100644 --- a/tests/cases/fourslash/importJsNodeModule2.ts +++ b/tests/cases/fourslash/importJsNodeModule2.ts @@ -23,4 +23,4 @@ verify.completions({ ], }); edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/importJsNodeModule3.ts b/tests/cases/fourslash/importJsNodeModule3.ts index 761a2ef3e45..4f3777724e1 100644 --- a/tests/cases/fourslash/importJsNodeModule3.ts +++ b/tests/cases/fourslash/importJsNodeModule3.ts @@ -26,11 +26,11 @@ goTo.marker(); edit.insert('.'); verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) });; edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); edit.backspace(4); edit.insert('y.'); -verify.completions({ includes: { name: "toUpperCase", kind: "method" } }); +verify.completions({ includes: { name: "toUpperCase", kind: "method", kindModifiers: "declare" } }); edit.backspace(2); edit.insert('z('); verify.signatureHelp({ diff --git a/tests/cases/fourslash/importJsNodeModule4.ts b/tests/cases/fourslash/importJsNodeModule4.ts index 08e9b936985..0358f682a0c 100644 --- a/tests/cases/fourslash/importJsNodeModule4.ts +++ b/tests/cases/fourslash/importJsNodeModule4.ts @@ -14,4 +14,4 @@ goTo.marker(); edit.insert('.'); verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) });; edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptClass4.ts b/tests/cases/fourslash/javaScriptClass4.ts index eae26f500cd..5b66c1e2909 100644 --- a/tests/cases/fourslash/javaScriptClass4.ts +++ b/tests/cases/fourslash/javaScriptClass4.ts @@ -18,4 +18,4 @@ goTo.marker(); edit.insert('.baz.'); -verify.completions({ includes: { name: "substr", kind: "method" } }); +verify.completions({ includes: { name: "substr", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptModules13.ts b/tests/cases/fourslash/javaScriptModules13.ts index 3f462f343ee..62987047862 100644 --- a/tests/cases/fourslash/javaScriptModules13.ts +++ b/tests/cases/fourslash/javaScriptModules13.ts @@ -24,4 +24,4 @@ verify.completions({ marker: "", includes: "y", excludes: "invisible" }); edit.insert('x.'); verify.completions({ includes: { name: "a", kind: "property" } }); edit.insert('a.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptModules15.ts b/tests/cases/fourslash/javaScriptModules15.ts index 7a000c53a2c..f81e6d090cf 100644 --- a/tests/cases/fourslash/javaScriptModules15.ts +++ b/tests/cases/fourslash/javaScriptModules15.ts @@ -22,4 +22,4 @@ goTo.marker(); edit.insert('.'); verify.completions({ includes: ["s", "b", "n"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptModules16.ts b/tests/cases/fourslash/javaScriptModules16.ts index 715e5d84da4..7c3bb31436d 100644 --- a/tests/cases/fourslash/javaScriptModules16.ts +++ b/tests/cases/fourslash/javaScriptModules16.ts @@ -22,4 +22,4 @@ verify.completions({ ], }); edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptModules17.ts b/tests/cases/fourslash/javaScriptModules17.ts index 02cddc4006f..09174c81579 100644 --- a/tests/cases/fourslash/javaScriptModules17.ts +++ b/tests/cases/fourslash/javaScriptModules17.ts @@ -13,4 +13,4 @@ goTo.marker(); edit.insert('.'); verify.completions({ includes: ["n", "s", "b"].map(name => ({ name, kind: "property" })) }); edit.insert('n.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptModules19.ts b/tests/cases/fourslash/javaScriptModules19.ts index 37304c4593a..1fe4ae3cfd1 100644 --- a/tests/cases/fourslash/javaScriptModules19.ts +++ b/tests/cases/fourslash/javaScriptModules19.ts @@ -22,4 +22,4 @@ verify.completions({ marker: "", includes: "y", excludes: "invisible" }); edit.insert('x.'); verify.completions({ includes: { name: "a", kind: "property" } }); edit.insert('a.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/javaScriptPrototype1.ts b/tests/cases/fourslash/javaScriptPrototype1.ts index e586b124e44..983af3fe9f8 100644 --- a/tests/cases/fourslash/javaScriptPrototype1.ts +++ b/tests/cases/fourslash/javaScriptPrototype1.ts @@ -28,7 +28,7 @@ edit.backspace(); // Members of a class method (1) goTo.marker('2'); edit.insert('.'); -verify.completions({ includes: { name: "length", kind: "property" } }); +verify.completions({ includes: { name: "length", kind: "property", kindModifiers: "declare" } }); edit.backspace(); // Members of the invocation of a class method (1) diff --git a/tests/cases/fourslash/javaScriptPrototype2.ts b/tests/cases/fourslash/javaScriptPrototype2.ts index 79169e47b0c..f8c2e56e1a9 100644 --- a/tests/cases/fourslash/javaScriptPrototype2.ts +++ b/tests/cases/fourslash/javaScriptPrototype2.ts @@ -26,7 +26,7 @@ edit.backspace(); // Verify the type of the instance property goTo.marker('2'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); goTo.marker('3'); edit.insert('.'); diff --git a/tests/cases/fourslash/jsDocFunctionSignatures3.ts b/tests/cases/fourslash/jsDocFunctionSignatures3.ts index c519a1dcc72..443c482e65e 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures3.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures3.ts @@ -23,10 +23,10 @@ goTo.marker('1'); edit.insert('.'); -verify.completions({ includes: { name: "substr", kind: "method" } }); +verify.completions({ includes: { name: "substr", kind: "method", kindModifiers: "declare" } }); edit.backspace(); goTo.marker('2'); edit.insert('.'); -verify.completions({ includes: { name: "toFixed", kind: "method" } }); +verify.completions({ includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); edit.backspace(); diff --git a/tests/cases/fourslash/jsDocGenerics1.ts b/tests/cases/fourslash/jsDocGenerics1.ts index 70e13851cf7..810d8fce664 100644 --- a/tests/cases/fourslash/jsDocGenerics1.ts +++ b/tests/cases/fourslash/jsDocGenerics1.ts @@ -23,4 +23,4 @@ //// var x; //// x[0].a./*3*/ -verify.completions({ marker: test.markers(), includes: { name: "toFixed", kind: "method" } }); +verify.completions({ marker: test.markers(), includes: { name: "toFixed", kind: "method", kindModifiers: "declare" } }); diff --git a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts index d3c4aafc938..a117bae1b11 100644 --- a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts +++ b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion.ts @@ -26,10 +26,10 @@ const values: ReadonlyArray = const typeMembers: ReadonlyArray = [ { name: "NumberLike", kind: "type" }, { name: "People", kind: "type" }, - { name: "O", kind: "module" }, + { name: "O", kind: "module", kindModifiers: "export" }, ]; function warnings(entries: ReadonlyArray): ReadonlyArray { - return entries.map(e => ({ ...e, kind: "warning" })); + return entries.map(e => ({ ...e, kind: "warning", kindModifiers: undefined })); } verify.completions( diff --git a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts index 0c939191808..efe73d9c023 100644 --- a/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts +++ b/tests/cases/fourslash/jsFileJsdocTypedefTagTypeExpressionCompletion3.ts @@ -44,7 +44,7 @@ verify.completions( { marker: "typeFooMember", exact: [ - { name: "Namespace", kind: "module" }, + { name: "Namespace", kind: "module", kindModifiers: "export" }, ...warnings(["Foo", "value", "property1", "method1", "method3", "method4", "foo", "age", "SomeType", "x", "x1"]), ], }, @@ -84,7 +84,7 @@ verify.completions( marker: "valueMemberOfFoo", exact: [ { name: "prototype", kind: "property" }, - { name: "method1", kind: "method" }, + { name: "method1", kind: "method", kindModifiers: "static" }, ...completion.functionMembers, ...warnings(["Foo", "value", "property1", "method3", "method4", "foo", "age", "Namespace", "SomeType", "x", "x1"]), ], diff --git a/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts b/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts index 21cea81e57b..7beeab84c57 100644 --- a/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts +++ b/tests/cases/fourslash/jsdocTypedefTagTypeExpressionCompletion.ts @@ -41,11 +41,11 @@ verify.completions( }, { marker: "typeFooMember", - exact: { name: "Namespace", kind: "module" }, + exact: { name: "Namespace", kind: "module", kindModifiers: "export" }, }, { marker: "NamespaceMember", - exact: { name: "SomeType", kind: "interface" }, + exact: { name: "SomeType", kind: "interface", kindModifiers: "export" }, }, { marker: "globalValue", @@ -71,7 +71,7 @@ verify.completions( marker: "valueMemberOfFoo", exact: [ "prototype", - { name: "method1", kind: "method" }, + { name: "method1", kind: "method", kindModifiers: "static" }, ...completion.functionMembers, ], }, diff --git a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts index 681ea8f04d7..71ed84d7768 100644 --- a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts +++ b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts @@ -23,6 +23,7 @@ verify.completions({ sourceDisplay: "./node_modules/foo/index", text: "const fail: number", kind: "const", + kindModifiers: "export,declare", hasAction: true, }, preferences: { includeCompletionsForModuleExports: true }, From 0481d44501c4335706f8fa423049ea15e499ca89 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 30 Oct 2018 13:25:24 -0700 Subject: [PATCH 157/262] Bad callsite inferences fall back to body usage (#28235) For parameters, the infer-from-usage codefix uses a substantially different codepath that previously only looked at call site uses. When this resulted in no inferences, or bad inferences, for a single parameter, the codefix would just use any. Only if no usages of a function were found would the codefix use the body-inference code. This commit makes parameter inference fall back to body-inference code for individual parameters when there is no inference or inference to any. --- src/services/codefixes/inferFromUsage.ts | 15 ++++++++++----- .../codeFixInferFromUsageCallBodyPriority.ts | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageCallBodyPriority.ts diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 834228f7884..12a0aeff730 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -349,7 +349,7 @@ namespace ts.codefix { findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile) : containingFunction.name; if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program.getTypeChecker(), cancellationToken); + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); } } } @@ -387,7 +387,8 @@ namespace ts.codefix { return getTypeFromUsageContext(usageContext, checker) || checker.getAnyType(); } - export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, checker: TypeChecker, cancellationToken: CancellationToken): ParameterInference[] | undefined { + export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + const checker = program.getTypeChecker(); if (references.length === 0) { return undefined; } @@ -422,10 +423,14 @@ namespace ts.codefix { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); } } - if (!types.length) { - return { declaration: parameter, type: checker.getAnyType() }; + + let type = types.length && checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); + if ((!type || type.flags & TypeFlags.Any) && isIdentifier(parameter.name)) { + type = inferTypeForVariableFromUsage(parameter.name, program, cancellationToken); + } + if (!type) { + type = checker.getAnyType(); } - const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, diff --git a/tests/cases/fourslash/codeFixInferFromUsageCallBodyPriority.ts b/tests/cases/fourslash/codeFixInferFromUsageCallBodyPriority.ts new file mode 100644 index 00000000000..1603d35d742 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageCallBodyPriority.ts @@ -0,0 +1,18 @@ +/// +// based on acorn + +////function isIdentifierStart([|code, astral |]) { +//// if (code < 65) { return code === 36 } +//// if (code < 91) { return true } +//// if (code < 97) { return code === 95 } +//// if (code < 123) { return true } +//// if (code <= 0xffff) { return code >= 0xaa } +//// if (astral === false) { return false } +////} +//// +////function isLet(nextCh: any) { +//// return isIdentifierStart(nextCh, true) +////}; + + +verify.rangeAfterCodeFix("code: number, astral: boolean",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); From 4cfff8962c3609049c4488d3f64e204e5944fbf4 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 30 Oct 2018 14:55:01 -0700 Subject: [PATCH 158/262] Fix declaration emit for cross-file enums (#28237) --- src/compiler/checker.ts | 16 ++--- ...clarationEmitQualifiedAliasTypeArgument.js | 40 ++++++++++++ ...tionEmitQualifiedAliasTypeArgument.symbols | 62 +++++++++++++++++++ ...rationEmitQualifiedAliasTypeArgument.types | 50 +++++++++++++++ ...clarationEmitQualifiedAliasTypeArgument.ts | 26 ++++++++ tests/cases/user/prettier/prettier | 2 +- 6 files changed, 188 insertions(+), 8 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.js create mode 100644 tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.symbols create mode 100644 tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.types create mode 100644 tests/cases/compiler/declarationEmitQualifiedAliasTypeArgument.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f23e26f51fc..154e6ea9b27 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3222,15 +3222,17 @@ namespace ts { } if (type.flags & TypeFlags.EnumLiteral && !(type.flags & TypeFlags.Union)) { const parentSymbol = getParentOfSymbol(type.symbol)!; - const parentName = symbolToName(parentSymbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); - const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : createQualifiedName(parentName, symbolName(type.symbol)); - context.approximateLength += symbolName(type.symbol).length; - return createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); + const parentName = symbolToTypeNode(parentSymbol, context, SymbolFlags.Type); + const enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type + ? parentName + : appendReferenceToType( + parentName as TypeReferenceNode | ImportTypeNode, + createTypeReferenceNode(symbolName(type.symbol), /*typeArguments*/ undefined) + ); + return enumLiteralName; } if (type.flags & TypeFlags.EnumLike) { - const name = symbolToName(type.symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false); - context.approximateLength += symbolName(type.symbol).length; - return createTypeReferenceNode(name, /*typeArguments*/ undefined); + return symbolToTypeNode(type.symbol, context, SymbolFlags.Type); } if (type.flags & TypeFlags.StringLiteral) { context.approximateLength += ((type).value.length + 2); diff --git a/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.js b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.js new file mode 100644 index 00000000000..bc895b62ace --- /dev/null +++ b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.js @@ -0,0 +1,40 @@ +//// [tests/cases/compiler/declarationEmitQualifiedAliasTypeArgument.ts] //// + +//// [bbb.d.ts] +export interface INode { + data: T; +} + +export function create(): () => INode; +//// [lib.d.ts] +export type G = { [P in T]: string }; + +export enum E { + A = "a", + B = "b" +} + +export type T = G; + +export type Q = G; + +//// [index.ts] +import { T, Q } from "./lib"; +import { create } from "./bbb"; + +export const fun = create(); + +export const fun2 = create(); + + +//// [index.js] +"use strict"; +exports.__esModule = true; +var bbb_1 = require("./bbb"); +exports.fun = bbb_1.create(); +exports.fun2 = bbb_1.create(); + + +//// [index.d.ts] +export declare const fun: () => import("./bbb").INode>; +export declare const fun2: () => import("./bbb").INode>; diff --git a/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.symbols b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.symbols new file mode 100644 index 00000000000..a6debc526ea --- /dev/null +++ b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.symbols @@ -0,0 +1,62 @@ +=== tests/cases/compiler/bbb.d.ts === +export interface INode { +>INode : Symbol(INode, Decl(bbb.d.ts, 0, 0)) +>T : Symbol(T, Decl(bbb.d.ts, 0, 23)) + + data: T; +>data : Symbol(INode.data, Decl(bbb.d.ts, 0, 27)) +>T : Symbol(T, Decl(bbb.d.ts, 0, 23)) +} + +export function create(): () => INode; +>create : Symbol(create, Decl(bbb.d.ts, 2, 1)) +>T : Symbol(T, Decl(bbb.d.ts, 4, 23)) +>INode : Symbol(INode, Decl(bbb.d.ts, 0, 0)) +>T : Symbol(T, Decl(bbb.d.ts, 4, 23)) + +=== tests/cases/compiler/lib.d.ts === +export type G = { [P in T]: string }; +>G : Symbol(G, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(lib.d.ts, --, --)) +>P : Symbol(P, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(lib.d.ts, --, --)) + +export enum E { +>E : Symbol(E, Decl(lib.d.ts, --, --)) + + A = "a", +>A : Symbol(E.A, Decl(lib.d.ts, --, --)) + + B = "b" +>B : Symbol(E.B, Decl(lib.d.ts, --, --)) +} + +export type T = G; +>T : Symbol(T, Decl(lib.d.ts, --, --)) +>G : Symbol(G, Decl(lib.d.ts, --, --)) +>E : Symbol(E, Decl(lib.d.ts, --, --)) + +export type Q = G; +>Q : Symbol(Q, Decl(lib.d.ts, --, --)) +>G : Symbol(G, Decl(lib.d.ts, --, --)) +>E : Symbol(E, Decl(lib.d.ts, --, --)) +>A : Symbol(E.A, Decl(lib.d.ts, --, --)) + +=== tests/cases/compiler/index.ts === +import { T, Q } from "./lib"; +>T : Symbol(T, Decl(index.ts, 0, 8)) +>Q : Symbol(Q, Decl(index.ts, 0, 11)) + +import { create } from "./bbb"; +>create : Symbol(create, Decl(index.ts, 1, 8)) + +export const fun = create(); +>fun : Symbol(fun, Decl(index.ts, 3, 12)) +>create : Symbol(create, Decl(index.ts, 1, 8)) +>T : Symbol(T, Decl(index.ts, 0, 8)) + +export const fun2 = create(); +>fun2 : Symbol(fun2, Decl(index.ts, 5, 12)) +>create : Symbol(create, Decl(index.ts, 1, 8)) +>Q : Symbol(Q, Decl(index.ts, 0, 11)) + diff --git a/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.types b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.types new file mode 100644 index 00000000000..e660e7d0bb9 --- /dev/null +++ b/tests/baselines/reference/declarationEmitQualifiedAliasTypeArgument.types @@ -0,0 +1,50 @@ +=== tests/cases/compiler/bbb.d.ts === +export interface INode { + data: T; +>data : T +} + +export function create(): () => INode; +>create : () => () => INode + +=== tests/cases/compiler/lib.d.ts === +export type G = { [P in T]: string }; +>G : G + +export enum E { +>E : E + + A = "a", +>A : E.A +>"a" : "a" + + B = "b" +>B : E.B +>"b" : "b" +} + +export type T = G; +>T : G + +export type Q = G; +>Q : G +>E : any + +=== tests/cases/compiler/index.ts === +import { T, Q } from "./lib"; +>T : any +>Q : any + +import { create } from "./bbb"; +>create : () => () => import("tests/cases/compiler/bbb").INode + +export const fun = create(); +>fun : () => import("tests/cases/compiler/bbb").INode> +>create() : () => import("tests/cases/compiler/bbb").INode> +>create : () => () => import("tests/cases/compiler/bbb").INode + +export const fun2 = create(); +>fun2 : () => import("tests/cases/compiler/bbb").INode> +>create() : () => import("tests/cases/compiler/bbb").INode> +>create : () => () => import("tests/cases/compiler/bbb").INode + diff --git a/tests/cases/compiler/declarationEmitQualifiedAliasTypeArgument.ts b/tests/cases/compiler/declarationEmitQualifiedAliasTypeArgument.ts new file mode 100644 index 00000000000..0a3c346a430 --- /dev/null +++ b/tests/cases/compiler/declarationEmitQualifiedAliasTypeArgument.ts @@ -0,0 +1,26 @@ +// @declaration: true +// @filename: bbb.d.ts +export interface INode { + data: T; +} + +export function create(): () => INode; +// @filename: lib.d.ts +export type G = { [P in T]: string }; + +export enum E { + A = "a", + B = "b" +} + +export type T = G; + +export type Q = G; + +// @filename: index.ts +import { T, Q } from "./lib"; +import { create } from "./bbb"; + +export const fun = create(); + +export const fun2 = create(); diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 2402a2a07b4..67f1c4877ee 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 2402a2a07b434411dbc8a529b41d0d1d41befca5 +Subproject commit 67f1c4877ee1090b66d468a847caccca411a6f82 From e2436f331ad3f78a5052367bf0e3fa020721618a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 30 Oct 2018 14:55:30 -0700 Subject: [PATCH 159/262] Use constraint for default default value if possible (#28222) --- src/compiler/checker.ts | 2 +- ...tUsesConstraintOnCircularDefault.errors.txt | 18 ++++++++++++++++++ ...ntDefaultUsesConstraintOnCircularDefault.js | 11 +++++++++++ ...aultUsesConstraintOnCircularDefault.symbols | 18 ++++++++++++++++++ ...efaultUsesConstraintOnCircularDefault.types | 17 +++++++++++++++++ ...ntDefaultUsesConstraintOnCircularDefault.ts | 5 +++++ 6 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.errors.txt create mode 100644 tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.js create mode 100644 tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.symbols create mode 100644 tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.types create mode 100644 tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 154e6ea9b27..0a6cec7f6cb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7653,7 +7653,7 @@ namespace ts { // If a type parameter does not have a default type, or if the default type // is a forward reference, the empty object type is used. for (let i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + result[i] = getConstraintFromTypeParameter(typeParameters![i]) || getDefaultTypeArgumentType(isJavaScriptImplicitAny); } for (let i = numTypeArguments; i < numTypeParameters; i++) { const mapper = createTypeMapper(typeParameters!, result); diff --git a/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.errors.txt b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.errors.txt new file mode 100644 index 00000000000..71e3ef04627 --- /dev/null +++ b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts(3,18): error TS2322: Type '{ foo: string; }' is not assignable to type 'Test'. + Object literal may only specify known properties, and 'foo' does not exist in type 'Test'. +tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts(5,19): error TS2322: Type '{}' is not assignable to type 'string'. + + +==== tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts (2 errors) ==== + type Test = { value: T }; + + let zz: Test = { foo: "abc" }; // should error on comparison with Test + ~~~~~~~~~~ +!!! error TS2322: Type '{ foo: string; }' is not assignable to type 'Test'. +!!! error TS2322: Object literal may only specify known properties, and 'foo' does not exist in type 'Test'. + + let zzy: Test = { value: {} }; // should error + ~~~~~ +!!! error TS2322: Type '{}' is not assignable to type 'string'. +!!! related TS6500 tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts:1:37: The expected type comes from property 'value' which is declared here on type 'Test' + \ No newline at end of file diff --git a/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.js b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.js new file mode 100644 index 00000000000..296a0063fe2 --- /dev/null +++ b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.js @@ -0,0 +1,11 @@ +//// [typeArgumentDefaultUsesConstraintOnCircularDefault.ts] +type Test = { value: T }; + +let zz: Test = { foo: "abc" }; // should error on comparison with Test + +let zzy: Test = { value: {} }; // should error + + +//// [typeArgumentDefaultUsesConstraintOnCircularDefault.js] +var zz = { foo: "abc" }; // should error on comparison with Test +var zzy = { value: {} }; // should error diff --git a/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.symbols b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.symbols new file mode 100644 index 00000000000..2181e341889 --- /dev/null +++ b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts === +type Test = { value: T }; +>Test : Symbol(Test, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 0)) +>T : Symbol(T, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 10)) +>T : Symbol(T, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 10)) +>value : Symbol(value, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 35)) +>T : Symbol(T, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 10)) + +let zz: Test = { foo: "abc" }; // should error on comparison with Test +>zz : Symbol(zz, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 2, 3)) +>Test : Symbol(Test, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 0)) +>foo : Symbol(foo, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 2, 16)) + +let zzy: Test = { value: {} }; // should error +>zzy : Symbol(zzy, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 4, 3)) +>Test : Symbol(Test, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 0, 0)) +>value : Symbol(value, Decl(typeArgumentDefaultUsesConstraintOnCircularDefault.ts, 4, 17)) + diff --git a/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.types b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.types new file mode 100644 index 00000000000..7c0d469da46 --- /dev/null +++ b/tests/baselines/reference/typeArgumentDefaultUsesConstraintOnCircularDefault.types @@ -0,0 +1,17 @@ +=== tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts === +type Test = { value: T }; +>Test : Test +>value : T + +let zz: Test = { foo: "abc" }; // should error on comparison with Test +>zz : Test +>{ foo: "abc" } : { foo: string; } +>foo : string +>"abc" : "abc" + +let zzy: Test = { value: {} }; // should error +>zzy : Test +>{ value: {} } : { value: {}; } +>value : {} +>{} : {} + diff --git a/tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts b/tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts new file mode 100644 index 00000000000..b8361ea5714 --- /dev/null +++ b/tests/cases/compiler/typeArgumentDefaultUsesConstraintOnCircularDefault.ts @@ -0,0 +1,5 @@ +type Test = { value: T }; + +let zz: Test = { foo: "abc" }; // should error on comparison with Test + +let zzy: Test = { value: {} }; // should error From 65ba8d9fce1751d214bb4b389ee13b7a86793156 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 30 Oct 2018 14:55:52 -0700 Subject: [PATCH 160/262] Accept baseline with correct additional span location (#28238) --- tests/baselines/reference/exportAsNamespace_augment.errors.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/baselines/reference/exportAsNamespace_augment.errors.txt b/tests/baselines/reference/exportAsNamespace_augment.errors.txt index 76cb643d62a..ba1b4d80c6d 100644 --- a/tests/baselines/reference/exportAsNamespace_augment.errors.txt +++ b/tests/baselines/reference/exportAsNamespace_augment.errors.txt @@ -14,7 +14,7 @@ ~~~~~~~~ !!! error TS2451: Cannot redeclare block-scoped variable 'conflict'. !!! related TS6203 /b.ts:6:22: 'conflict' was also declared here. -!!! related TS6204 /b.ts:6:22: and here. +!!! related TS6204 /b.ts:12:18: and here. ==== /b.ts (6 errors) ==== import * as a2 from "./a"; From 60801a261c35a32738dbdd188818710bacdcf40c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 30 Oct 2018 15:22:00 -0700 Subject: [PATCH 161/262] Report error requiring references to have composite only if the program is not container only --- src/compiler/program.ts | 6 ++- src/harness/virtualFileSystemWithWatch.ts | 12 +++++ src/testRunner/unittests/tsbuildWatchMode.ts | 19 ++----- .../unittests/tsserverProjectSystem.ts | 49 +++++++++++++++++++ .../projects/container/compositeExec/index.ts | 5 ++ .../container/compositeExec/tsconfig.json | 12 +++++ tests/projects/container/exec/index.ts | 5 ++ tests/projects/container/exec/tsconfig.json | 11 +++++ tests/projects/container/lib/index.ts | 3 ++ tests/projects/container/lib/tsconfig.json | 11 +++++ tests/projects/container/tsconfig.json | 8 +++ 11 files changed, 125 insertions(+), 16 deletions(-) create mode 100644 tests/projects/container/compositeExec/index.ts create mode 100644 tests/projects/container/compositeExec/tsconfig.json create mode 100644 tests/projects/container/exec/index.ts create mode 100644 tests/projects/container/exec/tsconfig.json create mode 100644 tests/projects/container/lib/index.ts create mode 100644 tests/projects/container/lib/tsconfig.json create mode 100644 tests/projects/container/tsconfig.json diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 997bdaa80c7..e2f743818f2 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2806,7 +2806,11 @@ namespace ts { } const options = resolvedRef.commandLine.options; if (!options.composite) { - createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + // ok to not have composite if the current program is container only + const inputs = parent ? parent.commandLine.fileNames : rootNames; + if (inputs.length) { + createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } } if (ref.prepend) { const out = options.outFile || options.out; diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index bd31a04a0df..0ec3b8431e9 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -988,4 +988,16 @@ interface Array {}` return this.environmentVariables && this.environmentVariables.get(name) || ""; } } + + export const tsbuildProjectsLocation = "/user/username/projects"; + export function getTsBuildProjectFilePath(project: string, file: string) { + return `${tsbuildProjectsLocation}/${project}/${file}`; + } + + export function getTsBuildProjectFile(project: string, file: string): File { + return { + path: getTsBuildProjectFilePath(project, file), + content: Harness.IO.readFile(`${Harness.IO.getWorkspaceRoot()}/tests/projects/${project}/${file}`)! + }; + } } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 3461cfdb785..9178416373c 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -1,6 +1,9 @@ namespace ts.tscWatch { export import libFile = TestFSWithWatch.libFile; - function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation; + import getFilePathInProject = TestFSWithWatch.getTsBuildProjectFilePath; + import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile; + export function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { const host = createSolutionBuilderWithWatchHost(system); return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true }); } @@ -13,7 +16,6 @@ namespace ts.tscWatch { } describe("tsbuild-watch program updates", () => { - const projectsLocation = "/user/username/projects"; const project = "sample1"; const enum SubProject { core = "core", @@ -24,23 +26,10 @@ namespace ts.tscWatch { type ReadonlyFile = Readonly; /** [tsconfig, index] | [tsconfig, index, anotherModule, someDecl] */ type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; - const root = Harness.IO.getWorkspaceRoot(); - function getProjectPath(project: string) { return `${projectsLocation}/${project}`; } - function getFilePathInProject(project: string, file: string) { - return `${projectsLocation}/${project}/${file}`; - } - - function getFileFromProject(project: string, file: string): File { - return { - path: getFilePathInProject(project, file), - content: Harness.IO.readFile(`${root}/tests/projects/${project}/${file}`)! - }; - } - function projectPath(subProject: SubProject) { return getFilePathInProject(project, subProject); } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 3ffd28702a2..b4a412d24e3 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10427,6 +10427,55 @@ declare class TestLib { }); }); + describe("tsserverProjectSystem with tsbuild projects", () => { + function getProjectFiles(project: string): [File, File] { + return [ + TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile(project, "index.ts"), + ]; + } + it("does not error on container only project", () => { + const project = "container"; + const containerLib = getProjectFiles("container/lib"); + const containerExec = getProjectFiles("container/exec"); + const containerCompositeExec = getProjectFiles("container/compositeExec"); + const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); + const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; + const host = createServerHost(files); + + // ts build should succeed + const solutionBuilder = tscWatch.createSolutionBuilder(host, [containerConfig.path], {}); + solutionBuilder.buildAllProjects(); + assert.equal(host.getOutput().length, 0); + + // Open external project for the folder + const session = createSession(host); + const service = session.getProjectService(); + service.openExternalProjects([{ + projectFileName: TestFSWithWatch.getTsBuildProjectFilePath(project, project), + rootFiles: files.map(f => ({ fileName: f.path })), + options: {} + }]); + checkNumberOfProjects(service, { configuredProjects: 4 }); + files.forEach(f => { + const args: protocol.FileRequestArgs = { + file: f.path, + projectFileName: endsWith(f.path, "tsconfig.json") ? f.path : undefined + }; + const syntaxDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SyntacticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(syntaxDiagnostics, []); + const semanticDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SemanticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(semanticDiagnostics, []); + }); + }); + }); + describe("tsserverProjectSystem duplicate packages", () => { // Tests that 'moduleSpecifiers.ts' will import from the redirecting file, and not from the file it redirects to, if that can provide a global module specifier. it("works with import fixes", () => { diff --git a/tests/projects/container/compositeExec/index.ts b/tests/projects/container/compositeExec/index.ts new file mode 100644 index 00000000000..4d3216676fb --- /dev/null +++ b/tests/projects/container/compositeExec/index.ts @@ -0,0 +1,5 @@ +namespace container { + export function getMyConst() { + return myConst; + } +} \ No newline at end of file diff --git a/tests/projects/container/compositeExec/tsconfig.json b/tests/projects/container/compositeExec/tsconfig.json new file mode 100644 index 00000000000..f28a9e44eee --- /dev/null +++ b/tests/projects/container/compositeExec/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "outFile": "../built/local/compositeExec.js", + "composite": true + }, + "files": [ + "index.ts" + ], + "references": [ + { "path": "../lib", "prepend": true } + ] +} \ No newline at end of file diff --git a/tests/projects/container/exec/index.ts b/tests/projects/container/exec/index.ts new file mode 100644 index 00000000000..4d3216676fb --- /dev/null +++ b/tests/projects/container/exec/index.ts @@ -0,0 +1,5 @@ +namespace container { + export function getMyConst() { + return myConst; + } +} \ No newline at end of file diff --git a/tests/projects/container/exec/tsconfig.json b/tests/projects/container/exec/tsconfig.json new file mode 100644 index 00000000000..1a3a4c9edd1 --- /dev/null +++ b/tests/projects/container/exec/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outFile": "../built/local/exec.js" + }, + "files": [ + "index.ts" + ], + "references": [ + { "path": "../lib", "prepend": true } + ] +} \ No newline at end of file diff --git a/tests/projects/container/lib/index.ts b/tests/projects/container/lib/index.ts new file mode 100644 index 00000000000..c89a3a3d289 --- /dev/null +++ b/tests/projects/container/lib/index.ts @@ -0,0 +1,3 @@ +namespace container { + export const myConst = 30; +} \ No newline at end of file diff --git a/tests/projects/container/lib/tsconfig.json b/tests/projects/container/lib/tsconfig.json new file mode 100644 index 00000000000..15766e83721 --- /dev/null +++ b/tests/projects/container/lib/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outFile": "../built/local/lib.js", + "composite": true, + "declarationMap": true + }, + "references": [], + "files": [ + "index.ts" + ] +} \ No newline at end of file diff --git a/tests/projects/container/tsconfig.json b/tests/projects/container/tsconfig.json new file mode 100644 index 00000000000..854c4029fd9 --- /dev/null +++ b/tests/projects/container/tsconfig.json @@ -0,0 +1,8 @@ +{ + "files": [], + "include": [], + "references": [ + { "path": "./exec" }, + { "path": "./compositeExec" } + ] +} \ No newline at end of file From 9d5e8fe89f0063a0eb70034c3314f6e903003e4e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 16:00:05 -0700 Subject: [PATCH 162/262] Continue to error on rest from generic source type --- 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 2a27a7a7e8a..23cb632b2b1 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4637,7 +4637,7 @@ namespace ts { let type: Type | undefined; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { if (declaration.dotDotDotToken) { - if (parentType.flags & TypeFlags.Unknown || !isValidSpreadType(parentType)) { + if (parentType.flags & TypeFlags.Unknown || !isValidSpreadType(parentType) || isGenericObjectType(parentType)) { error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; } From 3c3633995535e59b471ec423ed782b8c746c0498 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 16:00:14 -0700 Subject: [PATCH 163/262] Accept new baselines --- .../reference/objectRestNegative.errors.txt | 5 ++++- .../reference/objectRestNegative.types | 6 +++--- .../restInvalidArgumentType.errors.txt | 20 ++++++++++++++++++- .../reference/restInvalidArgumentType.types | 12 +++++------ 4 files changed, 32 insertions(+), 11 deletions(-) diff --git a/tests/baselines/reference/objectRestNegative.errors.txt b/tests/baselines/reference/objectRestNegative.errors.txt index 42b25d137ef..fef99187d55 100644 --- a/tests/baselines/reference/objectRestNegative.errors.txt +++ b/tests/baselines/reference/objectRestNegative.errors.txt @@ -5,10 +5,11 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Ty tests/cases/conformance/types/rest/objectRestNegative.ts(9,31): error TS2462: A rest element must be last in a destructuring pattern. tests/cases/conformance/types/rest/objectRestNegative.ts(11,30): error TS7008: Member 'x' implicitly has an 'any' type. tests/cases/conformance/types/rest/objectRestNegative.ts(11,33): error TS7008: Member 'y' implicitly has an 'any' type. +tests/cases/conformance/types/rest/objectRestNegative.ts(12,17): error TS2700: Rest types may only be created from object types. tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: The target of an object rest assignment must be a variable or a property access. -==== tests/cases/conformance/types/rest/objectRestNegative.ts (6 errors) ==== +==== tests/cases/conformance/types/rest/objectRestNegative.ts (7 errors) ==== let o = { a: 1, b: 'no' }; var { ...mustBeLast, a } = o; ~~~~~~~~~~ @@ -33,6 +34,8 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: Th ~ !!! error TS7008: Member 'y' implicitly has an 'any' type. let { x, ...rest } = t; + ~~~~ +!!! error TS2700: Rest types may only be created from object types. return rest; } diff --git a/tests/baselines/reference/objectRestNegative.types b/tests/baselines/reference/objectRestNegative.types index f032dbe7d5b..dff6388d609 100644 --- a/tests/baselines/reference/objectRestNegative.types +++ b/tests/baselines/reference/objectRestNegative.types @@ -36,18 +36,18 @@ function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { >b : string } function generic(t: T) { ->generic : (t: T) => { y: any; } +>generic : (t: T) => any >x : any >y : any >t : T let { x, ...rest } = t; >x : any ->rest : { y: any; } +>rest : any >t : T return rest; ->rest : { y: any; } +>rest : any } let rest: { b: string } diff --git a/tests/baselines/reference/restInvalidArgumentType.errors.txt b/tests/baselines/reference/restInvalidArgumentType.errors.txt index 7e0c852316a..0cc4faea557 100644 --- a/tests/baselines/reference/restInvalidArgumentType.errors.txt +++ b/tests/baselines/reference/restInvalidArgumentType.errors.txt @@ -1,5 +1,11 @@ +tests/cases/compiler/restInvalidArgumentType.ts(27,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(29,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(30,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(31,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(33,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(36,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(37,13): error TS2700: Rest types may only be created from object types. +tests/cases/compiler/restInvalidArgumentType.ts(39,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(40,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(42,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(43,13): error TS2700: Rest types may only be created from object types. @@ -10,7 +16,7 @@ tests/cases/compiler/restInvalidArgumentType.ts(51,13): error TS2700: Rest types tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types may only be created from object types. -==== tests/cases/compiler/restInvalidArgumentType.ts (10 errors) ==== +==== tests/cases/compiler/restInvalidArgumentType.ts (16 errors) ==== enum E { v1, v2 }; function f(p1: T, p2: T[]) { @@ -38,22 +44,34 @@ tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types var a: any; var {...r1} = p1; // Error, generic type paramterre + ~~ +!!! error TS2700: Rest types may only be created from object types. var {...r2} = p2; // OK var {...r3} = t; // Error, generic type paramter + ~~ +!!! error TS2700: Rest types may only be created from object types. var {...r4} = i; // Error, index access + ~~ +!!! error TS2700: Rest types may only be created from object types. var {...r5} = k; // Error, index ~~ !!! error TS2700: Rest types may only be created from object types. var {...r6} = mapped_generic; // Error, generic mapped object type + ~~ +!!! error TS2700: Rest types may only be created from object types. var {...r7} = mapped; // OK, non-generic mapped type var {...r8} = union_generic; // Error, union with generic type parameter + ~~ +!!! error TS2700: Rest types may only be created from object types. var {...r9} = union_primitive; // Error, union with generic type parameter ~~ !!! error TS2700: Rest types may only be created from object types. var {...r10} = intersection_generic; // Error, intersection with generic type parameter + ~~~ +!!! error TS2700: Rest types may only be created from object types. var {...r11} = intersection_primitive; // Error, intersection with generic type parameter ~~~ !!! error TS2700: Rest types may only be created from object types. diff --git a/tests/baselines/reference/restInvalidArgumentType.types b/tests/baselines/reference/restInvalidArgumentType.types index cd598247193..ce59fb145f9 100644 --- a/tests/baselines/reference/restInvalidArgumentType.types +++ b/tests/baselines/reference/restInvalidArgumentType.types @@ -67,7 +67,7 @@ function f(p1: T, p2: T[]) { >a : any var {...r1} = p1; // Error, generic type paramterre ->r1 : { b: string; } +>r1 : any >p1 : T var {...r2} = p2; // OK @@ -75,11 +75,11 @@ function f(p1: T, p2: T[]) { >p2 : T[] var {...r3} = t; // Error, generic type paramter ->r3 : { b: string; } +>r3 : any >t : T var {...r4} = i; // Error, index access ->r4 : { readonly [index: number]: string; toString(): string; charAt(pos: number): string; charCodeAt(index: number): number; concat(...strings: string[]): string; indexOf(searchString: string, position?: number): number; lastIndexOf(searchString: string, position?: number): number; localeCompare(that: string): number; localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number; match(regexp: string | RegExp): RegExpMatchArray; replace(searchValue: string | RegExp, replaceValue: string): string; replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; search(regexp: string | RegExp): number; slice(start?: number, end?: number): string; split(separator: string | RegExp, limit?: number): string[]; substring(start: number, end?: number): string; toLowerCase(): string; toLocaleLowerCase(): string; toUpperCase(): string; toLocaleUpperCase(): string; trim(): string; length: number; substr(from: number, length?: number): string; valueOf(): string; } +>r4 : any >i : T["b"] var {...r5} = k; // Error, index @@ -87,7 +87,7 @@ function f(p1: T, p2: T[]) { >k : keyof T var {...r6} = mapped_generic; // Error, generic mapped object type ->r6 : { b: T["b"]; } +>r6 : any >mapped_generic : { [P in keyof T]: T[P]; } var {...r7} = mapped; // OK, non-generic mapped type @@ -95,7 +95,7 @@ function f(p1: T, p2: T[]) { >mapped : { b: T["b"]; } var {...r8} = union_generic; // Error, union with generic type parameter ->r8 : { b: string; } | { a: number; } +>r8 : any >union_generic : T | { a: number; } var {...r9} = union_primitive; // Error, union with generic type parameter @@ -103,7 +103,7 @@ function f(p1: T, p2: T[]) { >union_primitive : number | { a: number; } var {...r10} = intersection_generic; // Error, intersection with generic type parameter ->r10 : { b: string; a: number; } +>r10 : any >intersection_generic : T & { a: number; } var {...r11} = intersection_primitive; // Error, intersection with generic type parameter From 2ed627aaf12b3270c4e21fa8db4d92058c545625 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 16:33:14 -0700 Subject: [PATCH 164/262] Update tests --- .../cases/compiler/spreadInvalidArgumentType.ts | 14 +++++++------- .../conformance/types/spread/objectSpread.ts | 14 ++++++++++++++ .../types/spread/objectSpreadNegative.ts | 16 ---------------- 3 files changed, 21 insertions(+), 23 deletions(-) diff --git a/tests/cases/compiler/spreadInvalidArgumentType.ts b/tests/cases/compiler/spreadInvalidArgumentType.ts index f18e73b31ef..d75d606cc73 100644 --- a/tests/cases/compiler/spreadInvalidArgumentType.ts +++ b/tests/cases/compiler/spreadInvalidArgumentType.ts @@ -27,18 +27,18 @@ function f(p1: T, p2: T[]) { var e: E; - var o1 = { ...p1 }; // Error, generic type paramterre - var o2 = { ...p2 }; // OK - var o3 = { ...t }; // Error, generic type paramter - var o4 = { ...i }; // Error, index access + var o1 = { ...p1 }; // OK, generic type paramterre + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // OK, generic type paramter + var o4 = { ...i }; // OK, index access var o5 = { ...k }; // Error, index - var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o6 = { ...mapped_generic }; // OK, generic mapped object type var o7 = { ...mapped }; // OK, non-generic mapped type - var o8 = { ...union_generic }; // Error, union with generic type parameter + var o8 = { ...union_generic }; // OK, union with generic type parameter var o9 = { ...union_primitive }; // Error, union with generic type parameter - var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o10 = { ...intersection_generic }; // OK, intersection with generic type parameter var o11 = { ...intersection_primitive }; // Error, intersection with generic type parameter var o12 = { ...num }; // Error diff --git a/tests/cases/conformance/types/spread/objectSpread.ts b/tests/cases/conformance/types/spread/objectSpread.ts index 810a8f3d496..5917bdf6dcf 100644 --- a/tests/cases/conformance/types/spread/objectSpread.ts +++ b/tests/cases/conformance/types/spread/objectSpread.ts @@ -122,6 +122,20 @@ let shortCutted: { a: number, b: string } = { ...o, a } let spreadNonPrimitive = { ...{}}; // generic spreads + +function f(t: T, u: U) { + return { ...t, ...u, id: 'id' }; +} + +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +let overlap: { id: string, a: number, b: string } = + f({ a: 1 }, { a: 2, b: 'extra' }) +let overlapConflict: { id:string, a: string } = + f({ a: 1 }, { a: 'mismatch' }) +let overwriteId: { id: string, a: number, c: number, d: string } = + f({ a: 1, id: true }, { c: 1, d: 'no' }) + function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { let x01 = { ...t }; let x02 = { ...t, ...t }; diff --git a/tests/cases/conformance/types/spread/objectSpreadNegative.ts b/tests/cases/conformance/types/spread/objectSpreadNegative.ts index 789016762da..f31d62e2faf 100644 --- a/tests/cases/conformance/types/spread/objectSpreadNegative.ts +++ b/tests/cases/conformance/types/spread/objectSpreadNegative.ts @@ -57,19 +57,3 @@ spreadC.m(); // error 'm' is not in '{ ... c }' let obj: object = { a: 123 }; let spreadObj = { ...obj }; spreadObj.a; // error 'a' is not in {} - -// generics -function f(t: T, u: U) { - return { ...t, ...u, id: 'id' }; -} -function override(initial: U, override: U): U { - return { ...initial, ...override }; -} -let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = - f({ a: 1, b: 'yes' }, { c: 'no', d: false }) -let overlap: { id: string, a: number, b: string } = - f({ a: 1 }, { a: 2, b: 'extra' }) -let overlapConflict: { id:string, a: string } = - f({ a: 1 }, { a: 'mismatch' }) -let overwriteId: { id: string, a: number, c: number, d: string } = - f({ a: 1, id: true }, { c: 1, d: 'no' }) From 1577f9429dafc3191e48d7c37d62a8c413baa425 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 30 Oct 2018 16:33:26 -0700 Subject: [PATCH 165/262] Accept new baselines --- tests/baselines/reference/objectSpread.js | 21 ++ .../baselines/reference/objectSpread.symbols | 285 +++++++++++------- tests/baselines/reference/objectSpread.types | 90 ++++++ .../reference/objectSpreadNegative.errors.txt | 16 - .../reference/objectSpreadNegative.js | 27 -- .../reference/objectSpreadNegative.symbols | 79 ----- .../reference/objectSpreadNegative.types | 99 ------ .../spreadInvalidArgumentType.errors.txt | 14 +- .../reference/spreadInvalidArgumentType.js | 26 +- .../spreadInvalidArgumentType.symbols | 14 +- .../reference/spreadInvalidArgumentType.types | 14 +- 11 files changed, 321 insertions(+), 364 deletions(-) diff --git a/tests/baselines/reference/objectSpread.js b/tests/baselines/reference/objectSpread.js index c47cc649498..b7d3e858c79 100644 --- a/tests/baselines/reference/objectSpread.js +++ b/tests/baselines/reference/objectSpread.js @@ -121,6 +121,20 @@ let shortCutted: { a: number, b: string } = { ...o, a } let spreadNonPrimitive = { ...{}}; // generic spreads + +function f(t: T, u: U) { + return { ...t, ...u, id: 'id' }; +} + +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +let overlap: { id: string, a: number, b: string } = + f({ a: 1 }, { a: 2, b: 'extra' }) +let overlapConflict: { id:string, a: string } = + f({ a: 1 }, { a: 'mismatch' }) +let overwriteId: { id: string, a: number, c: number, d: string } = + f({ a: 1, id: true }, { c: 1, d: 'no' }) + function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { let x01 = { ...t }; let x02 = { ...t, ...t }; @@ -236,6 +250,13 @@ var shortCutted = __assign({}, o, { a: a }); // non primitive var spreadNonPrimitive = __assign({}, {}); // generic spreads +function f(t, u) { + return __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' }); +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); diff --git a/tests/baselines/reference/objectSpread.symbols b/tests/baselines/reference/objectSpread.symbols index 6702ff5c909..e72772676e1 100644 --- a/tests/baselines/reference/objectSpread.symbols +++ b/tests/baselines/reference/objectSpread.symbols @@ -453,116 +453,183 @@ let spreadNonPrimitive = { ...{}}; >spreadNonPrimitive : Symbol(spreadNonPrimitive, Decl(objectSpread.ts, 119, 3)) // generic spreads -function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { ->genericSpread : Symbol(genericSpread, Decl(objectSpread.ts, 119, 42)) ->T : Symbol(T, Decl(objectSpread.ts, 122, 23)) ->U : Symbol(U, Decl(objectSpread.ts, 122, 25)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->T : Symbol(T, Decl(objectSpread.ts, 122, 23)) ->u : Symbol(u, Decl(objectSpread.ts, 122, 34)) ->U : Symbol(U, Decl(objectSpread.ts, 122, 25)) ->v : Symbol(v, Decl(objectSpread.ts, 122, 40)) ->T : Symbol(T, Decl(objectSpread.ts, 122, 23)) ->U : Symbol(U, Decl(objectSpread.ts, 122, 25)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) ->T : Symbol(T, Decl(objectSpread.ts, 122, 23)) ->s : Symbol(s, Decl(objectSpread.ts, 122, 59)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) ->x : Symbol(x, Decl(objectSpread.ts, 122, 79)) - let x01 = { ...t }; ->x01 : Symbol(x01, Decl(objectSpread.ts, 123, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) +function f(t: T, u: U) { +>f : Symbol(f, Decl(objectSpread.ts, 119, 42)) +>T : Symbol(T, Decl(objectSpread.ts, 123, 11)) +>U : Symbol(U, Decl(objectSpread.ts, 123, 13)) +>t : Symbol(t, Decl(objectSpread.ts, 123, 17)) +>T : Symbol(T, Decl(objectSpread.ts, 123, 11)) +>u : Symbol(u, Decl(objectSpread.ts, 123, 22)) +>U : Symbol(U, Decl(objectSpread.ts, 123, 13)) - let x02 = { ...t, ...t }; ->x02 : Symbol(x02, Decl(objectSpread.ts, 124, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) - - let x03 = { ...t, ...u }; ->x03 : Symbol(x03, Decl(objectSpread.ts, 125, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->u : Symbol(u, Decl(objectSpread.ts, 122, 34)) - - let x04 = { ...u, ...t }; ->x04 : Symbol(x04, Decl(objectSpread.ts, 126, 7)) ->u : Symbol(u, Decl(objectSpread.ts, 122, 34)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) - - let x05 = { a: 5, b: 'hi', ...t }; ->x05 : Symbol(x05, Decl(objectSpread.ts, 127, 7)) ->a : Symbol(a, Decl(objectSpread.ts, 127, 15)) ->b : Symbol(b, Decl(objectSpread.ts, 127, 21)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) - - let x06 = { ...t, a: 5, b: 'hi' }; ->x06 : Symbol(x06, Decl(objectSpread.ts, 128, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->a : Symbol(a, Decl(objectSpread.ts, 128, 21)) ->b : Symbol(b, Decl(objectSpread.ts, 128, 27)) - - let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; ->x07 : Symbol(x07, Decl(objectSpread.ts, 129, 7)) ->a : Symbol(a, Decl(objectSpread.ts, 129, 15)) ->b : Symbol(b, Decl(objectSpread.ts, 129, 21)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->c : Symbol(c, Decl(objectSpread.ts, 129, 36)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; ->x09 : Symbol(x09, Decl(objectSpread.ts, 130, 7)) ->a : Symbol(a, Decl(objectSpread.ts, 130, 15)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->b : Symbol(b, Decl(objectSpread.ts, 130, 27)) ->c : Symbol(c, Decl(objectSpread.ts, 130, 36)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; ->x10 : Symbol(x10, Decl(objectSpread.ts, 131, 7)) ->a : Symbol(a, Decl(objectSpread.ts, 131, 15)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->b : Symbol(b, Decl(objectSpread.ts, 131, 27)) ->u : Symbol(u, Decl(objectSpread.ts, 122, 34)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x11 = { ...v }; ->x11 : Symbol(x11, Decl(objectSpread.ts, 132, 7)) ->v : Symbol(v, Decl(objectSpread.ts, 122, 40)) - - let x12 = { ...v, ...obj }; ->x12 : Symbol(x12, Decl(objectSpread.ts, 133, 7)) ->v : Symbol(v, Decl(objectSpread.ts, 122, 40)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x13 = { ...w }; ->x13 : Symbol(x13, Decl(objectSpread.ts, 134, 7)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) - - let x14 = { ...w, ...obj }; ->x14 : Symbol(x14, Decl(objectSpread.ts, 135, 7)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x15 = { ...t, ...v }; ->x15 : Symbol(x15, Decl(objectSpread.ts, 136, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->v : Symbol(v, Decl(objectSpread.ts, 122, 40)) - - let x16 = { ...t, ...w }; ->x16 : Symbol(x16, Decl(objectSpread.ts, 137, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) - - let x17 = { ...t, ...w, ...obj }; ->x17 : Symbol(x17, Decl(objectSpread.ts, 138, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) ->obj : Symbol(obj, Decl(objectSpread.ts, 122, 72)) - - let x18 = { ...t, ...v, ...w }; ->x18 : Symbol(x18, Decl(objectSpread.ts, 139, 7)) ->t : Symbol(t, Decl(objectSpread.ts, 122, 29)) ->v : Symbol(v, Decl(objectSpread.ts, 122, 40)) ->w : Symbol(w, Decl(objectSpread.ts, 122, 50)) + return { ...t, ...u, id: 'id' }; +>t : Symbol(t, Decl(objectSpread.ts, 123, 17)) +>u : Symbol(u, Decl(objectSpread.ts, 123, 22)) +>id : Symbol(id, Decl(objectSpread.ts, 124, 24)) +} + +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = +>exclusive : Symbol(exclusive, Decl(objectSpread.ts, 127, 3)) +>id : Symbol(id, Decl(objectSpread.ts, 127, 16)) +>a : Symbol(a, Decl(objectSpread.ts, 127, 28)) +>b : Symbol(b, Decl(objectSpread.ts, 127, 39)) +>c : Symbol(c, Decl(objectSpread.ts, 127, 50)) +>d : Symbol(d, Decl(objectSpread.ts, 127, 61)) + + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +>f : Symbol(f, Decl(objectSpread.ts, 119, 42)) +>a : Symbol(a, Decl(objectSpread.ts, 128, 7)) +>b : Symbol(b, Decl(objectSpread.ts, 128, 13)) +>c : Symbol(c, Decl(objectSpread.ts, 128, 27)) +>d : Symbol(d, Decl(objectSpread.ts, 128, 36)) + +let overlap: { id: string, a: number, b: string } = +>overlap : Symbol(overlap, Decl(objectSpread.ts, 129, 3)) +>id : Symbol(id, Decl(objectSpread.ts, 129, 14)) +>a : Symbol(a, Decl(objectSpread.ts, 129, 26)) +>b : Symbol(b, Decl(objectSpread.ts, 129, 37)) + + f({ a: 1 }, { a: 2, b: 'extra' }) +>f : Symbol(f, Decl(objectSpread.ts, 119, 42)) +>a : Symbol(a, Decl(objectSpread.ts, 130, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 130, 17)) +>b : Symbol(b, Decl(objectSpread.ts, 130, 23)) + +let overlapConflict: { id:string, a: string } = +>overlapConflict : Symbol(overlapConflict, Decl(objectSpread.ts, 131, 3)) +>id : Symbol(id, Decl(objectSpread.ts, 131, 22)) +>a : Symbol(a, Decl(objectSpread.ts, 131, 33)) + + f({ a: 1 }, { a: 'mismatch' }) +>f : Symbol(f, Decl(objectSpread.ts, 119, 42)) +>a : Symbol(a, Decl(objectSpread.ts, 132, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 132, 17)) + +let overwriteId: { id: string, a: number, c: number, d: string } = +>overwriteId : Symbol(overwriteId, Decl(objectSpread.ts, 133, 3)) +>id : Symbol(id, Decl(objectSpread.ts, 133, 18)) +>a : Symbol(a, Decl(objectSpread.ts, 133, 30)) +>c : Symbol(c, Decl(objectSpread.ts, 133, 41)) +>d : Symbol(d, Decl(objectSpread.ts, 133, 52)) + + f({ a: 1, id: true }, { c: 1, d: 'no' }) +>f : Symbol(f, Decl(objectSpread.ts, 119, 42)) +>a : Symbol(a, Decl(objectSpread.ts, 134, 7)) +>id : Symbol(id, Decl(objectSpread.ts, 134, 13)) +>c : Symbol(c, Decl(objectSpread.ts, 134, 27)) +>d : Symbol(d, Decl(objectSpread.ts, 134, 33)) + +function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { +>genericSpread : Symbol(genericSpread, Decl(objectSpread.ts, 134, 44)) +>T : Symbol(T, Decl(objectSpread.ts, 136, 23)) +>U : Symbol(U, Decl(objectSpread.ts, 136, 25)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>T : Symbol(T, Decl(objectSpread.ts, 136, 23)) +>u : Symbol(u, Decl(objectSpread.ts, 136, 34)) +>U : Symbol(U, Decl(objectSpread.ts, 136, 25)) +>v : Symbol(v, Decl(objectSpread.ts, 136, 40)) +>T : Symbol(T, Decl(objectSpread.ts, 136, 23)) +>U : Symbol(U, Decl(objectSpread.ts, 136, 25)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) +>T : Symbol(T, Decl(objectSpread.ts, 136, 23)) +>s : Symbol(s, Decl(objectSpread.ts, 136, 59)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) +>x : Symbol(x, Decl(objectSpread.ts, 136, 79)) + + let x01 = { ...t }; +>x01 : Symbol(x01, Decl(objectSpread.ts, 137, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) + + let x02 = { ...t, ...t }; +>x02 : Symbol(x02, Decl(objectSpread.ts, 138, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) + + let x03 = { ...t, ...u }; +>x03 : Symbol(x03, Decl(objectSpread.ts, 139, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>u : Symbol(u, Decl(objectSpread.ts, 136, 34)) + + let x04 = { ...u, ...t }; +>x04 : Symbol(x04, Decl(objectSpread.ts, 140, 7)) +>u : Symbol(u, Decl(objectSpread.ts, 136, 34)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) + + let x05 = { a: 5, b: 'hi', ...t }; +>x05 : Symbol(x05, Decl(objectSpread.ts, 141, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 141, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 141, 21)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) + + let x06 = { ...t, a: 5, b: 'hi' }; +>x06 : Symbol(x06, Decl(objectSpread.ts, 142, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>a : Symbol(a, Decl(objectSpread.ts, 142, 21)) +>b : Symbol(b, Decl(objectSpread.ts, 142, 27)) + + let x07 = { a: 5, b: 'hi', ...t, c: true, ...obj }; +>x07 : Symbol(x07, Decl(objectSpread.ts, 143, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 143, 15)) +>b : Symbol(b, Decl(objectSpread.ts, 143, 21)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>c : Symbol(c, Decl(objectSpread.ts, 143, 36)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x09 = { a: 5, ...t, b: 'hi', c: true, ...obj }; +>x09 : Symbol(x09, Decl(objectSpread.ts, 144, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 144, 15)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>b : Symbol(b, Decl(objectSpread.ts, 144, 27)) +>c : Symbol(c, Decl(objectSpread.ts, 144, 36)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x10 = { a: 5, ...t, b: 'hi', ...u, ...obj }; +>x10 : Symbol(x10, Decl(objectSpread.ts, 145, 7)) +>a : Symbol(a, Decl(objectSpread.ts, 145, 15)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>b : Symbol(b, Decl(objectSpread.ts, 145, 27)) +>u : Symbol(u, Decl(objectSpread.ts, 136, 34)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x11 = { ...v }; +>x11 : Symbol(x11, Decl(objectSpread.ts, 146, 7)) +>v : Symbol(v, Decl(objectSpread.ts, 136, 40)) + + let x12 = { ...v, ...obj }; +>x12 : Symbol(x12, Decl(objectSpread.ts, 147, 7)) +>v : Symbol(v, Decl(objectSpread.ts, 136, 40)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x13 = { ...w }; +>x13 : Symbol(x13, Decl(objectSpread.ts, 148, 7)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) + + let x14 = { ...w, ...obj }; +>x14 : Symbol(x14, Decl(objectSpread.ts, 149, 7)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x15 = { ...t, ...v }; +>x15 : Symbol(x15, Decl(objectSpread.ts, 150, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>v : Symbol(v, Decl(objectSpread.ts, 136, 40)) + + let x16 = { ...t, ...w }; +>x16 : Symbol(x16, Decl(objectSpread.ts, 151, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) + + let x17 = { ...t, ...w, ...obj }; +>x17 : Symbol(x17, Decl(objectSpread.ts, 152, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) +>obj : Symbol(obj, Decl(objectSpread.ts, 136, 72)) + + let x18 = { ...t, ...v, ...w }; +>x18 : Symbol(x18, Decl(objectSpread.ts, 153, 7)) +>t : Symbol(t, Decl(objectSpread.ts, 136, 29)) +>v : Symbol(v, Decl(objectSpread.ts, 136, 40)) +>w : Symbol(w, Decl(objectSpread.ts, 136, 50)) } diff --git a/tests/baselines/reference/objectSpread.types b/tests/baselines/reference/objectSpread.types index 8df457a162d..0ffd5dd20b7 100644 --- a/tests/baselines/reference/objectSpread.types +++ b/tests/baselines/reference/objectSpread.types @@ -579,6 +579,96 @@ let spreadNonPrimitive = { ...{}}; >{} : {} // generic spreads + +function f(t: T, u: U) { +>f : (t: T, u: U) => T & U & { id: string; } +>t : T +>u : U + + return { ...t, ...u, id: 'id' }; +>{ ...t, ...u, id: 'id' } : T & U & { id: string; } +>t : T +>u : U +>id : string +>'id' : "id" +} + +let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = +>exclusive : { id: string; a: number; b: string; c: string; d: boolean; } +>id : string +>a : number +>b : string +>c : string +>d : boolean + + f({ a: 1, b: 'yes' }, { c: 'no', d: false }) +>f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : { a: number; b: string; } & { c: string; d: boolean; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } +>{ a: 1, b: 'yes' } : { a: number; b: string; } +>a : number +>1 : 1 +>b : string +>'yes' : "yes" +>{ c: 'no', d: false } : { c: string; d: false; } +>c : string +>'no' : "no" +>d : false +>false : false + +let overlap: { id: string, a: number, b: string } = +>overlap : { id: string; a: number; b: string; } +>id : string +>a : number +>b : string + + f({ a: 1 }, { a: 2, b: 'extra' }) +>f({ a: 1 }, { a: 2, b: 'extra' }) : { a: number; } & { a: number; b: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } +>{ a: 1 } : { a: number; } +>a : number +>1 : 1 +>{ a: 2, b: 'extra' } : { a: number; b: string; } +>a : number +>2 : 2 +>b : string +>'extra' : "extra" + +let overlapConflict: { id:string, a: string } = +>overlapConflict : { id: string; a: string; } +>id : string +>a : string + + f({ a: 1 }, { a: 'mismatch' }) +>f({ a: 1 }, { a: 'mismatch' }) : { a: number; } & { a: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } +>{ a: 1 } : { a: number; } +>a : number +>1 : 1 +>{ a: 'mismatch' } : { a: string; } +>a : string +>'mismatch' : "mismatch" + +let overwriteId: { id: string, a: number, c: number, d: string } = +>overwriteId : { id: string; a: number; c: number; d: string; } +>id : string +>a : number +>c : number +>d : string + + f({ a: 1, id: true }, { c: 1, d: 'no' }) +>f({ a: 1, id: true }, { c: 1, d: 'no' }) : { a: number; id: boolean; } & { c: number; d: string; } & { id: string; } +>f : (t: T, u: U) => T & U & { id: string; } +>{ a: 1, id: true } : { a: number; id: true; } +>a : number +>1 : 1 +>id : true +>true : true +>{ c: 1, d: 'no' } : { c: number; d: string; } +>c : number +>1 : 1 +>d : string +>'no' : "no" + function genericSpread(t: T, u: U, v: T | U, w: T | { s: string }, obj: { x: number }) { >genericSpread : (t: T, u: U, v: T | U, w: T | { s: string; }, obj: { x: number; }) => void >t : T diff --git a/tests/baselines/reference/objectSpreadNegative.errors.txt b/tests/baselines/reference/objectSpreadNegative.errors.txt index c7f33d2d61b..43c7ffdcca5 100644 --- a/tests/baselines/reference/objectSpreadNegative.errors.txt +++ b/tests/baselines/reference/objectSpreadNegative.errors.txt @@ -110,20 +110,4 @@ tests/cases/conformance/types/spread/objectSpreadNegative.ts(58,11): error TS233 spreadObj.a; // error 'a' is not in {} ~ !!! error TS2339: Property 'a' does not exist on type '{}'. - - // generics - function f(t: T, u: U) { - return { ...t, ...u, id: 'id' }; - } - function override(initial: U, override: U): U { - return { ...initial, ...override }; - } - let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = - f({ a: 1, b: 'yes' }, { c: 'no', d: false }) - let overlap: { id: string, a: number, b: string } = - f({ a: 1 }, { a: 2, b: 'extra' }) - let overlapConflict: { id:string, a: string } = - f({ a: 1 }, { a: 'mismatch' }) - let overwriteId: { id: string, a: number, c: number, d: string } = - f({ a: 1, id: true }, { c: 1, d: 'no' }) \ No newline at end of file diff --git a/tests/baselines/reference/objectSpreadNegative.js b/tests/baselines/reference/objectSpreadNegative.js index 35d8cdf9830..23de5699ce6 100644 --- a/tests/baselines/reference/objectSpreadNegative.js +++ b/tests/baselines/reference/objectSpreadNegative.js @@ -57,22 +57,6 @@ spreadC.m(); // error 'm' is not in '{ ... c }' let obj: object = { a: 123 }; let spreadObj = { ...obj }; spreadObj.a; // error 'a' is not in {} - -// generics -function f(t: T, u: U) { - return { ...t, ...u, id: 'id' }; -} -function override(initial: U, override: U): U { - return { ...initial, ...override }; -} -let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = - f({ a: 1, b: 'yes' }, { c: 'no', d: false }) -let overlap: { id: string, a: number, b: string } = - f({ a: 1 }, { a: 2, b: 'extra' }) -let overlapConflict: { id:string, a: string } = - f({ a: 1 }, { a: 'mismatch' }) -let overwriteId: { id: string, a: number, c: number, d: string } = - f({ a: 1, id: true }, { c: 1, d: 'no' }) //// [objectSpreadNegative.js] @@ -146,14 +130,3 @@ spreadC.m(); // error 'm' is not in '{ ... c }' var obj = { a: 123 }; var spreadObj = __assign({}, obj); spreadObj.a; // error 'a' is not in {} -// generics -function f(t, u) { - return __assign({}, t, u, { id: 'id' }); -} -function override(initial, override) { - return __assign({}, initial, override); -} -var exclusive = f({ a: 1, b: 'yes' }, { c: 'no', d: false }); -var overlap = f({ a: 1 }, { a: 2, b: 'extra' }); -var overlapConflict = f({ a: 1 }, { a: 'mismatch' }); -var overwriteId = f({ a: 1, id: true }, { c: 1, d: 'no' }); diff --git a/tests/baselines/reference/objectSpreadNegative.symbols b/tests/baselines/reference/objectSpreadNegative.symbols index 4bff16d9be6..0e398fa2ec1 100644 --- a/tests/baselines/reference/objectSpreadNegative.symbols +++ b/tests/baselines/reference/objectSpreadNegative.symbols @@ -164,82 +164,3 @@ let spreadObj = { ...obj }; spreadObj.a; // error 'a' is not in {} >spreadObj : Symbol(spreadObj, Decl(objectSpreadNegative.ts, 56, 3)) -// generics -function f(t: T, u: U) { ->f : Symbol(f, Decl(objectSpreadNegative.ts, 57, 12)) ->T : Symbol(T, Decl(objectSpreadNegative.ts, 60, 11)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 60, 13)) ->t : Symbol(t, Decl(objectSpreadNegative.ts, 60, 17)) ->T : Symbol(T, Decl(objectSpreadNegative.ts, 60, 11)) ->u : Symbol(u, Decl(objectSpreadNegative.ts, 60, 22)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 60, 13)) - - return { ...t, ...u, id: 'id' }; ->t : Symbol(t, Decl(objectSpreadNegative.ts, 60, 17)) ->u : Symbol(u, Decl(objectSpreadNegative.ts, 60, 22)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 61, 24)) -} -function override(initial: U, override: U): U { ->override : Symbol(override, Decl(objectSpreadNegative.ts, 62, 1)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 63, 18)) ->initial : Symbol(initial, Decl(objectSpreadNegative.ts, 63, 21)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 63, 18)) ->override : Symbol(override, Decl(objectSpreadNegative.ts, 63, 32)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 63, 18)) ->U : Symbol(U, Decl(objectSpreadNegative.ts, 63, 18)) - - return { ...initial, ...override }; ->initial : Symbol(initial, Decl(objectSpreadNegative.ts, 63, 21)) ->override : Symbol(override, Decl(objectSpreadNegative.ts, 63, 32)) -} -let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = ->exclusive : Symbol(exclusive, Decl(objectSpreadNegative.ts, 66, 3)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 66, 16)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 66, 28)) ->b : Symbol(b, Decl(objectSpreadNegative.ts, 66, 39)) ->c : Symbol(c, Decl(objectSpreadNegative.ts, 66, 50)) ->d : Symbol(d, Decl(objectSpreadNegative.ts, 66, 61)) - - f({ a: 1, b: 'yes' }, { c: 'no', d: false }) ->f : Symbol(f, Decl(objectSpreadNegative.ts, 57, 12)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 67, 7)) ->b : Symbol(b, Decl(objectSpreadNegative.ts, 67, 13)) ->c : Symbol(c, Decl(objectSpreadNegative.ts, 67, 27)) ->d : Symbol(d, Decl(objectSpreadNegative.ts, 67, 36)) - -let overlap: { id: string, a: number, b: string } = ->overlap : Symbol(overlap, Decl(objectSpreadNegative.ts, 68, 3)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 68, 14)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 68, 26)) ->b : Symbol(b, Decl(objectSpreadNegative.ts, 68, 37)) - - f({ a: 1 }, { a: 2, b: 'extra' }) ->f : Symbol(f, Decl(objectSpreadNegative.ts, 57, 12)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 69, 7)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 69, 17)) ->b : Symbol(b, Decl(objectSpreadNegative.ts, 69, 23)) - -let overlapConflict: { id:string, a: string } = ->overlapConflict : Symbol(overlapConflict, Decl(objectSpreadNegative.ts, 70, 3)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 70, 22)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 70, 33)) - - f({ a: 1 }, { a: 'mismatch' }) ->f : Symbol(f, Decl(objectSpreadNegative.ts, 57, 12)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 71, 7)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 71, 17)) - -let overwriteId: { id: string, a: number, c: number, d: string } = ->overwriteId : Symbol(overwriteId, Decl(objectSpreadNegative.ts, 72, 3)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 72, 18)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 72, 30)) ->c : Symbol(c, Decl(objectSpreadNegative.ts, 72, 41)) ->d : Symbol(d, Decl(objectSpreadNegative.ts, 72, 52)) - - f({ a: 1, id: true }, { c: 1, d: 'no' }) ->f : Symbol(f, Decl(objectSpreadNegative.ts, 57, 12)) ->a : Symbol(a, Decl(objectSpreadNegative.ts, 73, 7)) ->id : Symbol(id, Decl(objectSpreadNegative.ts, 73, 13)) ->c : Symbol(c, Decl(objectSpreadNegative.ts, 73, 27)) ->d : Symbol(d, Decl(objectSpreadNegative.ts, 73, 33)) - diff --git a/tests/baselines/reference/objectSpreadNegative.types b/tests/baselines/reference/objectSpreadNegative.types index ed2d996af9d..60bfb382c0a 100644 --- a/tests/baselines/reference/objectSpreadNegative.types +++ b/tests/baselines/reference/objectSpreadNegative.types @@ -226,102 +226,3 @@ spreadObj.a; // error 'a' is not in {} >spreadObj : {} >a : any -// generics -function f(t: T, u: U) { ->f : (t: T, u: U) => T & U & { id: string; } ->t : T ->u : U - - return { ...t, ...u, id: 'id' }; ->{ ...t, ...u, id: 'id' } : T & U & { id: string; } ->t : T ->u : U ->id : string ->'id' : "id" -} -function override(initial: U, override: U): U { ->override : (initial: U, override: U) => U ->initial : U ->override : U - - return { ...initial, ...override }; ->{ ...initial, ...override } : U ->initial : U ->override : U -} -let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = ->exclusive : { id: string; a: number; b: string; c: string; d: boolean; } ->id : string ->a : number ->b : string ->c : string ->d : boolean - - f({ a: 1, b: 'yes' }, { c: 'no', d: false }) ->f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : { a: number; b: string; } & { c: string; d: boolean; } & { id: string; } ->f : (t: T, u: U) => T & U & { id: string; } ->{ a: 1, b: 'yes' } : { a: number; b: string; } ->a : number ->1 : 1 ->b : string ->'yes' : "yes" ->{ c: 'no', d: false } : { c: string; d: false; } ->c : string ->'no' : "no" ->d : false ->false : false - -let overlap: { id: string, a: number, b: string } = ->overlap : { id: string; a: number; b: string; } ->id : string ->a : number ->b : string - - f({ a: 1 }, { a: 2, b: 'extra' }) ->f({ a: 1 }, { a: 2, b: 'extra' }) : { a: number; } & { a: number; b: string; } & { id: string; } ->f : (t: T, u: U) => T & U & { id: string; } ->{ a: 1 } : { a: number; } ->a : number ->1 : 1 ->{ a: 2, b: 'extra' } : { a: number; b: string; } ->a : number ->2 : 2 ->b : string ->'extra' : "extra" - -let overlapConflict: { id:string, a: string } = ->overlapConflict : { id: string; a: string; } ->id : string ->a : string - - f({ a: 1 }, { a: 'mismatch' }) ->f({ a: 1 }, { a: 'mismatch' }) : { a: number; } & { a: string; } & { id: string; } ->f : (t: T, u: U) => T & U & { id: string; } ->{ a: 1 } : { a: number; } ->a : number ->1 : 1 ->{ a: 'mismatch' } : { a: string; } ->a : string ->'mismatch' : "mismatch" - -let overwriteId: { id: string, a: number, c: number, d: string } = ->overwriteId : { id: string; a: number; c: number; d: string; } ->id : string ->a : number ->c : number ->d : string - - f({ a: 1, id: true }, { c: 1, d: 'no' }) ->f({ a: 1, id: true }, { c: 1, d: 'no' }) : { a: number; id: boolean; } & { c: number; d: string; } & { id: string; } ->f : (t: T, u: U) => T & U & { id: string; } ->{ a: 1, id: true } : { a: number; id: true; } ->a : number ->1 : 1 ->id : true ->true : true ->{ c: 1, d: 'no' } : { c: number; d: string; } ->c : number ->1 : 1 ->d : string ->'no' : "no" - diff --git a/tests/baselines/reference/spreadInvalidArgumentType.errors.txt b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt index 50caa0e76bb..cb2b74b7b19 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.errors.txt +++ b/tests/baselines/reference/spreadInvalidArgumentType.errors.txt @@ -40,22 +40,22 @@ tests/cases/compiler/spreadInvalidArgumentType.ts(55,17): error TS2698: Spread t var e: E; - var o1 = { ...p1 }; // Error, generic type paramterre - var o2 = { ...p2 }; // OK - var o3 = { ...t }; // Error, generic type paramter - var o4 = { ...i }; // Error, index access + var o1 = { ...p1 }; // OK, generic type paramterre + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // OK, generic type paramter + var o4 = { ...i }; // OK, index access var o5 = { ...k }; // Error, index ~~~~ !!! error TS2698: Spread types may only be created from object types. - var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o6 = { ...mapped_generic }; // OK, generic mapped object type var o7 = { ...mapped }; // OK, non-generic mapped type - var o8 = { ...union_generic }; // Error, union with generic type parameter + var o8 = { ...union_generic }; // OK, union with generic type parameter var o9 = { ...union_primitive }; // Error, union with generic type parameter ~~~~~~~~~~~~~~~~~~ !!! error TS2698: Spread types may only be created from object types. - var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o10 = { ...intersection_generic }; // OK, intersection with generic type parameter var o11 = { ...intersection_primitive }; // Error, intersection with generic type parameter ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2698: Spread types may only be created from object types. diff --git a/tests/baselines/reference/spreadInvalidArgumentType.js b/tests/baselines/reference/spreadInvalidArgumentType.js index 9a08fe4c366..b1cb2561eca 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.js +++ b/tests/baselines/reference/spreadInvalidArgumentType.js @@ -28,18 +28,18 @@ function f(p1: T, p2: T[]) { var e: E; - var o1 = { ...p1 }; // Error, generic type paramterre - var o2 = { ...p2 }; // OK - var o3 = { ...t }; // Error, generic type paramter - var o4 = { ...i }; // Error, index access + var o1 = { ...p1 }; // OK, generic type paramterre + var o2 = { ...p2 }; // OK + var o3 = { ...t }; // OK, generic type paramter + var o4 = { ...i }; // OK, index access var o5 = { ...k }; // Error, index - var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o6 = { ...mapped_generic }; // OK, generic mapped object type var o7 = { ...mapped }; // OK, non-generic mapped type - var o8 = { ...union_generic }; // Error, union with generic type parameter + var o8 = { ...union_generic }; // OK, union with generic type parameter var o9 = { ...union_primitive }; // Error, union with generic type parameter - var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o10 = { ...intersection_generic }; // OK, intersection with generic type parameter var o11 = { ...intersection_primitive }; // Error, intersection with generic type parameter var o12 = { ...num }; // Error @@ -93,16 +93,16 @@ function f(p1, p2) { var n; var a; var e; - var o1 = __assign({}, p1); // Error, generic type paramterre + var o1 = __assign({}, p1); // OK, generic type paramterre var o2 = __assign({}, p2); // OK - var o3 = __assign({}, t); // Error, generic type paramter - var o4 = __assign({}, i); // Error, index access + var o3 = __assign({}, t); // OK, generic type paramter + var o4 = __assign({}, i); // OK, index access var o5 = __assign({}, k); // Error, index - var o6 = __assign({}, mapped_generic); // Error, generic mapped object type + var o6 = __assign({}, mapped_generic); // OK, generic mapped object type var o7 = __assign({}, mapped); // OK, non-generic mapped type - var o8 = __assign({}, union_generic); // Error, union with generic type parameter + var o8 = __assign({}, union_generic); // OK, union with generic type parameter var o9 = __assign({}, union_primitive); // Error, union with generic type parameter - var o10 = __assign({}, intersection_generic); // Error, intersection with generic type parameter + var o10 = __assign({}, intersection_generic); // OK, intersection with generic type parameter var o11 = __assign({}, intersection_primitive); // Error, intersection with generic type parameter var o12 = __assign({}, num); // Error var o13 = __assign({}, str); // Error diff --git a/tests/baselines/reference/spreadInvalidArgumentType.symbols b/tests/baselines/reference/spreadInvalidArgumentType.symbols index 3701440ffe8..8c29a923d37 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.symbols +++ b/tests/baselines/reference/spreadInvalidArgumentType.symbols @@ -82,19 +82,19 @@ function f(p1: T, p2: T[]) { >e : Symbol(e, Decl(spreadInvalidArgumentType.ts, 27, 7)) >E : Symbol(E, Decl(spreadInvalidArgumentType.ts, 0, 0)) - var o1 = { ...p1 }; // Error, generic type paramterre + var o1 = { ...p1 }; // OK, generic type paramterre >o1 : Symbol(o1, Decl(spreadInvalidArgumentType.ts, 29, 7)) >p1 : Symbol(p1, Decl(spreadInvalidArgumentType.ts, 2, 36)) - var o2 = { ...p2 }; // OK + var o2 = { ...p2 }; // OK >o2 : Symbol(o2, Decl(spreadInvalidArgumentType.ts, 30, 7)) >p2 : Symbol(p2, Decl(spreadInvalidArgumentType.ts, 2, 42)) - var o3 = { ...t }; // Error, generic type paramter + var o3 = { ...t }; // OK, generic type paramter >o3 : Symbol(o3, Decl(spreadInvalidArgumentType.ts, 31, 7)) >t : Symbol(t, Decl(spreadInvalidArgumentType.ts, 3, 7)) - var o4 = { ...i }; // Error, index access + var o4 = { ...i }; // OK, index access >o4 : Symbol(o4, Decl(spreadInvalidArgumentType.ts, 32, 7)) >i : Symbol(i, Decl(spreadInvalidArgumentType.ts, 5, 7)) @@ -102,7 +102,7 @@ function f(p1: T, p2: T[]) { >o5 : Symbol(o5, Decl(spreadInvalidArgumentType.ts, 33, 7)) >k : Symbol(k, Decl(spreadInvalidArgumentType.ts, 6, 7)) - var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o6 = { ...mapped_generic }; // OK, generic mapped object type >o6 : Symbol(o6, Decl(spreadInvalidArgumentType.ts, 34, 7)) >mapped_generic : Symbol(mapped_generic, Decl(spreadInvalidArgumentType.ts, 8, 7)) @@ -110,7 +110,7 @@ function f(p1: T, p2: T[]) { >o7 : Symbol(o7, Decl(spreadInvalidArgumentType.ts, 35, 7)) >mapped : Symbol(mapped, Decl(spreadInvalidArgumentType.ts, 9, 7)) - var o8 = { ...union_generic }; // Error, union with generic type parameter + var o8 = { ...union_generic }; // OK, union with generic type parameter >o8 : Symbol(o8, Decl(spreadInvalidArgumentType.ts, 37, 7)) >union_generic : Symbol(union_generic, Decl(spreadInvalidArgumentType.ts, 11, 7)) @@ -118,7 +118,7 @@ function f(p1: T, p2: T[]) { >o9 : Symbol(o9, Decl(spreadInvalidArgumentType.ts, 38, 7)) >union_primitive : Symbol(union_primitive, Decl(spreadInvalidArgumentType.ts, 12, 7)) - var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o10 = { ...intersection_generic }; // OK, intersection with generic type parameter >o10 : Symbol(o10, Decl(spreadInvalidArgumentType.ts, 40, 7)) >intersection_generic : Symbol(intersection_generic, Decl(spreadInvalidArgumentType.ts, 14, 7)) diff --git a/tests/baselines/reference/spreadInvalidArgumentType.types b/tests/baselines/reference/spreadInvalidArgumentType.types index 13e22457e3b..6828d557d0a 100644 --- a/tests/baselines/reference/spreadInvalidArgumentType.types +++ b/tests/baselines/reference/spreadInvalidArgumentType.types @@ -67,22 +67,22 @@ function f(p1: T, p2: T[]) { var e: E; >e : E - var o1 = { ...p1 }; // Error, generic type paramterre + var o1 = { ...p1 }; // OK, generic type paramterre >o1 : T >{ ...p1 } : T >p1 : T - var o2 = { ...p2 }; // OK + var o2 = { ...p2 }; // OK >o2 : { [x: number]: T; length: number; toString(): string; toLocaleString(): string; pop(): T; push(...items: T[]): number; concat(...items: ConcatArray[]): T[]; concat(...items: (T | ConcatArray)[]): T[]; join(separator?: string): string; reverse(): T[]; shift(): T; slice(start?: number, end?: number): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; splice(start: number, deleteCount?: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; unshift(...items: T[]): number; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; } >{ ...p2 } : { [n: number]: T; length: number; toString(): string; toLocaleString(): string; pop(): T; push(...items: T[]): number; concat(...items: ConcatArray[]): T[]; concat(...items: (T | ConcatArray)[]): T[]; join(separator?: string): string; reverse(): T[]; shift(): T; slice(start?: number, end?: number): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; splice(start: number, deleteCount?: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; unshift(...items: T[]): number; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; } >p2 : T[] - var o3 = { ...t }; // Error, generic type paramter + var o3 = { ...t }; // OK, generic type paramter >o3 : T >{ ...t } : T >t : T - var o4 = { ...i }; // Error, index access + var o4 = { ...i }; // OK, index access >o4 : T["b"] >{ ...i } : T["b"] >i : T["b"] @@ -92,7 +92,7 @@ function f(p1: T, p2: T[]) { >{ ...k } : any >k : keyof T - var o6 = { ...mapped_generic }; // Error, generic mapped object type + var o6 = { ...mapped_generic }; // OK, generic mapped object type >o6 : { [P in keyof T]: T[P]; } >{ ...mapped_generic } : { [P in keyof T]: T[P]; } >mapped_generic : { [P in keyof T]: T[P]; } @@ -102,7 +102,7 @@ function f(p1: T, p2: T[]) { >{ ...mapped } : { b: T["b"]; } >mapped : { b: T["b"]; } - var o8 = { ...union_generic }; // Error, union with generic type parameter + var o8 = { ...union_generic }; // OK, union with generic type parameter >o8 : T | { a: number; } >{ ...union_generic } : T | { a: number; } >union_generic : T | { a: number; } @@ -112,7 +112,7 @@ function f(p1: T, p2: T[]) { >{ ...union_primitive } : any >union_primitive : number | { a: number; } - var o10 = { ...intersection_generic }; // Error, intersection with generic type parameter + var o10 = { ...intersection_generic }; // OK, intersection with generic type parameter >o10 : T & { a: number; } >{ ...intersection_generic } : T & { a: number; } >intersection_generic : T & { a: number; } From 3458360322a2d84d4512fd136bc39210e233623d Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 16:38:52 -0700 Subject: [PATCH 166/262] Prefer getValidSourceFile over Debug.assertDefined(program.getSourceFile(*)) (#28242) --- src/services/services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/services.ts b/src/services/services.ts index a91836e6687..4367bd11985 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1533,7 +1533,7 @@ namespace ts { const normalizedFileName = normalizePath(fileName); Debug.assert(filesToSearch.some(f => normalizePath(f) === normalizedFileName)); synchronizeHostData(); - const sourceFilesToSearch = map(filesToSearch, f => Debug.assertDefined(program.getSourceFile(f))); + const sourceFilesToSearch = filesToSearch.map(getValidSourceFile); const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } From 903e68164ed0d18e39fd4630100a7b3ed05515ba Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 16:39:40 -0700 Subject: [PATCH 167/262] Redo resolution on ATA when previous resolution was to '.js' file (#28236) * Redo resolution on ATA when previous resolution was to '.js' file * Use a separate test case --- src/compiler/resolutionCache.ts | 9 ++-- src/server/project.ts | 4 +- src/testRunner/unittests/typingsInstaller.ts | 44 ++++++++++++++++++++ 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 6c8c79adefb..728ab926077 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -248,6 +248,7 @@ namespace ts { perDirectoryCacheWithRedirects: CacheWithRedirects>, loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T, getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName, + shouldRetryResolution: (t: T) => boolean, reusedNames: ReadonlyArray | undefined, logChanges: boolean): (R | undefined)[] { @@ -260,7 +261,7 @@ namespace ts { perDirectoryResolution = createMap(); perDirectoryCache.set(dirPath, perDirectoryResolution); } - const resolvedModules: R[] = []; + const resolvedModules: (R | undefined)[] = []; const compilerOptions = resolutionHost.getCompilationSettings(); const hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); @@ -278,7 +279,7 @@ namespace ts { if (!seenNamesInFile.has(name) && allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { + (hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { const existingResolution = resolution; const resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { @@ -302,7 +303,7 @@ namespace ts { } Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)!); // TODO: GH#18217 + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); } // Stop watching and remove the unused name @@ -339,6 +340,7 @@ namespace ts { typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*shouldRetryResolution*/ resolution => resolution.resolvedTypeReferenceDirective === undefined, /*reusedNames*/ undefined, /*logChanges*/ false ); } @@ -348,6 +350,7 @@ namespace ts { moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, + /*shouldRetryResolution*/ resolution => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), reusedNames, logChangesWhenResolvingModule ); } diff --git a/src/server/project.ts b/src/server/project.ts index 35ccea66008..89bac4060bb 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1186,7 +1186,9 @@ namespace ts.server { let unresolvedImports: string[] | undefined; file.resolvedModules.forEach((resolvedModule, name) => { // pick unresolved non-relative names - if (!resolvedModule && !isExternalModuleNameRelative(name) && !ambientModules.some(m => m === name)) { + if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && + !isExternalModuleNameRelative(name) && + !ambientModules.some(m => m === name)) { unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); } }); diff --git a/src/testRunner/unittests/typingsInstaller.ts b/src/testRunner/unittests/typingsInstaller.ts index b06c22d5d79..7e0790b7dbb 100644 --- a/src/testRunner/unittests/typingsInstaller.ts +++ b/src/testRunner/unittests/typingsInstaller.ts @@ -986,6 +986,50 @@ namespace ts.projectSystem { checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]); }); + it("should redo resolution that resolved to '.js' file after typings are installed", () => { + const file: TestFSWithWatch.File = { + path: "/a/b/app.js", + content: ` + import * as commander from "commander";` + }; + const cachePath = "/a/cache"; + const commanderJS: TestFSWithWatch.File = { + path: "/node_modules/commander/index.js", + content: "module.exports = 0", + }; + + const typeNames: ReadonlyArray = ["commander"]; + const typePath = (name: string): string => `${cachePath}/node_modules/@types/${name}/index.d.ts`; + const host = createServerHost([file, commanderJS]); + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry(...typeNames) }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) { + const installedTypings = typeNames.map(name => `@types/${name}`); + const typingFiles = typeNames.map((name): TestFSWithWatch.File => ({ path: typePath(name), content: "" })); + executeCommand(this, host, installedTypings, typingFiles, cb); + } + })(); + const service = createProjectService(host, { typingsInstaller: installer }); + service.openClientFile(file.path); + + checkWatchedFiles(host, [...flatMap(["/a/b", "/a", ""], x => [x + "/tsconfig.json", x + "/jsconfig.json"]), "/a/lib/lib.d.ts"]); + checkWatchedDirectories(host, [], /*recursive*/ false); + // Does not include cachePath because that is handled by typingsInstaller + checkWatchedDirectories(host, ["/node_modules", "/a/b/node_modules", "/a/b/node_modules/@types", "/a/b/bower_components"], /*recursive*/ true); + + service.checkNumberOfProjects({ inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [file.path, commanderJS.path]); + + installer.installAll(/*expectedCount*/1); + for (const name of typeNames) { + assert.isTrue(host.fileExists(typePath(name)), `typings for '${name}' should be created`); + } + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.inferredProjects[0], [file.path, ...typeNames.map(typePath)]); + }); + it("should pick typing names from non-relative unresolved imports", () => { const f1 = { path: "/a/b/app.js", From 305303cc0d5a785d5b917a8776d40dfe4e5de335 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 30 Oct 2018 18:59:25 -0700 Subject: [PATCH 168/262] Fix test case for project reference with composite not true --- src/testRunner/unittests/projectReferences.ts | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/testRunner/unittests/projectReferences.ts b/src/testRunner/unittests/projectReferences.ts index 53fcd4a9dd0..5b99e01585d 100644 --- a/src/testRunner/unittests/projectReferences.ts +++ b/src/testRunner/unittests/projectReferences.ts @@ -147,7 +147,10 @@ namespace ts { }, "/reference": { files: { "/secondary/b.ts": moduleImporting("../primary/a") }, - references: ["../primary"] + references: ["../primary"], + config: { + files: ["b.ts"] + } } }; testProjectReferences(spec, "/reference/tsconfig.json", program => { @@ -156,6 +159,26 @@ namespace ts { }); }); + it("does not error when the referenced project doesn't have composite:true if its a container project", () => { + const spec: TestSpecification = { + "/primary": { + files: { "/primary/a.ts": emptyModule }, + references: [], + options: { + composite: false + } + }, + "/reference": { + files: { "/secondary/b.ts": moduleImporting("../primary/a") }, + references: ["../primary"], + } + }; + testProjectReferences(spec, "/reference/tsconfig.json", program => { + const errs = program.getOptionsDiagnostics(); + assertNoErrors("Reports an error about 'composite' not being set", errs); + }); + }); + it("errors when the file list is not exhaustive", () => { const spec: TestSpecification = { "/primary": { From dce6668070ee5661e0e963b1634e048157a5fb54 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 30 Oct 2018 22:01:31 -0700 Subject: [PATCH 169/262] Change pathCompletions to stringCompletions, move more code there (#28245) --- src/services/completions.ts | 288 +----------------- ...athCompletions.ts => stringCompletions.ts} | 226 +++++++++++++- src/services/tsconfig.json | 2 +- src/services/utilities.ts | 66 ++++ 4 files changed, 296 insertions(+), 286 deletions(-) rename src/services/{pathCompletions.ts => stringCompletions.ts} (64%) diff --git a/src/services/completions.ts b/src/services/completions.ts index af9cc3d240a..f1e33087fdc 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -37,18 +37,13 @@ namespace ts.Completions { export function getCompletionsAtPosition(host: LanguageServiceHost, program: Program, log: Log, sourceFile: SourceFile, position: number, preferences: UserPreferences, triggerCharacter: CompletionsTriggerCharacter | undefined): CompletionInfo | undefined { const typeChecker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); - if (isInReferenceComment(sourceFile, position)) { - const entries = PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries && convertPathCompletions(entries); - } const contextToken = findPrecedingToken(position, sourceFile); if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) return undefined; - if (isInString(sourceFile, position, contextToken)) { - return !contextToken || !isStringLiteralLike(contextToken) - ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); + const stringCompletions = StringCompletions.getStringLiteralCompletions(sourceFile, position, contextToken, typeChecker, compilerOptions, host, log, preferences); + if (stringCompletions) { + return stringCompletions; } if (contextToken && isBreakOrContinueStatement(contextToken.parent) @@ -77,48 +72,6 @@ namespace ts.Completions { } } - function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, sourceFile: SourceFile, checker: TypeChecker, log: Log, preferences: UserPreferences): CompletionInfo | undefined { - if (completion === undefined) { - return undefined; - } - switch (completion.kind) { - case StringLiteralCompletionKind.Paths: - return convertPathCompletions(completion.paths); - case StringLiteralCompletionKind.Properties: { - const entries: CompletionEntry[] = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries }; - } - case StringLiteralCompletionKind.Types: { - const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.string, sortText: "0" })); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries }; - } - default: - return Debug.assertNever(completion); - } - } - - function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { - const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. - const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. - const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => - ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span })); - return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; - } - function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier { - switch (extension) { - case Extension.Dts: return ScriptElementKindModifier.dtsModifier; - case Extension.Js: return ScriptElementKindModifier.jsModifier; - case Extension.Json: return ScriptElementKindModifier.jsonModifier; - case Extension.Jsx: return ScriptElementKindModifier.jsxModifier; - case Extension.Ts: return ScriptElementKindModifier.tsModifier; - case Extension.Tsx: return ScriptElementKindModifier.tsxModifier; - case undefined: return ScriptElementKindModifier.none; - default: - return Debug.assertNever(extension); - } - } - function jsdocCompletionInfo(entries: CompletionEntry[]): CompletionInfo { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; } @@ -284,22 +237,6 @@ namespace ts.Completions { }; } - function quote(text: string, preferences: UserPreferences): string { - if (/^\d+$/.test(text)) { - return text; - } - const quoted = JSON.stringify(text); - switch (preferences.quotePreference) { - case undefined: - case "double": - return quoted; - case "single": - return `'${stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"')}'`; - default: - return Debug.assertNever(preferences.quotePreference); - } - } - function isRecommendedCompletionMatch(localSymbol: Symbol, recommendedCompletion: Symbol | undefined, checker: TypeChecker): boolean { return localSymbol === recommendedCompletion || !!(localSymbol.flags & SymbolFlags.ExportValue) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; @@ -313,7 +250,7 @@ namespace ts.Completions { return origin && originIsExport(origin) ? stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols( + export function getCompletionEntriesFromSymbols( symbols: ReadonlyArray, entries: Push, location: Node | undefined, @@ -391,145 +328,6 @@ namespace ts.Completions { return entries; } - const enum StringLiteralCompletionKind { Paths, Properties, Types } - interface StringLiteralCompletionsFromProperties { - readonly kind: StringLiteralCompletionKind.Properties; - readonly symbols: ReadonlyArray; - readonly hasIndexSignature: boolean; - } - interface StringLiteralCompletionsFromTypes { - readonly kind: StringLiteralCompletionKind.Types; - readonly types: ReadonlyArray; - readonly isNewIdentifier: boolean; - } - type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; - function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { - const { parent } = node; - switch (parent.kind) { - case SyntaxKind.LiteralType: - switch (parent.parent.kind) { - case SyntaxKind.TypeReference: - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false }; - case SyntaxKind.IndexedAccessType: - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType)); - case SyntaxKind.ImportType: - return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case SyntaxKind.UnionType: { - if (!isTypeReferenceNode(parent.parent.parent)) return undefined; - const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode); - const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value)); - return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false }; - } - default: - return undefined; - } - - case SyntaxKind.PropertyAssignment: - if (isObjectLiteralExpression(parent.parent) && (parent).name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); - } - return fromContextualType(); - - case SyntaxKind.ElementAccessExpression: { - const { expression, argumentExpression } = parent as ElementAccessExpression; - if (node === argumentExpression) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); - } - return undefined; - } - - case SyntaxKind.CallExpression: - case SyntaxKind.NewExpression: - if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) { - const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); - } - // falls through (is `require("")` or `import("")`) - - case SyntaxKind.ImportDeclaration: - case SyntaxKind.ExportDeclaration: - case SyntaxKind.ExternalModuleReference: - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - - default: - return fromContextualType(); - } - - function fromContextualType(): StringLiteralCompletion { - // Get completion for string literal from string literal type - // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; - } - } - - function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { - return mapDefined(union.types, type => - type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); - } - - function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { - let isNewIdentifier = false; - - const uniques = createMap(); - const candidates: Signature[] = []; - checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); - const types = flatMap(candidates, candidate => { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return; - const type = checker.getParameterType(candidate, argumentInfo.argumentIndex); - isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String); - return getStringLiteralTypes(type, uniques); - }); - - return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier }; - } - - function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { - return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; - } - - function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { - if (!type) return emptyArray; - type = skipConstraint(type); - return type.isUnion() - ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) - : type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) - ? [type] - : emptyArray; - } - interface SymbolCompletion { type: "symbol"; symbol: Symbol; @@ -597,10 +395,7 @@ namespace ts.Completions { const contextToken = findPrecedingToken(position, sourceFile); if (isInString(sourceFile, position, contextToken)) { - const stringLiteralCompletions = !contextToken || !isStringLiteralLike(contextToken) - ? undefined - : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); - return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken!, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + return StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. @@ -640,7 +435,7 @@ namespace ts.Completions { return createCompletionDetails(name, ScriptElementKindModifier.none, kind, [displayPart(name, kind2)]); } - function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { + export function createCompletionDetailsForSymbol(symbol: Symbol, checker: TypeChecker, sourceFile: SourceFile, location: Node, cancellationToken: CancellationToken, codeActions?: CodeAction[], sourceDisplay?: SymbolDisplayPart[]): CompletionEntryDetails { const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, checker => SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, SemanticMeaning.All) @@ -648,24 +443,7 @@ namespace ts.Completions { return createCompletionDetails(symbol.name, SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } - function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker, cancellationToken: CancellationToken): CompletionEntryDetails | undefined { - switch (completion.kind) { - case StringLiteralCompletionKind.Paths: { - const match = find(completion.paths, p => p.name === name); - return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); - } - case StringLiteralCompletionKind.Properties: { - const match = find(completion.symbols, s => s.name === name); - return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); - } - case StringLiteralCompletionKind.Types: - return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined; - default: - return Debug.assertNever(completion); - } - } - - function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { + export function createCompletionDetails(name: string, kindModifiers: string, kind: ScriptElementKind, displayParts: SymbolDisplayPart[], documentation?: SymbolDisplayPart[], tags?: JSDocTagInfo[], codeActions?: CodeAction[], source?: SymbolDisplayPart[]): CompletionEntryDetails { return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source }; } @@ -732,7 +510,7 @@ namespace ts.Completions { } type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag }; - const enum CompletionKind { + export const enum CompletionKind { ObjectPropertyDeclaration, Global, PropertyAccess, @@ -786,28 +564,6 @@ namespace ts.Completions { } } - function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { - const { parent } = node; - switch (parent.kind) { - case SyntaxKind.NewExpression: - return checker.getContextualType(parent as NewExpression); - case SyntaxKind.BinaryExpression: { - const { left, operatorToken, right } = parent as BinaryExpression; - return isEqualityOperatorKind(operatorToken.kind) - ? checker.getTypeAtLocation(node === right ? left : right) - : checker.getContextualType(node); - } - case SyntaxKind.CaseClause: - return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined; - default: - return checker.getContextualType(node); - } - } - - function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type | undefined { - return checker.getTypeAtLocation(caseClause.parent.parent.expression); - } - function getFirstSymbolInChain(symbol: Symbol, enclosingDeclaration: Node, checker: TypeChecker): Symbol | undefined { const chain = checker.getAccessibleSymbolChain(symbol, enclosingDeclaration, /*meaning*/ SymbolFlags.All, /*useOnlyExternalAliasing*/ false); if (chain) return first(chain); @@ -2207,18 +1963,6 @@ namespace ts.Completions { return isIdentifier(node) ? node.originalKeywordKind || SyntaxKind.Unknown : node.kind; } - function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { - switch (kind) { - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - return true; - default: - return false; - } - } - /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node: Node, position: number): JSDocTag | undefined { const jsdoc = findAncestor(node, isJSDoc); @@ -2286,10 +2030,6 @@ namespace ts.Completions { return node.parent && isClassOrTypeElement(node.parent) && isObjectTypeDeclaration(node.parent.parent); } - function hasIndexSignature(type: Type): boolean { - return !!type.getStringIndexType() || !!type.getNumberIndexType(); - } - function isValidTrigger(sourceFile: SourceFile, triggerCharacter: CompletionsTriggerCharacter, contextToken: Node | undefined, position: number): boolean { switch (triggerCharacter) { case ".": @@ -2315,16 +2055,4 @@ namespace ts.Completions { function binaryExpressionMayBeOpenTag({ left }: BinaryExpression): boolean { return nodeIsMissing(left); } - - function isStringLiteralOrTemplate(node: Node): node is StringLiteralLike | TemplateExpression | TaggedTemplateExpression { - switch (node.kind) { - case SyntaxKind.StringLiteral: - case SyntaxKind.NoSubstitutionTemplateLiteral: - case SyntaxKind.TemplateExpression: - case SyntaxKind.TaggedTemplateExpression: - return true; - default: - return false; - } - } } diff --git a/src/services/pathCompletions.ts b/src/services/stringCompletions.ts similarity index 64% rename from src/services/pathCompletions.ts rename to src/services/stringCompletions.ts index 97ed722dd16..4726e06ec42 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/stringCompletions.ts @@ -1,11 +1,227 @@ /* @internal */ -namespace ts.Completions.PathCompletions { - export interface NameAndKind { +namespace ts.Completions.StringCompletions { + export function getStringLiteralCompletions(sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, log: Log, preferences: UserPreferences): CompletionInfo | undefined { + if (isInReferenceComment(sourceFile, position)) { + const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + return entries && convertPathCompletions(entries); + } + if (isInString(sourceFile, position, contextToken)) { + return !contextToken || !isStringLiteralLike(contextToken) + ? undefined + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host), sourceFile, checker, log, preferences); + } + } + + function convertStringLiteralCompletions(completion: StringLiteralCompletion | undefined, sourceFile: SourceFile, checker: TypeChecker, log: Log, preferences: UserPreferences): CompletionInfo | undefined { + if (completion === undefined) { + return undefined; + } + switch (completion.kind) { + case StringLiteralCompletionKind.Paths: + return convertPathCompletions(completion.paths); + case StringLiteralCompletionKind.Properties: { + const entries: CompletionEntry[] = []; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, ScriptTarget.ESNext, log, CompletionKind.String, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries }; + } + case StringLiteralCompletionKind.Types: { + const entries = completion.types.map(type => ({ name: type.value, kindModifiers: ScriptElementKindModifier.none, kind: ScriptElementKind.string, sortText: "0" })); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries }; + } + default: + return Debug.assertNever(completion); + } + } + + export function getStringLiteralCompletionDetails(name: string, sourceFile: SourceFile, position: number, contextToken: Node | undefined, checker: TypeChecker, options: CompilerOptions, host: LanguageServiceHost, cancellationToken: CancellationToken) { + if (!contextToken || !isStringLiteralLike(contextToken)) return undefined; + const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); + return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, checker, cancellationToken); + } + + function stringLiteralCompletionDetails(name: string, location: Node, completion: StringLiteralCompletion, sourceFile: SourceFile, checker: TypeChecker, cancellationToken: CancellationToken): CompletionEntryDetails | undefined { + switch (completion.kind) { + case StringLiteralCompletionKind.Paths: { + const match = find(completion.paths, p => p.name === name); + return match && createCompletionDetails(name, kindModifiersFromExtension(match.extension), match.kind, [textPart(name)]); + } + case StringLiteralCompletionKind.Properties: { + const match = find(completion.symbols, s => s.name === name); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case StringLiteralCompletionKind.Types: + return find(completion.types, t => t.value === name) ? createCompletionDetails(name, ScriptElementKindModifier.none, ScriptElementKind.typeElement, [textPart(name)]) : undefined; + default: + return Debug.assertNever(completion); + } + } + + function convertPathCompletions(pathCompletions: ReadonlyArray): CompletionInfo { + const isGlobalCompletion = false; // We don't want the editor to offer any other completions, such as snippets, inside a comment. + const isNewIdentifierLocation = true; // The user may type in a path that doesn't yet exist, creating a "new identifier" with respect to the collection of identifiers the server is aware of. + const entries = pathCompletions.map(({ name, kind, span, extension }): CompletionEntry => + ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: "0", replacementSpan: span })); + return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; + } + function kindModifiersFromExtension(extension: Extension | undefined): ScriptElementKindModifier { + switch (extension) { + case Extension.Dts: return ScriptElementKindModifier.dtsModifier; + case Extension.Js: return ScriptElementKindModifier.jsModifier; + case Extension.Json: return ScriptElementKindModifier.jsonModifier; + case Extension.Jsx: return ScriptElementKindModifier.jsxModifier; + case Extension.Ts: return ScriptElementKindModifier.tsModifier; + case Extension.Tsx: return ScriptElementKindModifier.tsxModifier; + case undefined: return ScriptElementKindModifier.none; + default: + return Debug.assertNever(extension); + } + } + + const enum StringLiteralCompletionKind { Paths, Properties, Types } + interface StringLiteralCompletionsFromProperties { + readonly kind: StringLiteralCompletionKind.Properties; + readonly symbols: ReadonlyArray; + readonly hasIndexSignature: boolean; + } + interface StringLiteralCompletionsFromTypes { + readonly kind: StringLiteralCompletionKind.Types; + readonly types: ReadonlyArray; + readonly isNewIdentifier: boolean; + } + type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; + function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { + const { parent } = node; + switch (parent.kind) { + case SyntaxKind.LiteralType: + switch (parent.parent.kind) { + case SyntaxKind.TypeReference: + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false }; + case SyntaxKind.IndexedAccessType: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType)); + case SyntaxKind.ImportType: + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + case SyntaxKind.UnionType: { + if (!isTypeReferenceNode(parent.parent.parent)) return undefined; + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode); + const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value)); + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false }; + } + default: + return undefined; + } + + case SyntaxKind.PropertyAssignment: + if (isObjectLiteralExpression(parent.parent) && (parent).name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); + } + return fromContextualType(); + + case SyntaxKind.ElementAccessExpression: { + const { expression, argumentExpression } = parent as ElementAccessExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); + } + return undefined; + } + + case SyntaxKind.CallExpression: + case SyntaxKind.NewExpression: + if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) { + const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through (is `require("")` or `import("")`) + + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + case SyntaxKind.ExternalModuleReference: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return { kind: StringLiteralCompletionKind.Paths, paths: getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; + + default: + return fromContextualType(); + } + + function fromContextualType(): StringLiteralCompletion { + // Get completion for string literal from string literal type + // i.e. var x: "hi" | "hello" = "/*completion position*/" + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; + } + } + + function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { + return mapDefined(union.types, type => + type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); + } + + function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { + let isNewIdentifier = false; + + const uniques = createMap(); + const candidates: Signature[] = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + const types = flatMap(candidates, candidate => { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return; + const type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String); + return getStringLiteralTypes(type, uniques); + }); + + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier }; + } + + function stringLiteralCompletionsFromProperties(type: Type | undefined): StringLiteralCompletionsFromProperties | undefined { + return type && { kind: StringLiteralCompletionKind.Properties, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } + + function getStringLiteralTypes(type: Type | undefined, uniques = createMap()): ReadonlyArray { + if (!type) return emptyArray; + type = skipConstraint(type); + return type.isUnion() + ? flatMap(type.types, t => getStringLiteralTypes(t, uniques)) + : type.isStringLiteral() && !(type.flags & TypeFlags.EnumLiteral) && addToSeen(uniques, type.value) + ? [type] + : emptyArray; + } + + interface NameAndKind { readonly name: string; readonly kind: ScriptElementKind.scriptElement | ScriptElementKind.directory | ScriptElementKind.externalModuleName; readonly extension: Extension | undefined; } - export interface PathCompletion extends NameAndKind { + interface PathCompletion extends NameAndKind { readonly span: TextSpan | undefined; } @@ -21,7 +237,7 @@ namespace ts.Completions.PathCompletions { return names.map(({ name, kind, extension }): PathCompletion => ({ name, kind, extension, span })); } - export function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { + function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): ReadonlyArray { return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); } @@ -343,7 +559,7 @@ namespace ts.Completions.PathCompletions { return nonRelativeModuleNames; } - export function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { + function getTripleSlashReferenceCompletion(sourceFile: SourceFile, position: number, compilerOptions: CompilerOptions, host: LanguageServiceHost): ReadonlyArray | undefined { const token = getTokenAtPosition(sourceFile, position); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); const range = commentRanges && find(commentRanges, commentRange => position >= commentRange.pos && position <= commentRange.end); diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 6f718b43730..66b1977ddc5 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -11,7 +11,7 @@ "types.ts", "utilities.ts", "classifier.ts", - "pathCompletions.ts", + "stringCompletions.ts", "completions.ts", "documentHighlights.ts", "documentRegistry.ts", diff --git a/src/services/utilities.ts b/src/services/utilities.ts index da026510c56..30c45620c1f 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1847,4 +1847,70 @@ namespace ts { if (idx === -1) idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + + export function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { + const { parent } = node; + switch (parent.kind) { + case SyntaxKind.NewExpression: + return checker.getContextualType(parent as NewExpression); + case SyntaxKind.BinaryExpression: { + const { left, operatorToken, right } = parent as BinaryExpression; + return isEqualityOperatorKind(operatorToken.kind) + ? checker.getTypeAtLocation(node === right ? left : right) + : checker.getContextualType(node); + } + case SyntaxKind.CaseClause: + return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined; + default: + return checker.getContextualType(node); + } + } + + export function quote(text: string, preferences: UserPreferences): string { + if (/^\d+$/.test(text)) { + return text; + } + const quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return `'${stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"')}'`; + default: + return Debug.assertNever(preferences.quotePreference); + } + } + + export function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { + switch (kind) { + case SyntaxKind.EqualsEqualsEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: + return true; + default: + return false; + } + } + + export function isStringLiteralOrTemplate(node: Node): node is StringLiteralLike | TemplateExpression | TaggedTemplateExpression { + switch (node.kind) { + case SyntaxKind.StringLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: + case SyntaxKind.TemplateExpression: + case SyntaxKind.TaggedTemplateExpression: + return true; + default: + return false; + } + } + + export function hasIndexSignature(type: Type): boolean { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + + export function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type | undefined { + return checker.getTypeAtLocation(caseClause.parent.parent.expression); + } } From 6fd6a04f2eabcbd468b80aac270b34bad24892e4 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Wed, 31 Oct 2018 07:25:43 -0700 Subject: [PATCH 170/262] Update user baselines (#28249) --- tests/baselines/reference/user/assert.log | 20 +++++++++---------- tests/baselines/reference/user/async.log | 2 +- .../reference/user/create-react-app.log | 16 +++++++-------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/tests/baselines/reference/user/assert.log b/tests/baselines/reference/user/assert.log index ab73398f14c..02b6f0a67a6 100644 --- a/tests/baselines/reference/user/assert.log +++ b/tests/baselines/reference/user/assert.log @@ -25,17 +25,17 @@ node_modules/assert/test.js(143,10): error TS2339: Property 'a' does not exist o node_modules/assert/test.js(149,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? node_modules/assert/test.js(157,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'never' has no compatible call signatures. node_modules/assert/test.js(161,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? -node_modules/assert/test.js(168,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(182,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(229,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(235,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(250,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(254,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(168,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(182,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(229,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(235,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(250,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(254,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. node_modules/assert/test.js(256,55): error TS2345: Argument of type 'TypeError' is not assignable to parameter of type 'string'. -node_modules/assert/test.js(262,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(279,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(285,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -node_modules/assert/test.js(320,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(262,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(279,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(285,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +node_modules/assert/test.js(320,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index ceb25237c7b..a255b270590 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -51,7 +51,7 @@ node_modules/async/autoInject.js(160,28): error TS2695: Left side of comma opera node_modules/async/autoInject.js(164,14): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/autoInject.js(168,6): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/cargo.js(62,12): error TS2304: Cannot find name 'AsyncFunction'. -node_modules/async/cargo.js(67,14): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +node_modules/async/cargo.js(67,14): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. node_modules/async/cargo.js(67,20): error TS1005: '}' expected. node_modules/async/cargo.js(92,11): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/compose.js(8,37): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/create-react-app.log b/tests/baselines/reference/user/create-react-app.log index 537770fe818..275a3140def 100644 --- a/tests/baselines/reference/user/create-react-app.log +++ b/tests/baselines/reference/user/create-react-app.log @@ -15,9 +15,9 @@ packages/babel-preset-react-app/index.js(123,17): error TS2307: Cannot find modu packages/babel-preset-react-app/index.js(130,17): error TS2307: Cannot find module '@babel/plugin-transform-regenerator'. packages/babel-preset-react-app/index.js(137,15): error TS2307: Cannot find module '@babel/plugin-syntax-dynamic-import'. packages/babel-preset-react-app/index.js(140,17): error TS2307: Cannot find module 'babel-plugin-transform-dynamic-import'. -packages/confusing-browser-globals/test.js(14,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/confusing-browser-globals/test.js(14,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/confusing-browser-globals/test.js(15,3): error TS2304: Cannot find name 'expect'. -packages/confusing-browser-globals/test.js(18,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/confusing-browser-globals/test.js(18,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/confusing-browser-globals/test.js(19,3): error TS2304: Cannot find name 'expect'. packages/create-react-app/createReactApp.js(37,37): error TS2307: Cannot find module 'validate-npm-package-name'. packages/create-react-app/createReactApp.js(47,24): error TS2307: Cannot find module 'tar-pack'. @@ -35,18 +35,18 @@ packages/react-dev-utils/FileSizeReporter.js(16,24): error TS2307: Cannot find m packages/react-dev-utils/WebpackDevServerUtils.js(9,25): error TS2307: Cannot find module 'address'. packages/react-dev-utils/WebpackDevServerUtils.js(14,24): error TS2307: Cannot find module 'detect-port-alt'. packages/react-dev-utils/WebpackDevServerUtils.js(15,24): error TS2307: Cannot find module 'is-root'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/react-dev-utils/__tests__/ignoredFiles.test.js(18,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(19,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/react-dev-utils/__tests__/ignoredFiles.test.js(26,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/react-dev-utils/__tests__/ignoredFiles.test.js(36,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(37,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/react-dev-utils/__tests__/ignoredFiles.test.js(46,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. packages/react-dev-utils/__tests__/ignoredFiles.test.js(53,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/browsersHelper.js(9,30): error TS2307: Cannot find module 'browserslist'. packages/react-dev-utils/browsersHelper.js(13,23): error TS2307: Cannot find module 'pkg-up'. From 878b7a21ce7324974d94a9777d349a5b8ab421a9 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 29 Oct 2018 15:40:14 -0700 Subject: [PATCH 171/262] Fix incorrect event --- src/server/session.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/session.ts b/src/server/session.ts index 49db5562992..da4808c31f6 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -576,7 +576,7 @@ namespace ts.server { break; case ProjectLoadingFinishEvent: const { project: finishProject } = event.data; - this.event({ projectName: finishProject.getProjectName() }, ProjectLoadingStartEvent); + this.event({ projectName: finishProject.getProjectName() }, ProjectLoadingFinishEvent); break; case LargeFileReferencedEvent: const { file, fileSize, maxFileSize } = event.data; From f7189e17f4ac118de2c5a9cbb44a06061f5771d6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 12:51:31 -0700 Subject: [PATCH 172/262] Some reorg in creating sessions for testing --- src/server/protocol.ts | 4 ++ .../unittests/tsserverProjectSystem.ts | 62 +++++++++++-------- 2 files changed, 40 insertions(+), 26 deletions(-) diff --git a/src/server/protocol.ts b/src/server/protocol.ts index aad7ba085de..acffd6bde5c 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2401,6 +2401,7 @@ namespace ts.server.protocol { */ export interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } export interface ConfigFileDiagnosticEventBody { @@ -2520,6 +2521,9 @@ namespace ts.server.protocol { maxFileSize: number; } + export type AnyEvent = RequestCompletedEvent | DiagnosticEvent | ConfigFileDiagnosticEvent | ProjectLanguageServiceStateEvent | TelemetryEvent | + ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | SurveyReadyEvent | LargeFileReferencedEvent; + /** * Arguments for reload request. */ diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9f569f46d4d..f266caf7f4d 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -330,12 +330,12 @@ namespace ts.projectSystem { return new TestSession({ ...sessionOptions, ...opts }); } - function createSessionWithEventTracking(host: server.ServerHost, eventName: T["eventName"], eventName2?: U["eventName"]) { - const events: (T | U)[] = []; + function createSessionWithEventTracking(host: server.ServerHost, eventName: T["eventName"], ...eventNames: T["eventName"][]) { + const events: T[] = []; const session = createSession(host, { eventHandler: e => { - if (e.eventName === eventName || (eventName2 && e.eventName === eventName2)) { - events.push(e as T | U); + if (e.eventName === eventName || eventNames.some(eventName => e.eventName === eventName)) { + events.push(e as T); } } }); @@ -343,6 +343,33 @@ namespace ts.projectSystem { return { session, events }; } + function createSessionWithDefaultEventHandler(host: TestServerHost, eventName: T["event"], opts: Partial = {}, ...eventNames: T["event"][]) { + const session = createSession(host, { canUseEvents: true, ...opts }); + + return { + session, + getEvents, + clearEvents + }; + + function getEvents() { + const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; + return filter( + map( + host.getOutput(), s => convertToObject( + parseJsonText("json.json", s.replace(outputEventRegex, "")), + [] + ) + ), + e => e.event === eventName || eventNames.some(eventName => e.event === eventName) + ) as T[]; + } + + function clearEvents() { + session.clearMessages(); + } + } + interface CreateProjectServiceParameters { cancellationToken?: HostCancellationToken; logger?: server.Logger; @@ -8062,15 +8089,7 @@ namespace ts.projectSystem { verifyProjectsUpdatedInBackgroundEvent(createSessionWithProjectChangedEventHandler); function createSessionWithProjectChangedEventHandler(host: TestServerHost): ProjectsUpdatedInBackgroundEventVerifier { - const projectChangedEvents: server.ProjectsUpdatedInBackgroundEvent[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.ProjectsUpdatedInBackgroundEvent) { - projectChangedEvents.push(e); - } - } - }); - + const { session, events: projectChangedEvents } = createSessionWithEventTracking(host, server.ProjectsUpdatedInBackgroundEvent); return { session, verifyProjectsUpdatedInBackgroundEventHandler, @@ -8110,7 +8129,7 @@ namespace ts.projectSystem { function createSessionThatUsesEvents(host: TestServerHost, noGetErrOnBackgroundUpdate?: boolean): ProjectsUpdatedInBackgroundEventVerifier { - const session = createSession(host, { canUseEvents: true, noGetErrOnBackgroundUpdate }); + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, server.ProjectsUpdatedInBackgroundEvent, { noGetErrOnBackgroundUpdate }); return { session, @@ -8124,16 +8143,7 @@ namespace ts.projectSystem { openFiles: e.data.openFiles }; }); - const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; - const events: protocol.ProjectsUpdatedInBackgroundEvent[] = filter( - map( - host.getOutput(), s => convertToObject( - parseJsonText("json.json", s.replace(outputEventRegex, "")), - [] - ) - ), - e => e.event === server.ProjectsUpdatedInBackgroundEvent - ); + const events = getEvents(); assert.equal(events.length, expectedEvents.length, `Incorrect number of events Actual: ${map(events, e => e.body)} Expected: ${expectedEvents}`); forEach(events, (actualEvent, i) => { const expectedEvent = expectedEvents[i]; @@ -8141,7 +8151,7 @@ namespace ts.projectSystem { }); // Verified the events, reset them - session.clearMessages(); + clearEvents(); if (events.length) { host.checkTimeoutQueueLength(noGetErrOnBackgroundUpdate ? 0 : 1); // Error checking queued only if not noGetErrOnBackgroundUpdate @@ -9467,7 +9477,7 @@ export const x = 10;` } return originalReadFile.call(host, file); }; - const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); const service = session.getProjectService(); return { host, session, verifyEvent, verifyEventWithOpenTs, service, events }; From 0ef844ff2b204552dad7d3079e0480ac77173674 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 31 Oct 2018 13:21:35 -0700 Subject: [PATCH 173/262] Avoid this-instantiation if not necessary for relationship (#28263) --- src/compiler/checker.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ee1d06112df..7f197370048 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12065,12 +12065,15 @@ namespace ts { return result; } } - else { - const instantiated = getTypeWithThisArgument(constraint, source); - if (result = isRelatedTo(instantiated, target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + // hi-speed no-this-instantiation check (less accurate, but avoids costly `this`-instantiation when the constraint will suffice), see #28231 for report on why this is needed + else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, isIntersectionConstituent)) { errorInfo = saveErrorInfo; return result; - } + } + // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, isIntersectionConstituent)) { + errorInfo = saveErrorInfo; + return result; } } else if (source.flags & TypeFlags.Index) { From 677f04b165a6a5b5c5bf787824fa5984271f6e7f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 13:37:00 -0700 Subject: [PATCH 174/262] Test to verify project loading events with default event handler --- .../unittests/tsserverProjectSystem.ts | 271 ++++++++++-------- 1 file changed, 155 insertions(+), 116 deletions(-) diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index f266caf7f4d..9722905bbdb 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -9467,141 +9467,180 @@ export const x = 10;` const configBPath = `${projectRoot}/b/tsconfig.json`; const files = [libFile, aTs, configA]; - function createSessionWithEventHandler(files: ReadonlyArray) { - const host = createServerHost(files); + function verifyProjectLoadingStartAndFinish(createSession: (host: TestServerHost) => { + session: TestSession; + getNumberOfEvents: () => number; + clearEvents: () => void; + verifyProjectLoadEvents: (expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) => void; + }) { + function createSessionToVerifyEvent(files: ReadonlyArray) { + const host = createServerHost(files); + const originalReadFile = host.readFile; + const { session, getNumberOfEvents, clearEvents, verifyProjectLoadEvents } = createSession(host); + host.readFile = file => { + if (file === configA.path || file === configBPath) { + assert.equal(getNumberOfEvents(), 1, "Event for loading is sent before reading config file"); + } + return originalReadFile.call(host, file); + }; + const service = session.getProjectService(); + return { host, session, verifyEvent, verifyEventWithOpenTs, service, getNumberOfEvents }; - const originalReadFile = host.readFile; - host.readFile = file => { - if (file === configA.path || file === configBPath) { - assert.equal(events.length, 1, "Event for loading is sent before reading config file"); + function verifyEvent(project: server.Project, reason: string) { + verifyProjectLoadEvents([ + { eventName: server.ProjectLoadingStartEvent, data: { project, reason } }, + { eventName: server.ProjectLoadingFinishEvent, data: { project } } + ]); + clearEvents(); } - return originalReadFile.call(host, file); - }; - const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); - const service = session.getProjectService(); - return { host, session, verifyEvent, verifyEventWithOpenTs, service, events }; - function verifyEvent(project: server.Project, reason: string) { - assert.deepEqual(events, [ - { eventName: server.ProjectLoadingStartEvent, data: { project, reason } }, - { eventName: server.ProjectLoadingFinishEvent, data: { project } } - ]); - events.length = 0; + function verifyEventWithOpenTs(file: File, configPath: string, configuredProjects: number) { + openFilesForSession([file], session); + checkNumberOfProjects(service, { configuredProjects }); + const project = service.configuredProjects.get(configPath)!; + assert.isDefined(project); + verifyEvent(project, `Creating possible configured project for ${file.path} to open`); + } } - function verifyEventWithOpenTs(file: File, configPath: string, configuredProjects: number) { - openFilesForSession([file], session); - checkNumberOfProjects(service, { configuredProjects }); - const project = service.configuredProjects.get(configPath)!; - assert.isDefined(project); - verifyEvent(project, `Creating possible configured project for ${file.path} to open`); - } - } + it("when project is created by open file", () => { + const bTs: File = { + path: bTsPath, + content: "export class B {}" + }; + const configB: File = { + path: configBPath, + content: "{}" + }; + const { verifyEventWithOpenTs } = createSessionToVerifyEvent(files.concat(bTs, configB)); + verifyEventWithOpenTs(aTs, configA.path, 1); + verifyEventWithOpenTs(bTs, configB.path, 2); + }); - it("when project is created by open file", () => { - const bTs: File = { - path: bTsPath, - content: "export class B {}" - }; - const configB: File = { - path: configBPath, - content: "{}" - }; - const { verifyEventWithOpenTs } = createSessionWithEventHandler(files.concat(bTs, configB)); - verifyEventWithOpenTs(aTs, configA.path, 1); - verifyEventWithOpenTs(bTs, configB.path, 2); - }); + it("when change is detected in the config file", () => { + const { host, verifyEvent, verifyEventWithOpenTs, service } = createSessionToVerifyEvent(files); + verifyEventWithOpenTs(aTs, configA.path, 1); - it("when change is detected in the config file", () => { - const { host, verifyEvent, verifyEventWithOpenTs, service } = createSessionWithEventHandler(files); - verifyEventWithOpenTs(aTs, configA.path, 1); + host.writeFile(configA.path, configA.content); + host.checkTimeoutQueueLengthAndRun(2); + const project = service.configuredProjects.get(configA.path)!; + verifyEvent(project, `Change in config file detected`); + }); - host.writeFile(configA.path, configA.content); - host.checkTimeoutQueueLengthAndRun(2); - const project = service.configuredProjects.get(configA.path)!; - verifyEvent(project, `Change in config file detected`); - }); - - it("when opening original location project", () => { - const aDTs: File = { - path: `${projectRoot}/a/a.d.ts`, - content: `export declare class A { + it("when opening original location project", () => { + const aDTs: File = { + path: `${projectRoot}/a/a.d.ts`, + content: `export declare class A { } //# sourceMappingURL=a.d.ts.map ` - }; - const aDTsMap: File = { - path: `${projectRoot}/a/a.d.ts.map`, - content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` - }; - const bTs: File = { - path: bTsPath, - content: `import {A} from "../a/a"; new A();` - }; - const configB: File = { - path: configBPath, - content: JSON.stringify({ - references: [{ path: "../a" }] - }) - }; + }; + const aDTsMap: File = { + path: `${projectRoot}/a/a.d.ts.map`, + content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` + }; + const bTs: File = { + path: bTsPath, + content: `import {A} from "../a/a"; new A();` + }; + const configB: File = { + path: configBPath, + content: JSON.stringify({ + references: [{ path: "../a" }] + }) + }; - const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionWithEventHandler(files.concat(aDTs, aDTsMap, bTs, configB)); - verifyEventWithOpenTs(bTs, configB.path, 1); + const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionToVerifyEvent(files.concat(aDTs, aDTsMap, bTs, configB)); + verifyEventWithOpenTs(bTs, configB.path, 1); - session.executeCommandSeq({ - command: protocol.CommandTypes.References, - arguments: { - file: bTs.path, - ...protocolLocationFromSubstring(bTs.content, "A()") - } + session.executeCommandSeq({ + command: protocol.CommandTypes.References, + arguments: { + file: bTs.path, + ...protocolLocationFromSubstring(bTs.content, "A()") + } + }); + + checkNumberOfProjects(service, { configuredProjects: 2 }); + const project = service.configuredProjects.get(configA.path)!; + assert.isDefined(project); + verifyEvent(project, `Creating project for original file: ${aTs.path} for location: ${aDTs.path}`); }); - checkNumberOfProjects(service, { configuredProjects: 2 }); - const project = service.configuredProjects.get(configA.path)!; - assert.isDefined(project); - verifyEvent(project, `Creating project for original file: ${aTs.path} for location: ${aDTs.path}`); + describe("with external projects and config files ", () => { + const projectFileName = `${projectRoot}/a/project.csproj`; + + function createSession(lazyConfiguredProjectsFromExternalProject: boolean) { + const { session, service, verifyEvent: verifyEventWorker, getNumberOfEvents } = createSessionToVerifyEvent(files); + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); + service.openExternalProject({ + projectFileName, + rootFiles: toExternalFiles([aTs.path, configA.path]), + options: {} + }); + checkNumberOfProjects(service, { configuredProjects: 1 }); + return { session, service, verifyEvent, getNumberOfEvents }; + + function verifyEvent() { + const projectA = service.configuredProjects.get(configA.path)!; + assert.isDefined(projectA); + verifyEventWorker(projectA, `Creating configured project in external project: ${projectFileName}`); + } + } + + it("when lazyConfiguredProjectsFromExternalProject is false", () => { + const { verifyEvent } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ false); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is true and file is opened", () => { + const { verifyEvent, getNumberOfEvents, session } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(getNumberOfEvents(), 0); + + openFilesForSession([aTs], session); + verifyEvent(); + }); + + it("when lazyConfiguredProjectsFromExternalProject is disabled", () => { + const { verifyEvent, getNumberOfEvents, service } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); + assert.equal(getNumberOfEvents(), 0); + + service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } }); + verifyEvent(); + }); + }); + } + + describe("when using event handler", () => { + verifyProjectLoadingStartAndFinish(host => { + const { session, events } = createSessionWithEventTracking(host, server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent); + return { + session, + getNumberOfEvents: () => events.length, + clearEvents: () => events.length = 0, + verifyProjectLoadEvents: expected => assert.deepEqual(events, expected) + }; + }); }); - describe("with external projects and config files ", () => { - const projectFileName = `${projectRoot}/a/project.csproj`; + describe("when using default event handler", () => { + verifyProjectLoadingStartAndFinish(host => { + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, server.ProjectLoadingStartEvent, {}, server.ProjectLoadingFinishEvent); + return { + session, + getNumberOfEvents: () => getEvents().length, + clearEvents, + verifyProjectLoadEvents + }; - function createSession(lazyConfiguredProjectsFromExternalProject: boolean) { - const { session, service, verifyEvent: verifyEventWorker, events } = createSessionWithEventHandler(files); - service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject } }); - service.openExternalProject({ - projectFileName, - rootFiles: toExternalFiles([aTs.path, configA.path]), - options: {} - }); - checkNumberOfProjects(service, { configuredProjects: 1 }); - return { session, service, verifyEvent, events }; - - function verifyEvent() { - const projectA = service.configuredProjects.get(configA.path)!; - assert.isDefined(projectA); - verifyEventWorker(projectA, `Creating configured project in external project: ${projectFileName}`); + function verifyProjectLoadEvents(expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) { + const actual = getEvents().map(e => ({ eventName: e.event, data: e.body })); + const mappedExpected = expected.map(e => { + const { project, ...rest } = e.data; + return { eventName: e.eventName, data: { projectName: project.getProjectName(), ...rest } }; + }); + assert.deepEqual(actual, mappedExpected); } - } - - it("when lazyConfiguredProjectsFromExternalProject is false", () => { - const { verifyEvent } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ false); - verifyEvent(); - }); - - it("when lazyConfiguredProjectsFromExternalProject is true and file is opened", () => { - const { verifyEvent, events, session } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); - assert.equal(events.length, 0); - - openFilesForSession([aTs], session); - verifyEvent(); - }); - - it("when lazyConfiguredProjectsFromExternalProject is disabled", () => { - const { verifyEvent, events, service } = createSession(/*lazyConfiguredProjectsFromExternalProject*/ true); - assert.equal(events.length, 0); - - service.setHostConfiguration({ preferences: { lazyConfiguredProjectsFromExternalProject: false } }); - verifyEvent(); }); }); }); From 3a2f7c0df15c9764f2f2ae923a8c23524d2e6fd5 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 31 Oct 2018 14:09:12 -0700 Subject: [PATCH 175/262] Allow intersections of readonlys to be assignable to a readonly intersection (#28218) * Allow intersections of readonlys to be assignable to a readonly intersection * Add real motivating react example to test suite --- src/compiler/checker.ts | 4 +- ...phicMappedTypeIntersectionAssignability.js | 16 ++++++ ...appedTypeIntersectionAssignability.symbols | 33 ++++++++++++ ...cMappedTypeIntersectionAssignability.types | 28 ++++++++++ .../reactReadonlyHOCAssignabilityReal.js | 53 +++++++++++++++++++ .../reactReadonlyHOCAssignabilityReal.symbols | 36 +++++++++++++ .../reactReadonlyHOCAssignabilityReal.types | 32 +++++++++++ ...phicMappedTypeIntersectionAssignability.ts | 8 +++ .../reactReadonlyHOCAssignabilityReal.tsx | 12 +++++ 9 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.js create mode 100644 tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.symbols create mode 100644 tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.types create mode 100644 tests/baselines/reference/reactReadonlyHOCAssignabilityReal.js create mode 100644 tests/baselines/reference/reactReadonlyHOCAssignabilityReal.symbols create mode 100644 tests/baselines/reference/reactReadonlyHOCAssignabilityReal.types create mode 100644 tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts create mode 100644 tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7f197370048..2418c75f0cb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12036,13 +12036,15 @@ namespace ts { return Ternary.True; } // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (!isGenericMappedType(source) && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); const templateType = getTemplateTypeFromMappedType(target); if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { return result; } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } } diff --git a/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.js b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.js new file mode 100644 index 00000000000..80f0e8d1dbf --- /dev/null +++ b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.js @@ -0,0 +1,16 @@ +//// [homomorphicMappedTypeIntersectionAssignability.ts] +function f( + a: { weak?: string } & Readonly & { name: "ok" }, + b: Readonly, + c: Readonly & { name: string }) { + c = a; // Works + b = a; // Should also work +} + + +//// [homomorphicMappedTypeIntersectionAssignability.js] +"use strict"; +function f(a, b, c) { + c = a; // Works + b = a; // Should also work +} diff --git a/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.symbols b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.symbols new file mode 100644 index 00000000000..fae1f423be3 --- /dev/null +++ b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.symbols @@ -0,0 +1,33 @@ +=== tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts === +function f( +>f : Symbol(f, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 0)) +>TType : Symbol(TType, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 11)) + + a: { weak?: string } & Readonly & { name: "ok" }, +>a : Symbol(a, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 18)) +>weak : Symbol(weak, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 1, 8)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>TType : Symbol(TType, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 11)) +>name : Symbol(name, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 1, 46)) + + b: Readonly, +>b : Symbol(b, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 1, 60)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>TType : Symbol(TType, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 11)) +>name : Symbol(name, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 2, 25)) + + c: Readonly & { name: string }) { +>c : Symbol(c, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 2, 42)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>TType : Symbol(TType, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 11)) +>name : Symbol(name, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 3, 26)) + + c = a; // Works +>c : Symbol(c, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 2, 42)) +>a : Symbol(a, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 18)) + + b = a; // Should also work +>b : Symbol(b, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 1, 60)) +>a : Symbol(a, Decl(homomorphicMappedTypeIntersectionAssignability.ts, 0, 18)) +} + diff --git a/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.types b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.types new file mode 100644 index 00000000000..eafa5586fb1 --- /dev/null +++ b/tests/baselines/reference/homomorphicMappedTypeIntersectionAssignability.types @@ -0,0 +1,28 @@ +=== tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts === +function f( +>f : (a: { weak?: string | undefined; } & Readonly & { name: "ok"; }, b: Readonly, c: Readonly & { name: string; }) => void + + a: { weak?: string } & Readonly & { name: "ok" }, +>a : { weak?: string | undefined; } & Readonly & { name: "ok"; } +>weak : string | undefined +>name : "ok" + + b: Readonly, +>b : Readonly +>name : string + + c: Readonly & { name: string }) { +>c : Readonly & { name: string; } +>name : string + + c = a; // Works +>c = a : { weak?: string | undefined; } & Readonly & { name: "ok"; } +>c : Readonly & { name: string; } +>a : { weak?: string | undefined; } & Readonly & { name: "ok"; } + + b = a; // Should also work +>b = a : { weak?: string | undefined; } & Readonly & { name: "ok"; } +>b : Readonly +>a : { weak?: string | undefined; } & Readonly & { name: "ok"; } +} + diff --git a/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.js b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.js new file mode 100644 index 00000000000..57f6680e098 --- /dev/null +++ b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.js @@ -0,0 +1,53 @@ +//// [reactReadonlyHOCAssignabilityReal.tsx] +/// +import * as React from "react"; + +function myHigherOrderComponent

(Inner: React.ComponentClass

): React.ComponentClass

{ + return class OuterComponent extends React.Component

{ + render() { + return ; + } + }; +} + +//// [reactReadonlyHOCAssignabilityReal.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +exports.__esModule = true; +/// +var React = require("react"); +function myHigherOrderComponent(Inner) { + return /** @class */ (function (_super) { + __extends(OuterComponent, _super); + function OuterComponent() { + return _super !== null && _super.apply(this, arguments) || this; + } + OuterComponent.prototype.render = function () { + return React.createElement(Inner, __assign({}, this.props, { name: "Matt" })); + }; + return OuterComponent; + }(React.Component)); +} diff --git a/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.symbols b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.symbols new file mode 100644 index 00000000000..c0fc1dbafd0 --- /dev/null +++ b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx === +/// +import * as React from "react"; +>React : Symbol(React, Decl(reactReadonlyHOCAssignabilityReal.tsx, 1, 6)) + +function myHigherOrderComponent

(Inner: React.ComponentClass

): React.ComponentClass

{ +>myHigherOrderComponent : Symbol(myHigherOrderComponent, Decl(reactReadonlyHOCAssignabilityReal.tsx, 1, 31)) +>P : Symbol(P, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 32)) +>Inner : Symbol(Inner, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 35)) +>React : Symbol(React, Decl(reactReadonlyHOCAssignabilityReal.tsx, 1, 6)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react16.d.ts, 421, 9)) +>P : Symbol(P, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 32)) +>name : Symbol(name, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 68)) +>React : Symbol(React, Decl(reactReadonlyHOCAssignabilityReal.tsx, 1, 6)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react16.d.ts, 421, 9)) +>P : Symbol(P, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 32)) + + return class OuterComponent extends React.Component

{ +>OuterComponent : Symbol(OuterComponent, Decl(reactReadonlyHOCAssignabilityReal.tsx, 4, 10)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(reactReadonlyHOCAssignabilityReal.tsx, 1, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>P : Symbol(P, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 32)) + + render() { +>render : Symbol(OuterComponent.render, Decl(reactReadonlyHOCAssignabilityReal.tsx, 4, 60)) + + return ; +>Inner : Symbol(Inner, Decl(reactReadonlyHOCAssignabilityReal.tsx, 3, 35)) +>this.props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) +>this : Symbol(OuterComponent, Decl(reactReadonlyHOCAssignabilityReal.tsx, 4, 10)) +>props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) +>name : Symbol(name, Decl(reactReadonlyHOCAssignabilityReal.tsx, 6, 41)) + } + }; +} diff --git a/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.types b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.types new file mode 100644 index 00000000000..1f67ab5adf9 --- /dev/null +++ b/tests/baselines/reference/reactReadonlyHOCAssignabilityReal.types @@ -0,0 +1,32 @@ +=== tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx === +/// +import * as React from "react"; +>React : typeof React + +function myHigherOrderComponent

(Inner: React.ComponentClass

): React.ComponentClass

{ +>myHigherOrderComponent :

(Inner: React.ComponentClass

) => React.ComponentClass +>Inner : React.ComponentClass

+>React : any +>name : string +>React : any + + return class OuterComponent extends React.Component

{ +>class OuterComponent extends React.Component

{ render() { return ; } } : typeof OuterComponent +>OuterComponent : typeof OuterComponent +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>Inner : React.ComponentClass

+>this.props : Readonly<{ children?: React.ReactNode; }> & Readonly

+>this : this +>props : Readonly<{ children?: React.ReactNode; }> & Readonly

+>name : "Matt" + } + }; +} diff --git a/tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts b/tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts new file mode 100644 index 00000000000..f4f452e1156 --- /dev/null +++ b/tests/cases/compiler/homomorphicMappedTypeIntersectionAssignability.ts @@ -0,0 +1,8 @@ +// @strict: true +function f( + a: { weak?: string } & Readonly & { name: "ok" }, + b: Readonly, + c: Readonly & { name: string }) { + c = a; // Works + b = a; // Should also work +} diff --git a/tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx b/tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx new file mode 100644 index 00000000000..c573f699beb --- /dev/null +++ b/tests/cases/compiler/reactReadonlyHOCAssignabilityReal.tsx @@ -0,0 +1,12 @@ +// @strict: true +// @jsx: react +/// +import * as React from "react"; + +function myHigherOrderComponent

(Inner: React.ComponentClass

): React.ComponentClass

{ + return class OuterComponent extends React.Component

{ + render() { + return ; + } + }; +} \ No newline at end of file From 78174657e7cde49dd5c0b0e81aac0c4908bb96a6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 15:03:42 -0700 Subject: [PATCH 176/262] Do not add source files to container only project --- src/compiler/program.ts | 18 ++++++++++-------- .../unittests/tsserverProjectSystem.ts | 2 ++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index e2f743818f2..157ea0ed959 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -694,12 +694,14 @@ namespace ts { if (!resolvedProjectReferences) { resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } - for (const parsedRef of resolvedProjectReferences) { - if (parsedRef) { - const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; - if (out) { - const dtsOutfile = changeExtension(out, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (rootNames.length) { + for (const parsedRef of resolvedProjectReferences) { + if (parsedRef) { + const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + const dtsOutfile = changeExtension(out, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } } } @@ -708,7 +710,7 @@ namespace ts { forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false)); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - const typeReferences: string[] = getAutomaticTypeDirectiveNames(options, host); + const typeReferences: string[] = rootNames.length ? getAutomaticTypeDirectiveNames(options, host) : emptyArray; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side @@ -724,7 +726,7 @@ namespace ts { // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file const defaultLibraryFileName = getDefaultLibraryFileName(); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9f569f46d4d..87766f7f1ba 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10520,6 +10520,8 @@ declare class TestLib { }).response; assert.deepEqual(semanticDiagnostics, []); }); + const containerProject = service.configuredProjects.get(containerConfig.path)!; + checkProjectActualFiles(containerProject, [containerConfig.path]); }); }); From a373029f54e8703582c3f13c2fa6fd79dd5437b6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 15:10:08 -0700 Subject: [PATCH 177/262] Public API --- src/server/protocol.ts | 1 + tests/baselines/reference/api/tsserverlibrary.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/server/protocol.ts b/src/server/protocol.ts index acffd6bde5c..e956290181a 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -2521,6 +2521,7 @@ namespace ts.server.protocol { maxFileSize: number; } + /*@internal*/ export type AnyEvent = RequestCompletedEvent | DiagnosticEvent | ConfigFileDiagnosticEvent | ProjectLanguageServiceStateEvent | TelemetryEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | SurveyReadyEvent | LargeFileReferencedEvent; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index ccc9557e948..b5ef0cac750 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -7486,6 +7486,7 @@ declare namespace ts.server.protocol { */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } interface ConfigFileDiagnosticEventBody { /** From efe5dd6b6dfb0bf3be9dbf8f440c199b641d2c2a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 29 Oct 2018 15:39:02 -0700 Subject: [PATCH 178/262] Handle case sensitivity correctly in source map decoder --- src/compiler/sourcemapDecoder.ts | 5 +++-- src/services/services.ts | 2 +- src/services/sourcemaps.ts | 10 ++++++++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/compiler/sourcemapDecoder.ts b/src/compiler/sourcemapDecoder.ts index 28cbbe39cf5..dd0d65c8092 100644 --- a/src/compiler/sourcemapDecoder.ts +++ b/src/compiler/sourcemapDecoder.ts @@ -57,6 +57,7 @@ namespace ts.sourcemaps { fileExists(path: string): boolean; getCanonicalFileName(path: string): string; log(text: string): void; + useCaseSensitiveFileNames: boolean; } export function decode(host: SourceMapDecodeHost, mapPath: string, map: SourceMapData, program?: Program, fallbackCache = createSourceFileLikeCache(host)): SourceMapper { @@ -79,7 +80,7 @@ namespace ts.sourcemaps { // if no exact match, closest is 2's compliment of result targetIndex = ~targetIndex; } - if (!maps[targetIndex] || comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + if (!maps[targetIndex] || comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot, !host.useCaseSensitiveFileNames) !== 0) { return loc; } return { fileName: toPath(map.file!, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos @@ -129,7 +130,7 @@ namespace ts.sourcemaps { } function compareProcessedPositionSourcePositions(a: ProcessedSourceMapPosition, b: ProcessedSourceMapPosition) { - return comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + return comparePaths(a.sourcePath, b.sourcePath, sourceRoot, !host.useCaseSensitiveFileNames) || compareValues(a.sourcePosition, b.sourcePosition); } diff --git a/src/services/services.ts b/src/services/services.ts index 4367bd11985..afcdc7b4f16 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1139,7 +1139,7 @@ namespace ts { const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - const sourceMapper = getSourceMapper(getCanonicalFileName, currentDirectory, log, host, () => program); + const sourceMapper = getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, () => program); function getValidSourceFile(fileName: string): SourceFile { const sourceFile = program.getSourceFile(fileName); diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index 1833c415be4..25e6fb9c124 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -13,12 +13,13 @@ namespace ts { } export function getSourceMapper( - getCanonicalFileName: GetCanonicalFileName, + useCaseSensitiveFileNames: boolean, currentDirectory: string, log: (message: string) => void, host: LanguageServiceHost, getProgram: () => Program, ): SourceMapper { + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); let sourcemappedFileCache: SourceFileLikeCache; return { tryGetOriginalLocation, tryGetGeneratedLocation, toLineColumnOffset, clearCache }; @@ -56,6 +57,7 @@ namespace ts { return file.sourceMapper = sourcemaps.decode({ readFile: s => host.readFile!(s), // TODO: GH#18217 fileExists: s => host.fileExists!(s), // TODO: GH#18217 + useCaseSensitiveFileNames, getCanonicalFileName, log, }, mapFileName, maps, getProgram(), sourcemappedFileCache); @@ -105,7 +107,11 @@ namespace ts { function tryGetGeneratedLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { const program = getProgram(); - const declarationPath = getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + const options = program.getCompilerOptions(); + const outPath = options.outFile || options.out; + const declarationPath = outPath ? + removeFileExtension(outPath) + Extension.Dts : + getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; const declarationFile = getFile(declarationPath); if (!declarationFile) return undefined; From 9f844c4b084b52451fe99b667c109d907ef118f2 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 15:39:31 -0700 Subject: [PATCH 179/262] Test to verify that file with --out and case mismatch works with source map --- .../unittests/tsserverProjectSystem.ts | 46 ++++++++++++++++--- .../container/compositeExec/tsconfig.json | 3 +- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9f569f46d4d..28d39ccf032 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10481,13 +10481,15 @@ declare class TestLib { TestFSWithWatch.getTsBuildProjectFile(project, "index.ts"), ]; } - it("does not error on container only project", () => { - const project = "container"; - const containerLib = getProjectFiles("container/lib"); - const containerExec = getProjectFiles("container/exec"); - const containerCompositeExec = getProjectFiles("container/compositeExec"); - const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); - const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; + + const project = "container"; + const containerLib = getProjectFiles("container/lib"); + const containerExec = getProjectFiles("container/exec"); + const containerCompositeExec = getProjectFiles("container/compositeExec"); + const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); + const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; + + function createHost() { const host = createServerHost(files); // ts build should succeed @@ -10495,6 +10497,12 @@ declare class TestLib { solutionBuilder.buildAllProjects(); assert.equal(host.getOutput().length, 0); + return host; + } + + it("does not error on container only project", () => { + const host = createHost(); + // Open external project for the folder const session = createSession(host); const service = session.getProjectService(); @@ -10521,6 +10529,30 @@ declare class TestLib { assert.deepEqual(semanticDiagnostics, []); }); }); + + it("can successfully find references with --out options", () => { + const host = createHost(); + const session = createSession(host); + openFilesForSession([containerCompositeExec[1]], session); + const service = session.getProjectService(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const locationOfMyConst = protocolLocationFromSubstring(containerCompositeExec[1].content, "myConst"); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.Rename, + arguments: { + file: containerCompositeExec[1].path, + ...locationOfMyConst + } + }).response as protocol.RenameResponseBody; + + + const myConstLen = "myConst".length; + const locationOfMyConstInLib = protocolLocationFromSubstring(containerLib[1].content, "myConst"); + assert.deepEqual(response.locs, [ + { file: containerCompositeExec[1].path, locs: [{ start: locationOfMyConst, end: { line: locationOfMyConst.line, offset: locationOfMyConst.offset + myConstLen } }] }, + { file: containerLib[1].path, locs: [{ start: locationOfMyConstInLib, end: { line: locationOfMyConstInLib.line, offset: locationOfMyConstInLib.offset + myConstLen } }] } + ]); + }); }); describe("tsserverProjectSystem duplicate packages", () => { diff --git a/tests/projects/container/compositeExec/tsconfig.json b/tests/projects/container/compositeExec/tsconfig.json index f28a9e44eee..4f44b8a562d 100644 --- a/tests/projects/container/compositeExec/tsconfig.json +++ b/tests/projects/container/compositeExec/tsconfig.json @@ -1,7 +1,8 @@ { "compilerOptions": { "outFile": "../built/local/compositeExec.js", - "composite": true + "composite": true, + "declarationMap": true }, "files": [ "index.ts" From 851f739c8248368c3345724ca2aaeca96a36f526 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 15:41:07 -0700 Subject: [PATCH 180/262] Dont ignore libs since that could result in unexpected error --- src/compiler/program.ts | 2 +- src/testRunner/unittests/tsserverProjectSystem.ts | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 157ea0ed959..ca8731a533f 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -726,7 +726,7 @@ namespace ts { // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (rootNames.length && !skipDefaultLib) { + if (!skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file const defaultLibraryFileName = getDefaultLibraryFileName(); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 87766f7f1ba..c4dc4b9216a 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10521,7 +10521,12 @@ declare class TestLib { assert.deepEqual(semanticDiagnostics, []); }); const containerProject = service.configuredProjects.get(containerConfig.path)!; - checkProjectActualFiles(containerProject, [containerConfig.path]); + checkProjectActualFiles(containerProject, [containerConfig.path, libFile.path]); + const optionsDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.CompilerOptionsDiagnosticsFull, + arguments: { projectFileName: containerProject.projectName } + }).response; + assert.deepEqual(optionsDiagnostics, []); }); }); From a4a1bed88bdcb160eff032790f05629f9fa955b4 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 31 Oct 2018 15:57:09 -0700 Subject: [PATCH 181/262] Add showConfig tsc flag for debugging configs (#27353) * Add showConfig tsc flag for debugging configs * Merge showConfig implementation with init implementation, add basic unit tests * Fix lint * Add missing semicolon * showConfig when theres no config file --- src/compiler/commandLineParser.ts | 195 +++++++++++++----- src/compiler/diagnosticMessages.json | 4 + src/compiler/types.ts | 1 + src/testRunner/tsconfig.json | 1 + src/testRunner/unittests/showConfig.ts | 34 +++ src/tsc/tsc.ts | 10 + .../tsconfig.json | 3 + .../tsconfig.json | 8 + .../tsconfig.json | 5 + .../tsconfig.json | 6 + .../tsconfig.json | 3 + .../tsconfig.json | 8 + .../tsconfig.json | 3 + .../tsconfig.json | 8 + .../tsconfig.json | 8 + 15 files changed, 240 insertions(+), 57 deletions(-) create mode 100644 src/testRunner/unittests/showConfig.ts create mode 100644 tests/baselines/reference/showConfig/Default initialized TSConfig/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with advanced options/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with boolean value compiler options/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with enum value compiler options/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with files options/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option value/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with list compiler options with enum value/tsconfig.json create mode 100644 tests/baselines/reference/showConfig/Show TSConfig with list compiler options/tsconfig.json diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 782f76b3d1f..18987466352 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -164,6 +164,13 @@ namespace ts { category: Diagnostics.Command_line_Options, description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental }, + { + name: "showConfig", + type: "boolean", + category: Diagnostics.Command_line_Options, + isCommandLineOnly: true, + description: Diagnostics.Print_the_final_configuration_instead_of_building + }, // Basic { @@ -1653,6 +1660,137 @@ namespace ts { return false; } + /** + * Generate an uncommented, complete tsconfig for use with "--showConfig" + * @param configParseResult options to be generated into tsconfig.json + * @param configFileName name of the parsed config file - output paths will be generated relative to this + * @param host provides current directory and case sensitivity services + */ + /** @internal */ + export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: { getCurrentDirectory(): string, useCaseSensitiveFileNames: boolean }): object { + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); + const files = map( + filter( + configParseResult.fileNames, + !configParseResult.configFileSpecs ? _ => false : matchesSpecs( + configFileName, + configParseResult.configFileSpecs.validatedIncludeSpecs, + configParseResult.configFileSpecs.validatedExcludeSpecs + ) + ), + f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName) + ); + const optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); + const config = { + compilerOptions: { + ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}), + showConfig: undefined, + configFile: undefined, + configFilePath: undefined, + help: undefined, + init: undefined, + listFiles: undefined, + listEmittedFiles: undefined, + project: undefined, + }, + references: map(configParseResult.projectReferences, r => ({ ...r, path: r.originalPath, originalPath: undefined })), + files: length(files) ? files : undefined, + ...(configParseResult.configFileSpecs ? { + include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), + exclude: configParseResult.configFileSpecs.validatedExcludeSpecs + } : {}), + compilerOnSave: !!configParseResult.compileOnSave ? true : undefined + }; + return config; + } + + function filterSameAsDefaultInclude(specs: ReadonlyArray | undefined) { + if (!length(specs)) return undefined; + if (length(specs) !== 1) return specs; + if (specs![0] === "**/*") return undefined; + return specs; + } + + function matchesSpecs(path: string, includeSpecs: ReadonlyArray | undefined, excludeSpecs: ReadonlyArray | undefined): (path: string) => boolean { + if (!includeSpecs) return _ => false; + const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, sys.useCaseSensitiveFileNames, sys.getCurrentDirectory()); + const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, sys.useCaseSensitiveFileNames); + const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, sys.useCaseSensitiveFileNames); + if (includeRe) { + if (excludeRe) { + return path => includeRe.test(path) && !excludeRe.test(path); + } + return path => includeRe.test(path); + } + if (excludeRe) { + return path => !excludeRe.test(path); + } + return _ => false; + } + + function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return (optionDefinition).type; + } + } + + function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return forEachEntry(customTypeMap, (mapValue, key) => { + if (mapValue === value) { + return key; + } + }); + } + + function serializeCompilerOptions(options: CompilerOptions, pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }): Map { + const result = createMap(); + const optionsNameMap = getOptionNameMap().optionNameMap; + const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames); + + for (const name in options) { + if (hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) { + continue; + } + const value = options[name]; + const optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + if (pathOptions && optionDefinition.isFilePath) { + result.set(name, getRelativePathFromFile(pathOptions.configFilePath, getNormalizedAbsolutePath(value as string, getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName!)); + } + else { + result.set(name, value); + } + } + else { + if (optionDefinition.type === "list") { + result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); + } + } + } + } + } + return result; + } + /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -1664,63 +1802,6 @@ namespace ts { const compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return (optionDefinition).type; - } - } - - function getNameOfCompilerOptionValue(value: CompilerOptionsValue, customTypeMap: Map): string | undefined { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return forEachEntry(customTypeMap, (mapValue, key) => { - if (mapValue === value) { - return key; - } - }); - } - - function serializeCompilerOptions(options: CompilerOptions): Map { - const result = createMap(); - const optionsNameMap = getOptionNameMap().optionNameMap; - - for (const name in options) { - if (hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name)!.category === Diagnostics.Command_line_Options) { - continue; - } - const value = options[name]; - const optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - const customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap)!)); // TODO: GH#18217 - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); - } - } - } - } - } - return result; - } - function getDefaultValueForOption(option: CommandLineOption) { switch (option.type) { case "number": diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 1f1ee7a6948..01aa861cabb 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1007,6 +1007,10 @@ "category": "Error", "code": 1349 }, + "Print the final configuration instead of building.": { + "category": "Message", + "code": 1350 + }, "Duplicate identifier '{0}'.": { "category": "Error", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index aeb310671ed..1e592ad5886 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4556,6 +4556,7 @@ namespace ts { /*@internal*/ version?: boolean; /*@internal*/ watch?: boolean; esModuleInterop?: boolean; + /* @internal */ showConfig?: boolean; [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 42edf839964..af25aba408d 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -75,6 +75,7 @@ "unittests/reuseProgramStructure.ts", "unittests/session.ts", "unittests/semver.ts", + "unittests/showConfig.ts", "unittests/symbolWalker.ts", "unittests/telemetry.ts", "unittests/textChanges.ts", diff --git a/src/testRunner/unittests/showConfig.ts b/src/testRunner/unittests/showConfig.ts new file mode 100644 index 00000000000..a2b5bb10258 --- /dev/null +++ b/src/testRunner/unittests/showConfig.ts @@ -0,0 +1,34 @@ +namespace ts { + describe("showTSConfig", () => { + function showTSConfigCorrectly(name: string, commandLinesArgs: string[]) { + describe(name, () => { + const commandLine = parseCommandLine(commandLinesArgs); + const initResult = convertToTSConfig(commandLine, `/${name}/tsconfig.json`, { getCurrentDirectory() { return `/${name}`; }, useCaseSensitiveFileNames: true }); + const outputFileName = `showConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`; + + it(`Correct output for ${outputFileName}`, () => { + // tslint:disable-next-line:no-null-keyword + Harness.Baseline.runBaseline(outputFileName, JSON.stringify(initResult, null, 4) + "\n"); + }); + }); + } + + showTSConfigCorrectly("Default initialized TSConfig", ["--showConfig"]); + + showTSConfigCorrectly("Show TSConfig with files options", ["--showConfig", "file0.st", "file1.ts", "file2.ts"]); + + showTSConfigCorrectly("Show TSConfig with boolean value compiler options", ["--showConfig", "--noUnusedLocals"]); + + showTSConfigCorrectly("Show TSConfig with enum value compiler options", ["--showConfig", "--target", "es5", "--jsx", "react"]); + + showTSConfigCorrectly("Show TSConfig with list compiler options", ["--showConfig", "--types", "jquery,mocha"]); + + showTSConfigCorrectly("Show TSConfig with list compiler options with enum value", ["--showConfig", "--lib", "es5,es2015.core"]); + + showTSConfigCorrectly("Show TSConfig with incorrect compiler option", ["--showConfig", "--someNonExistOption"]); + + showTSConfigCorrectly("Show TSConfig with incorrect compiler option value", ["--showConfig", "--lib", "nonExistLib,es5,es2015.promise"]); + + showTSConfigCorrectly("Show TSConfig with advanced options", ["--showConfig", "--declaration", "--declarationDir", "lib", "--skipLibCheck", "--noErrorTruncation"]); + }); +} \ No newline at end of file diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index ec2d029e60a..549f79f9025 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -132,6 +132,11 @@ namespace ts { const commandLineOptions = commandLine.options; if (configFileName) { const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic)!; // TODO: GH#18217 + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + sys.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } updateReportDiagnostic(configParseResult.options); if (isWatchSet(configParseResult.options)) { reportWatchModeWithoutSysSupport(); @@ -142,6 +147,11 @@ namespace ts { } } else { + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + sys.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(sys.getCurrentDirectory(), "tsconfig.json"), sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } updateReportDiagnostic(commandLineOptions); if (isWatchSet(commandLineOptions)) { reportWatchModeWithoutSysSupport(); diff --git a/tests/baselines/reference/showConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/showConfig/Default initialized TSConfig/tsconfig.json new file mode 100644 index 00000000000..cd727e8ccdc --- /dev/null +++ b/tests/baselines/reference/showConfig/Default initialized TSConfig/tsconfig.json @@ -0,0 +1,3 @@ +{ + "compilerOptions": {} +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with advanced options/tsconfig.json new file mode 100644 index 00000000000..6dbccf64bb9 --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with advanced options/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "declaration": true, + "declarationDir": "./lib", + "skipLibCheck": true, + "noErrorTruncation": true + } +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with boolean value compiler options/tsconfig.json new file mode 100644 index 00000000000..650a347f895 --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with boolean value compiler options/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "noUnusedLocals": true + } +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with enum value compiler options/tsconfig.json new file mode 100644 index 00000000000..0052b1327f1 --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with enum value compiler options/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "target": "es5", + "jsx": "react" + } +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with files options/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with files options/tsconfig.json new file mode 100644 index 00000000000..cd727e8ccdc --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with files options/tsconfig.json @@ -0,0 +1,3 @@ +{ + "compilerOptions": {} +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option value/tsconfig.json new file mode 100644 index 00000000000..c75e5d4ae1d --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option value/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "lib": [ + "es5", + "es2015.promise" + ] + } +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option/tsconfig.json new file mode 100644 index 00000000000..cd727e8ccdc --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with incorrect compiler option/tsconfig.json @@ -0,0 +1,3 @@ +{ + "compilerOptions": {} +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with list compiler options with enum value/tsconfig.json new file mode 100644 index 00000000000..6da42b43907 --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with list compiler options with enum value/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "lib": [ + "es5", + "es2015.core" + ] + } +} diff --git a/tests/baselines/reference/showConfig/Show TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/showConfig/Show TSConfig with list compiler options/tsconfig.json new file mode 100644 index 00000000000..7b5da8e7d3c --- /dev/null +++ b/tests/baselines/reference/showConfig/Show TSConfig with list compiler options/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "types": [ + "jquery", + "mocha" + ] + } +} From 72aec56fe8e1b9d2341a8548493e439385810738 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 15:57:32 -0700 Subject: [PATCH 182/262] Use mapDefined and combine event name inputs --- .../unittests/tsserverProjectSystem.ts | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 9722905bbdb..ae3a3901ea1 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -343,7 +343,7 @@ namespace ts.projectSystem { return { session, events }; } - function createSessionWithDefaultEventHandler(host: TestServerHost, eventName: T["event"], opts: Partial = {}, ...eventNames: T["event"][]) { + function createSessionWithDefaultEventHandler(host: TestServerHost, eventNames: T["event"] | T["event"][], opts: Partial = {}) { const session = createSession(host, { canUseEvents: true, ...opts }); return { @@ -354,15 +354,13 @@ namespace ts.projectSystem { function getEvents() { const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; - return filter( - map( - host.getOutput(), s => convertToObject( - parseJsonText("json.json", s.replace(outputEventRegex, "")), - [] - ) - ), - e => e.event === eventName || eventNames.some(eventName => e.event === eventName) - ) as T[]; + return mapDefined(host.getOutput(), s => { + const e = convertToObject( + parseJsonText("json.json", s.replace(outputEventRegex, "")), + [] + ); + return (isArray(eventNames) ? eventNames.some(eventName => e.event === eventName) : e.event === eventNames) ? e as T : undefined; + }); } function clearEvents() { @@ -9625,7 +9623,7 @@ export const x = 10;` describe("when using default event handler", () => { verifyProjectLoadingStartAndFinish(host => { - const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, server.ProjectLoadingStartEvent, {}, server.ProjectLoadingFinishEvent); + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]); return { session, getNumberOfEvents: () => getEvents().length, From 121a350c5da04ddbc5bf2243a990af17fdd03ced Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 31 Oct 2018 19:00:55 -0700 Subject: [PATCH 183/262] Instead of adding lib files, avoid creating diagnostics producing checker for container projects --- src/compiler/program.ts | 4 ++-- src/testRunner/unittests/tscWatchMode.ts | 10 ++++++++-- src/testRunner/unittests/tsserverProjectSystem.ts | 4 ++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index ca8731a533f..15c09a1a79b 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -726,7 +726,7 @@ namespace ts { // - The '--noLib' flag is used. // - A 'no-default-lib' reference comment is encountered in // processing the root files. - if (!skipDefaultLib) { + if (rootNames.length && !skipDefaultLib) { // If '--lib' is not specified, include default library file according to '--target' // otherwise, using options specified in '--lib' instead of '--target' default library file const defaultLibraryFileName = getDefaultLibraryFileName(); @@ -1841,7 +1841,7 @@ namespace ts { } function getGlobalDiagnostics(): SortedReadonlyArray { - return sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + return rootNames.length ? sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : emptyArray as any as SortedReadonlyArray; } function getConfigFileParsingDiagnostics(): ReadonlyArray { diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index ca00e08fdd2..3523db7544f 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1074,7 +1074,10 @@ namespace ts.tscWatch { const host = createWatchedSystem([file1, configFile, libFile]); const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramActualFiles(watch(), [libFile.path]); + checkProgramActualFiles(watch(), emptyArray); + checkOutputErrorsInitial(host, [ + "error TS18003: No inputs were found in config file '/a/b/tsconfig.json'. Specified 'include' paths were '[\"app/*\",\"test/**/*\",\"something\"]' and 'exclude' paths were '[]'.\n" + ]); }); it("non-existing directories listed in config file input array should be able to handle @types if input file list is empty", () => { @@ -1100,7 +1103,10 @@ namespace ts.tscWatch { const host = createWatchedSystem([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) }); const watch = createWatchOfConfigFile(config.path, host); - checkProgramActualFiles(watch(), [t1.path, t2.path]); + checkProgramActualFiles(watch(), emptyArray); + checkOutputErrorsInitial(host, [ + "tsconfig.json(1,24): error TS18002: The 'files' list in config file '/a/tsconfig.json' is empty.\n" + ]); }); it("should support files without extensions", () => { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index c4dc4b9216a..3b7e3d61a79 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -3061,7 +3061,7 @@ namespace ts.projectSystem { const configProject = configuredProjectAt(projectService, 0); checkProjectActualFiles(configProject, lazyConfiguredProjectsFromExternalProject ? emptyArray : // Since no files opened from this project, its not loaded - [libFile.path, configFile.path]); + [configFile.path]); host.reloadFS([libFile, site]); host.checkTimeoutQueueLengthAndRun(1); @@ -10521,7 +10521,7 @@ declare class TestLib { assert.deepEqual(semanticDiagnostics, []); }); const containerProject = service.configuredProjects.get(containerConfig.path)!; - checkProjectActualFiles(containerProject, [containerConfig.path, libFile.path]); + checkProjectActualFiles(containerProject, [containerConfig.path]); const optionsDiagnostics = session.executeCommandSeq({ command: protocol.CommandTypes.CompilerOptionsDiagnosticsFull, arguments: { projectFileName: containerProject.projectName } From a0767437f658a675d743e0a552c315e132799ba4 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Thu, 1 Nov 2018 17:48:52 +0100 Subject: [PATCH 184/262] remove some useless internal comments --- src/compiler/utilities.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index a969d580b86..991e403f52e 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2921,7 +2921,6 @@ namespace ts { } } - /* @internal */ export function getBinaryOperatorPrecedence(kind: SyntaxKind): number { switch (kind) { case SyntaxKind.BarBarToken: @@ -6834,7 +6833,6 @@ namespace ts { /* @internal */ namespace ts { - /** @internal */ export function isNamedImportsOrExports(node: Node): node is NamedImportsOrExports { return node.kind === SyntaxKind.NamedImports || node.kind === SyntaxKind.NamedExports; } @@ -6898,7 +6896,6 @@ namespace ts { getSourceMapSourceConstructor: () => SourceMapSource, }; - /* @internal */ export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex = 0): string { return text.replace(/{(\d+)}/g, (_match, index: string) => Debug.assertDefined(args[+index + baseIndex])); } @@ -6909,7 +6906,6 @@ namespace ts { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } - /* @internal */ export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: (string | number | undefined)[]): DiagnosticWithLocation; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): DiagnosticWithLocation { Debug.assertGreaterThanOrEqual(start, 0); @@ -6938,7 +6934,6 @@ namespace ts { }; } - /* @internal */ export function formatMessage(_dummy: any, message: DiagnosticMessage): string { let text = getLocaleSpecificMessage(message); @@ -6949,7 +6944,6 @@ namespace ts { return text; } - /* @internal */ export function createCompilerDiagnostic(message: DiagnosticMessage, ...args: (string | number | undefined)[]): Diagnostic; export function createCompilerDiagnostic(message: DiagnosticMessage): Diagnostic { let text = getLocaleSpecificMessage(message); @@ -6970,7 +6964,6 @@ namespace ts { }; } - /* @internal */ export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic { return { file: undefined, @@ -6983,7 +6976,6 @@ namespace ts { }; } - /* @internal */ export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage, ...args: (string | undefined)[]): DiagnosticMessageChain; export function chainDiagnosticMessages(details: DiagnosticMessageChain | undefined, message: DiagnosticMessage): DiagnosticMessageChain { let text = getLocaleSpecificMessage(message); @@ -7015,14 +7007,12 @@ namespace ts { return diagnostic.file ? diagnostic.file.path : undefined; } - /* @internal */ export function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || Comparison.EqualTo; } - /* @internal */ export function compareDiagnosticsSkipRelatedInformation(d1: Diagnostic, d2: Diagnostic): Comparison { return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || @@ -7360,7 +7350,6 @@ namespace ts { return rootLength > 0 && rootLength === path.length; } - /* @internal */ export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath From f555261d7a6c8695de4953288965823c3089d33c Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 12:33:18 -0700 Subject: [PATCH 185/262] Add Rest type to lib.d.ts --- src/lib/es5.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index c8e99f0d1db..70e7e805899 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1416,6 +1416,13 @@ type Pick = { [P in K]: T[P]; }; +/** + * From T, omit a set of properties whose keys are in the union K + */ +type Rest = { + [P in Exclude]: T[P]; +}; + /** * Construct a type with a set of properties K of type T */ From 6f8959b86b7b984bf5557429d6c39bb00ba38916 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 12:41:39 -0700 Subject: [PATCH 186/262] Use Rest for rest properties in object destructuring --- src/compiler/checker.ts | 59 +++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2418c75f0cb..6bde3775b94 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -517,6 +517,7 @@ namespace ts { let deferredGlobalTemplateStringsArrayType: ObjectType; let deferredGlobalImportMetaType: ObjectType; let deferredGlobalExtractSymbol: Symbol; + let deferredGlobalRestSymbol: Symbol; const allPotentiallyUnusedIdentifiers = createMap(); // key is file name @@ -4596,26 +4597,18 @@ namespace ts { if (source.flags & TypeFlags.Never) { return emptyObjectType; } - if (source.flags & TypeFlags.Union) { return mapType(source, t => getRestType(t, properties, symbol)); } - - const members = createSymbolTable(); - const names = createUnderscoreEscapedMap(); - for (const name of properties) { - names.set(getTextOfPropertyName(name), true); + const restTypeAlias = getGlobalRestSymbol(); + if (!restTypeAlias) { + return errorType; } - for (const prop of getPropertiesOfType(source)) { - if (!names.has(prop.escapedName) - && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) - && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getSpreadSymbol(prop)); - } + const omitTypes = getUnionType(map(properties, getLiteralTypeFromPropertyName)); + if (omitTypes.flags & TypeFlags.Never) { + return source; } - const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); - const numberIndexInfo = getIndexInfoOfType(source, IndexKind.Number); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); + return getTypeAliasInstantiation(restTypeAlias, [source, omitTypes]); } /** Return the inferred type for a binding element */ @@ -4639,7 +4632,7 @@ namespace ts { let type: Type | undefined; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { if (declaration.dotDotDotToken) { - if (parentType.flags & TypeFlags.Unknown || !isValidSpreadType(parentType) || isGenericObjectType(parentType)) { + if (parentType.flags & TypeFlags.Unknown || !isValidSpreadType(parentType)) { error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; } @@ -6823,7 +6816,7 @@ namespace ts { if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (const prop of getPropertiesOfType(modifiersType)) { - addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include)); + addMemberForKeyType(getLiteralTypeFromProperty(prop, include)); } if (modifiersType.flags & TypeFlags.Any || getIndexInfoOfType(modifiersType, IndexKind.String)) { addMemberForKeyType(stringType); @@ -8674,6 +8667,10 @@ namespace ts { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 } + function getGlobalRestSymbol(): Symbol { + return deferredGlobalRestSymbol || (deferredGlobalRestSymbol = getGlobalSymbol("Rest" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 + } + /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -9256,14 +9253,18 @@ namespace ts { type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getLiteralTypeFromPropertyName(prop: Symbol, include: TypeFlags) { + function getLiteralTypeFromPropertyName(name: PropertyName) { + return isComputedPropertyName(name) ? checkComputedPropertyName(name) : + isIdentifier(name) ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) : + checkExpression(name); + } + + function getLiteralTypeFromProperty(prop: Symbol, include: TypeFlags) { if (!(getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier)) { let type = getLateBoundSymbol(prop).nameType; if (!type && !isKnownSymbol(prop)) { - const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration); - type = name && isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : - getLiteralType(symbolName(prop)); + const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration) as PropertyName; + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(symbolName(prop)); } if (type && type.flags & include) { return type; @@ -9272,8 +9273,8 @@ namespace ts { return neverType; } - function getLiteralTypeFromPropertyNames(type: Type, include: TypeFlags) { - return getUnionType(map(getPropertiesOfType(type), t => getLiteralTypeFromPropertyName(t, include))); + function getLiteralTypeFromProperties(type: Type, include: TypeFlags) { + return getUnionType(map(getPropertiesOfType(type), t => getLiteralTypeFromProperty(t, include))); } function getNonEnumNumberIndexInfo(type: Type) { @@ -9288,10 +9289,10 @@ namespace ts { getObjectFlags(type) & ObjectFlags.Mapped ? getConstraintTypeFromMappedType(type) : type === wildcardType ? wildcardType : type.flags & TypeFlags.Any ? keyofConstraintType : - stringsOnly ? getIndexInfoOfType(type, IndexKind.String) ? stringType : getLiteralTypeFromPropertyNames(type, TypeFlags.StringLiteral) : - getIndexInfoOfType(type, IndexKind.String) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, TypeFlags.UniqueESSymbol)]) : - getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, TypeFlags.StringLiteral | TypeFlags.UniqueESSymbol)]) : - getLiteralTypeFromPropertyNames(type, TypeFlags.StringOrNumberLiteralOrUnique); + stringsOnly ? getIndexInfoOfType(type, IndexKind.String) ? stringType : getLiteralTypeFromProperties(type, TypeFlags.StringLiteral) : + getIndexInfoOfType(type, IndexKind.String) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, TypeFlags.UniqueESSymbol)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, TypeFlags.StringLiteral | TypeFlags.UniqueESSymbol)]) : + getLiteralTypeFromProperties(type, TypeFlags.StringOrNumberLiteralOrUnique); } function getExtractStringType(type: Type) { @@ -10976,7 +10977,7 @@ namespace ts { if (!length(node.properties)) return; for (const prop of node.properties) { if (isSpreadAssignment(prop)) continue; - const type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), TypeFlags.StringOrNumberLiteralOrUnique); + const type = getLiteralTypeFromProperty(getSymbolOfNode(prop), TypeFlags.StringOrNumberLiteralOrUnique); if (!type || (type.flags & TypeFlags.Never)) { continue; } From 18f80b89088fb853dc1accf8b81fcdcf7e074442 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 12:42:32 -0700 Subject: [PATCH 187/262] Accept new baselines --- .../asyncFunctionTempVariableScoping.types | 2 +- ...ropertyNamesContextualType8_ES5.errors.txt | 19 +++--- ...ropertyNamesContextualType8_ES6.errors.txt | 19 +++--- .../expressionTypeNodeShouldError.types | 12 ++-- ...turingDoesNotElideFollowingStatement.types | 2 +- .../importHelpersInAmbientContext.types | 4 +- .../intersectionsOfLargeUnions.types | 6 +- .../intersectionsOfLargeUnions2.types | 6 +- .../modularizeLibrary_Dom.iterable.types | 4 +- .../nonPrimitiveAccessProperty.types | 2 +- .../baselines/reference/objectRest.errors.txt | 58 +++++++++++++++++++ tests/baselines/reference/objectRest.types | 34 +++++------ .../reference/objectRestAssignment.types | 8 +-- .../baselines/reference/objectRestForOf.types | 6 +- .../reference/objectRestNegative.errors.txt | 9 +-- .../reference/objectRestNegative.types | 10 ++-- .../reference/objectRestParameter.symbols | 12 ++-- .../reference/objectRestParameter.types | 18 +++--- .../reference/objectRestParameterES5.symbols | 12 ++-- .../reference/objectRestParameterES5.types | 18 +++--- .../reference/objectRestReadonly.symbols | 4 +- .../reference/objectRestReadonly.types | 4 +- ...InitializerBeforeDestructuringEmit.symbols | 8 +-- ...erInitializerBeforeDestructuringEmit.types | 8 +-- .../parserOverloadOnConstants1.types | 8 +-- .../restInvalidArgumentType.errors.txt | 20 +------ .../reference/restInvalidArgumentType.types | 14 ++--- .../unusedLocalsAndObjectSpread.types | 12 ++-- 28 files changed, 189 insertions(+), 150 deletions(-) create mode 100644 tests/baselines/reference/objectRest.errors.txt diff --git a/tests/baselines/reference/asyncFunctionTempVariableScoping.types b/tests/baselines/reference/asyncFunctionTempVariableScoping.types index 30b23994903..cc477523cb9 100644 --- a/tests/baselines/reference/asyncFunctionTempVariableScoping.types +++ b/tests/baselines/reference/asyncFunctionTempVariableScoping.types @@ -5,7 +5,7 @@ async ({ foo, bar, ...rest }) => bar(await foo); >async ({ foo, bar, ...rest }) => bar(await foo) : ({ foo, bar, ...rest }: { [x: string]: any; foo: any; bar: any; }) => Promise >foo : any >bar : any ->rest : { [x: string]: any; } +>rest : Rest<{ [x: string]: any; foo: any; bar: any; }, "foo" | "bar"> >bar(await foo) : any >bar : any >await foo : any diff --git a/tests/baselines/reference/computedPropertyNamesContextualType8_ES5.errors.txt b/tests/baselines/reference/computedPropertyNamesContextualType8_ES5.errors.txt index 56e374f0d53..ee36609095a 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType8_ES5.errors.txt +++ b/tests/baselines/reference/computedPropertyNamesContextualType8_ES5.errors.txt @@ -1,20 +1,21 @@ -tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts(7,5): error TS2418: Type of computed property's value is 'string', which is not assignable to type 'boolean'. -tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts(8,5): error TS2418: Type of computed property's value is 'number', which is not assignable to type 'boolean'. +tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts(6,5): error TS2322: Type '{ [x: string]: string | number; }' is not assignable to type 'I'. + Index signatures are incompatible. + Type 'string | number' is not assignable to type 'boolean'. + Type 'string' is not assignable to type 'boolean'. -==== tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts (2 errors) ==== +==== tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts (1 errors) ==== interface I { [s: string]: boolean; [s: number]: boolean; } var o: I = { + ~ +!!! error TS2322: Type '{ [x: string]: string | number; }' is not assignable to type 'I'. +!!! error TS2322: Index signatures are incompatible. +!!! error TS2322: Type 'string | number' is not assignable to type 'boolean'. +!!! error TS2322: Type 'string' is not assignable to type 'boolean'. [""+"foo"]: "", - ~~~~~~~~~~ -!!! error TS2418: Type of computed property's value is 'string', which is not assignable to type 'boolean'. -!!! related TS6501 tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts:2:5: The expected type comes from this index signature. [""+"bar"]: 0 - ~~~~~~~~~~ -!!! error TS2418: Type of computed property's value is 'number', which is not assignable to type 'boolean'. -!!! related TS6501 tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES5.ts:2:5: The expected type comes from this index signature. } \ No newline at end of file diff --git a/tests/baselines/reference/computedPropertyNamesContextualType8_ES6.errors.txt b/tests/baselines/reference/computedPropertyNamesContextualType8_ES6.errors.txt index c24b53eaa17..1048fd2e119 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType8_ES6.errors.txt +++ b/tests/baselines/reference/computedPropertyNamesContextualType8_ES6.errors.txt @@ -1,20 +1,21 @@ -tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts(7,5): error TS2418: Type of computed property's value is 'string', which is not assignable to type 'boolean'. -tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts(8,5): error TS2418: Type of computed property's value is 'number', which is not assignable to type 'boolean'. +tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts(6,5): error TS2322: Type '{ [x: string]: string | number; }' is not assignable to type 'I'. + Index signatures are incompatible. + Type 'string | number' is not assignable to type 'boolean'. + Type 'string' is not assignable to type 'boolean'. -==== tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts (2 errors) ==== +==== tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts (1 errors) ==== interface I { [s: string]: boolean; [s: number]: boolean; } var o: I = { + ~ +!!! error TS2322: Type '{ [x: string]: string | number; }' is not assignable to type 'I'. +!!! error TS2322: Index signatures are incompatible. +!!! error TS2322: Type 'string | number' is not assignable to type 'boolean'. +!!! error TS2322: Type 'string' is not assignable to type 'boolean'. [""+"foo"]: "", - ~~~~~~~~~~ -!!! error TS2418: Type of computed property's value is 'string', which is not assignable to type 'boolean'. -!!! related TS6501 tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts:2:5: The expected type comes from this index signature. [""+"bar"]: 0 - ~~~~~~~~~~ -!!! error TS2418: Type of computed property's value is 'number', which is not assignable to type 'boolean'. -!!! related TS6501 tests/cases/conformance/es6/computedProperties/computedPropertyNamesContextualType8_ES6.ts:2:5: The expected type comes from this index signature. } \ No newline at end of file diff --git a/tests/baselines/reference/expressionTypeNodeShouldError.types b/tests/baselines/reference/expressionTypeNodeShouldError.types index 45c12d7c8ff..90707d4db50 100644 --- a/tests/baselines/reference/expressionTypeNodeShouldError.types +++ b/tests/baselines/reference/expressionTypeNodeShouldError.types @@ -31,9 +31,9 @@ class C { const nodes = document.getElementsByTagName("li"); >nodes : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType = "".typeof(nodes.item(0)); @@ -72,9 +72,9 @@ class C2 { const nodes2 = document.getElementsByTagName("li"); >nodes2 : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType2 = 4..typeof(nodes.item(0)); @@ -114,9 +114,9 @@ class C3 { const nodes3 = document.getElementsByTagName("li"); >nodes3 : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType3 = true.typeof(nodes.item(0)); diff --git a/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types b/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types index 246c6d2e7db..600c4f9d717 100644 --- a/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types +++ b/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types @@ -10,7 +10,7 @@ let array = [{a: 0, b: 1}] for (let { a, ...rest } of array) >a : number ->rest : { b: number; } +>rest : Rest<{ a: number; b: number; }, "a"> >array : { a: number; b: number; }[] void a diff --git a/tests/baselines/reference/importHelpersInAmbientContext.types b/tests/baselines/reference/importHelpersInAmbientContext.types index 0c3365d7d93..794bdb2e418 100644 --- a/tests/baselines/reference/importHelpersInAmbientContext.types +++ b/tests/baselines/reference/importHelpersInAmbientContext.types @@ -33,7 +33,7 @@ interface Foo { } export var { a, ...x } : Foo; >a : number ->x : { b: string; } +>x : Rest === tests/cases/compiler/b.ts === export {}; @@ -72,7 +72,7 @@ declare namespace N { } export var { a, ...x } : Foo; >a : number ->x : { b: string; } +>x : Rest } === tests/cases/compiler/tslib.d.ts === diff --git a/tests/baselines/reference/intersectionsOfLargeUnions.types b/tests/baselines/reference/intersectionsOfLargeUnions.types index 06d01c0c6b2..26f93ac79db 100644 --- a/tests/baselines/reference/intersectionsOfLargeUnions.types +++ b/tests/baselines/reference/intersectionsOfLargeUnions.types @@ -24,7 +24,7 @@ export function assertIsElement(node: Node | null): node is Element { } export function assertNodeTagName< ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U T extends keyof ElementTagNameMap, U extends ElementTagNameMap[T]>(node: Node | null, tagName: T): node is U { @@ -56,7 +56,7 @@ export function assertNodeTagName< } export function assertNodeProperty< ->assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void +>assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void T extends keyof ElementTagNameMap, P extends keyof ElementTagNameMap[T], @@ -69,7 +69,7 @@ export function assertNodeProperty< if (assertNodeTagName(node, tagName)) { >assertNodeTagName(node, tagName) : boolean ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U >node : Node | null >tagName : T diff --git a/tests/baselines/reference/intersectionsOfLargeUnions2.types b/tests/baselines/reference/intersectionsOfLargeUnions2.types index 82160fb235e..277806ae314 100644 --- a/tests/baselines/reference/intersectionsOfLargeUnions2.types +++ b/tests/baselines/reference/intersectionsOfLargeUnions2.types @@ -38,7 +38,7 @@ export function assertIsElement(node: Node | null): node is Element { } export function assertNodeTagName< ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U T extends keyof ElementTagNameMap, U extends ElementTagNameMap[T]>(node: Node | null, tagName: T): node is U { @@ -70,7 +70,7 @@ export function assertNodeTagName< } export function assertNodeProperty< ->assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void +>assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void T extends keyof ElementTagNameMap, P extends keyof ElementTagNameMap[T], @@ -83,7 +83,7 @@ export function assertNodeProperty< if (assertNodeTagName(node, tagName)) { >assertNodeTagName(node, tagName) : boolean ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U >node : Node | null >tagName : T diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types index e2ba3e7a300..70c6a6cb5b9 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types @@ -2,9 +2,9 @@ for (const element of document.getElementsByTagName("a")) { >element : HTMLAnchorElement >document.getElementsByTagName("a") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"a" : "a" element.href; diff --git a/tests/baselines/reference/nonPrimitiveAccessProperty.types b/tests/baselines/reference/nonPrimitiveAccessProperty.types index 900df294d9b..5218aa20fda 100644 --- a/tests/baselines/reference/nonPrimitiveAccessProperty.types +++ b/tests/baselines/reference/nonPrimitiveAccessProperty.types @@ -19,6 +19,6 @@ var { destructuring } = a; // error >a : object var { ...rest } = a; // ok ->rest : {} +>rest : object >a : object diff --git a/tests/baselines/reference/objectRest.errors.txt b/tests/baselines/reference/objectRest.errors.txt new file mode 100644 index 00000000000..dfea8b96b96 --- /dev/null +++ b/tests/baselines/reference/objectRest.errors.txt @@ -0,0 +1,58 @@ +tests/cases/conformance/types/rest/objectRest.ts(43,57): error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type 'Rest<{ a: number; b: string; }, string>'. +tests/cases/conformance/types/rest/objectRest.ts(44,53): error TS2322: Type 'Rest<{ a: number; b: string; }, string>' is not assignable to type '{ a: number; b: string; }'. + Property 'a' is missing in type 'Rest<{ a: number; b: string; }, string>'. + + +==== tests/cases/conformance/types/rest/objectRest.ts (2 errors) ==== + var o = { a: 1, b: 'no' } + var { ...clone } = o; + var { a, ...justB } = o; + var { a, b: renamed, ...empty } = o; + var { ['b']: renamed, ...justA } = o; + var { 'b': renamed, ...justA } = o; + var { b: { '0': n, '1': oooo }, ...justA } = o; + + let o2 = { c: 'terrible idea?', d: 'yes' }; + var { d: renamed, ...d } = o2; + + let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; + var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; + + let complex: { x: { ka, ki }, y: number }; + var { x: { ka, ...nested }, y: other, ...rest } = complex; + ({x: { ka, ...nested }, y: other, ...rest} = complex); + var { x, ...fresh } = { x: 1, y: 2 }; + ({ x, ...fresh } = { x: 1, y: 2 }); + + class Removable { + private x: number; + protected y: number; + set z(value: number) { } + get both(): number { return 12 } + set both(value: number) { } + m() { } + removed: string; + remainder: string; + } + interface I { + m(): void; + removed: string; + remainder: string; + } + var removable = new Removable(); + var { removed, ...removableRest } = removable; + var i: I = removable; + var { removed, ...removableRest2 } = i; + + let computed = 'b'; + let computed2 = 'a'; + var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; + ~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type 'Rest<{ a: number; b: string; }, string>'. + ({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); + ~ +!!! error TS2322: Type 'Rest<{ a: number; b: string; }, string>' is not assignable to type '{ a: number; b: string; }'. +!!! error TS2322: Property 'a' is missing in type 'Rest<{ a: number; b: string; }, string>'. + + var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; + \ No newline at end of file diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types index cb50daf9c4b..e664c5e64cd 100644 --- a/tests/baselines/reference/objectRest.types +++ b/tests/baselines/reference/objectRest.types @@ -13,32 +13,32 @@ var { ...clone } = o; var { a, ...justB } = o; >a : number ->justB : { b: string; } +>justB : Rest<{ a: number; b: string; }, "a"> >o : { a: number; b: string; } var { a, b: renamed, ...empty } = o; >a : number >b : any >renamed : string ->empty : {} +>empty : Rest<{ a: number; b: string; }, "a" | "b"> >o : { a: number; b: string; } var { ['b']: renamed, ...justA } = o; >'b' : "b" >renamed : string ->justA : { a: number; } +>justA : Rest<{ a: number; b: string; }, "b"> >o : { a: number; b: string; } var { 'b': renamed, ...justA } = o; >renamed : string ->justA : { a: number; } +>justA : Rest<{ a: number; b: string; }, "b"> >o : { a: number; b: string; } var { b: { '0': n, '1': oooo }, ...justA } = o; >b : any >n : string >oooo : string ->justA : { a: number; } +>justA : Rest<{ a: number; b: string; }, "b"> >o : { a: number; b: string; } let o2 = { c: 'terrible idea?', d: 'yes' }; @@ -52,7 +52,7 @@ let o2 = { c: 'terrible idea?', d: 'yes' }; var { d: renamed, ...d } = o2; >d : any >renamed : string ->d : { c: string; } +>d : Rest<{ c: string; d: string; }, "d"> >o2 : { c: string; d: string; } let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; @@ -75,7 +75,7 @@ var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; >z : number >n3 : any >nr : { n4: number; } ->restrest : { rest: number; restrest: number; } +>restrest : Rest<{ x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; }, "x" | "n1"> >nestedrest : { x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; } let complex: { x: { ka, ki }, y: number }; @@ -88,10 +88,10 @@ let complex: { x: { ka, ki }, y: number }; var { x: { ka, ...nested }, y: other, ...rest } = complex; >x : any >ka : any ->nested : { ki: any; } +>nested : Rest<{ ka: any; ki: any; }, "ka"> >y : any >other : number ->rest : {} +>rest : Rest<{ x: { ka: any; ki: any; }; y: number; }, "x" | "y"> >complex : { x: { ka: any; ki: any; }; y: number; } ({x: { ka, ...nested }, y: other, ...rest} = complex); @@ -101,15 +101,15 @@ var { x: { ka, ...nested }, y: other, ...rest } = complex; >x : { ki: any; ka: any; } >{ ka, ...nested } : { ki: any; ka: any; } >ka : any ->nested : { ki: any; } +>nested : Rest<{ ka: any; ki: any; }, "ka"> >y : number >other : number ->rest : {} +>rest : Rest<{ x: { ka: any; ki: any; }; y: number; }, "x" | "y"> >complex : { x: { ka: any; ki: any; }; y: number; } var { x, ...fresh } = { x: 1, y: 2 }; >x : number ->fresh : { y: number; } +>fresh : Rest<{ x: number; y: number; }, "x"> >{ x: 1, y: 2 } : { x: number; y: number; } >x : number >1 : 1 @@ -121,7 +121,7 @@ var { x, ...fresh } = { x: 1, y: 2 }; >{ x, ...fresh } = { x: 1, y: 2 } : { x: number; y: number; } >{ x, ...fresh } : { y: number; x: number; } >x : number ->fresh : { y: number; } +>fresh : Rest<{ x: number; y: number; }, "x"> >{ x: 1, y: 2 } : { x: number; y: number; } >x : number >1 : 1 @@ -175,7 +175,7 @@ var removable = new Removable(); var { removed, ...removableRest } = removable; >removed : string ->removableRest : { remainder: string; } +>removableRest : Rest >removable : Removable var i: I = removable; @@ -184,7 +184,7 @@ var i: I = removable; var { removed, ...removableRest2 } = i; >removed : string ->removableRest2 : { m(): void; remainder: string; } +>removableRest2 : Rest >i : I let computed = 'b'; @@ -221,10 +221,10 @@ var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmp >({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any >aNumber : number >12 : 12 ->notEmptyObject : { [x: string]: any; } +>notEmptyObject : Rest<{ [x: string]: any; aNumber?: number; }, "aNumber"> >aNumber + notEmptyObject.anythingGoes : any >aNumber : number >notEmptyObject.anythingGoes : any ->notEmptyObject : { [x: string]: any; } +>notEmptyObject : Rest<{ [x: string]: any; aNumber?: number; }, "aNumber"> >anythingGoes : any diff --git a/tests/baselines/reference/objectRestAssignment.types b/tests/baselines/reference/objectRestAssignment.types index c0c84b6d5e3..04507f688cb 100644 --- a/tests/baselines/reference/objectRestAssignment.types +++ b/tests/baselines/reference/objectRestAssignment.types @@ -52,8 +52,8 @@ var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; >y : { ka: string; x: string; }[] >b : any >z : string ->c : { ki: string; ku: string; } ->rest2 : { ke: string; ko: string; } +>c : Rest<{ z: string; ki: string; ku: string; }, "z"> +>rest2 : Rest<{ a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; }, "a" | "b"> >overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } ({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); @@ -69,7 +69,7 @@ var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; >b : { ki: string; ku: string; z: string; } >{ z, ...c } : { ki: string; ku: string; z: string; } >z : string ->c : { ki: string; ku: string; } ->rest2 : { ke: string; ko: string; } +>c : Rest<{ z: string; ki: string; ku: string; }, "z"> +>rest2 : Rest<{ a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; }, "a" | "b"> >overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } diff --git a/tests/baselines/reference/objectRestForOf.types b/tests/baselines/reference/objectRestForOf.types index 30e10999bc7..107a38ecea6 100644 --- a/tests/baselines/reference/objectRestForOf.types +++ b/tests/baselines/reference/objectRestForOf.types @@ -6,13 +6,13 @@ let array: { x: number, y: string }[]; for (let { x, ...restOf } of array) { >x : number ->restOf : { y: string; } +>restOf : Rest<{ x: number; y: string; }, "x"> >array : { x: number; y: string; }[] [x, restOf]; ->[x, restOf] : (number | { y: string; })[] +>[x, restOf] : (number | Rest<{ x: number; y: string; }, "x">)[] >x : number ->restOf : { y: string; } +>restOf : Rest<{ x: number; y: string; }, "x"> } let xx: number; >xx : number diff --git a/tests/baselines/reference/objectRestNegative.errors.txt b/tests/baselines/reference/objectRestNegative.errors.txt index fef99187d55..8e599f26639 100644 --- a/tests/baselines/reference/objectRestNegative.errors.txt +++ b/tests/baselines/reference/objectRestNegative.errors.txt @@ -1,15 +1,14 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(2,10): error TS2462: A rest element must be last in a destructuring pattern. -tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. +tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Type 'Rest<{ a: number; b: string; }, "b">' is not assignable to type '{ a: string; }'. Types of property 'a' are incompatible. Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/rest/objectRestNegative.ts(9,31): error TS2462: A rest element must be last in a destructuring pattern. tests/cases/conformance/types/rest/objectRestNegative.ts(11,30): error TS7008: Member 'x' implicitly has an 'any' type. tests/cases/conformance/types/rest/objectRestNegative.ts(11,33): error TS7008: Member 'y' implicitly has an 'any' type. -tests/cases/conformance/types/rest/objectRestNegative.ts(12,17): error TS2700: Rest types may only be created from object types. tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: The target of an object rest assignment must be a variable or a property access. -==== tests/cases/conformance/types/rest/objectRestNegative.ts (7 errors) ==== +==== tests/cases/conformance/types/rest/objectRestNegative.ts (6 errors) ==== let o = { a: 1, b: 'no' }; var { ...mustBeLast, a } = o; ~~~~~~~~~~ @@ -19,7 +18,7 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: Th let notAssignable: { a: string }; ({ b, ...notAssignable } = o); ~~~~~~~~~~~~~ -!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. +!!! error TS2322: Type 'Rest<{ a: number; b: string; }, "b">' is not assignable to type '{ a: string; }'. !!! error TS2322: Types of property 'a' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. @@ -34,8 +33,6 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: Th ~ !!! error TS7008: Member 'y' implicitly has an 'any' type. let { x, ...rest } = t; - ~~~~ -!!! error TS2700: Rest types may only be created from object types. return rest; } diff --git a/tests/baselines/reference/objectRestNegative.types b/tests/baselines/reference/objectRestNegative.types index dff6388d609..8287f870599 100644 --- a/tests/baselines/reference/objectRestNegative.types +++ b/tests/baselines/reference/objectRestNegative.types @@ -8,7 +8,7 @@ let o = { a: 1, b: 'no' }; >'no' : "no" var { ...mustBeLast, a } = o; ->mustBeLast : { b: string; } +>mustBeLast : Rest<{ a: number; b: string; }, "a"> >a : number >o : { a: number; b: string; } @@ -30,24 +30,24 @@ let notAssignable: { a: string }; function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { >stillMustBeLast : ({ ...mustBeLast, a }: { a: number; b: string; }) => void ->mustBeLast : { b: string; } +>mustBeLast : Rest<{ a: number; b: string; }, "a"> >a : number >a : number >b : string } function generic(t: T) { ->generic : (t: T) => any +>generic : (t: T) => Rest >x : any >y : any >t : T let { x, ...rest } = t; >x : any ->rest : any +>rest : Rest >t : T return rest; ->rest : any +>rest : Rest } let rest: { b: string } diff --git a/tests/baselines/reference/objectRestParameter.symbols b/tests/baselines/reference/objectRestParameter.symbols index f629f46e8e9..536689ae567 100644 --- a/tests/baselines/reference/objectRestParameter.symbols +++ b/tests/baselines/reference/objectRestParameter.symbols @@ -21,9 +21,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >x : Symbol(x, Decl(objectRestParameter.ts, 3, 34)) >a : Symbol(a, Decl(objectRestParameter.ts, 4, 11)) >rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) ->rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>rest.y : Symbol(y) >rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) ->y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>y : Symbol(y) suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly : Symbol(suddenly, Decl(objectRestParameter.ts, 1, 1)) @@ -35,12 +35,12 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >z : Symbol(z, Decl(objectRestParameter.ts, 5, 56)) >ka : Symbol(ka, Decl(objectRestParameter.ts, 5, 62)) >y : Symbol(y, Decl(objectRestParameter.ts, 5, 71)) ->rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>rest.y : Symbol(y) >rest : Symbol(rest, Decl(objectRestParameter.ts, 5, 37)) ->y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) ->nested.ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) +>y : Symbol(y) +>nested.ka : Symbol(ka) >nested : Symbol(nested, Decl(objectRestParameter.ts, 5, 24)) ->ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) +>ka : Symbol(ka) class C { >C : Symbol(C, Decl(objectRestParameter.ts, 5, 107)) diff --git a/tests/baselines/reference/objectRestParameter.types b/tests/baselines/reference/objectRestParameter.types index 831ac9df59f..c3d1c4f01f2 100644 --- a/tests/baselines/reference/objectRestParameter.types +++ b/tests/baselines/reference/objectRestParameter.types @@ -2,7 +2,7 @@ function cloneAgain({ a, ...clone }: { a: number, b: string }): void { >cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string } @@ -22,9 +22,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >rest.y : string ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >y : string suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); @@ -34,8 +34,8 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >x : any >z : any >12 : 12 ->nested : { ka: any; } ->rest : { y: string; } +>nested : Rest<{ z: any; ka: any; }, "z"> +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >{ x: { z: 1, ka: 1 }, y: 'noo' } : { x: { z: number; ka: number; }; y: string; } >x : { z: number; ka: number; } >{ z: 1, ka: 1 } : { z: number; ka: number; } @@ -47,10 +47,10 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >'noo' : "noo" >rest.y + nested.ka : string >rest.y : string ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >y : string >nested.ka : any ->nested : { ka: any; } +>nested : Rest<{ z: any; ka: any; }, "z"> >ka : any class C { @@ -59,7 +59,7 @@ class C { m({ a, ...clone }: { a: number, b: string}): void { >m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string @@ -68,7 +68,7 @@ class C { set p({ a, ...clone }: { a: number, b: string}) { >p : { a: number; b: string; } >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string diff --git a/tests/baselines/reference/objectRestParameterES5.symbols b/tests/baselines/reference/objectRestParameterES5.symbols index 4c6b8115169..c397e137799 100644 --- a/tests/baselines/reference/objectRestParameterES5.symbols +++ b/tests/baselines/reference/objectRestParameterES5.symbols @@ -21,9 +21,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >x : Symbol(x, Decl(objectRestParameterES5.ts, 3, 34)) >a : Symbol(a, Decl(objectRestParameterES5.ts, 4, 11)) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 4, 17)) ->rest.y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) +>rest.y : Symbol(y) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 4, 17)) ->y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) +>y : Symbol(y) suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly : Symbol(suddenly, Decl(objectRestParameterES5.ts, 1, 1)) @@ -35,12 +35,12 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >z : Symbol(z, Decl(objectRestParameterES5.ts, 5, 56)) >ka : Symbol(ka, Decl(objectRestParameterES5.ts, 5, 62)) >y : Symbol(y, Decl(objectRestParameterES5.ts, 5, 71)) ->rest.y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) +>rest.y : Symbol(y) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 5, 37)) ->y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) ->nested.ka : Symbol(ka, Decl(objectRestParameterES5.ts, 3, 42)) +>y : Symbol(y) +>nested.ka : Symbol(ka) >nested : Symbol(nested, Decl(objectRestParameterES5.ts, 5, 24)) ->ka : Symbol(ka, Decl(objectRestParameterES5.ts, 3, 42)) +>ka : Symbol(ka) class C { >C : Symbol(C, Decl(objectRestParameterES5.ts, 5, 107)) diff --git a/tests/baselines/reference/objectRestParameterES5.types b/tests/baselines/reference/objectRestParameterES5.types index 1b8dd29e29e..329f69bedcd 100644 --- a/tests/baselines/reference/objectRestParameterES5.types +++ b/tests/baselines/reference/objectRestParameterES5.types @@ -2,7 +2,7 @@ function cloneAgain({ a, ...clone }: { a: number, b: string }): void { >cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string } @@ -22,9 +22,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >rest.y : string ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >y : string suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); @@ -34,8 +34,8 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >x : any >z : any >12 : 12 ->nested : { ka: any; } ->rest : { y: string; } +>nested : Rest<{ z: any; ka: any; }, "z"> +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >{ x: { z: 1, ka: 1 }, y: 'noo' } : { x: { z: number; ka: number; }; y: string; } >x : { z: number; ka: number; } >{ z: 1, ka: 1 } : { z: number; ka: number; } @@ -47,10 +47,10 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >'noo' : "noo" >rest.y + nested.ka : string >rest.y : string ->rest : { y: string; } +>rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> >y : string >nested.ka : any ->nested : { ka: any; } +>nested : Rest<{ z: any; ka: any; }, "z"> >ka : any class C { @@ -59,7 +59,7 @@ class C { m({ a, ...clone }: { a: number, b: string}): void { >m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string @@ -68,7 +68,7 @@ class C { set p({ a, ...clone }: { a: number, b: string}) { >p : { a: number; b: string; } >a : number ->clone : { b: string; } +>clone : Rest<{ a: number; b: string; }, "a"> >a : number >b : string diff --git a/tests/baselines/reference/objectRestReadonly.symbols b/tests/baselines/reference/objectRestReadonly.symbols index f2a7504e9b5..ef32c8b616a 100644 --- a/tests/baselines/reference/objectRestReadonly.symbols +++ b/tests/baselines/reference/objectRestReadonly.symbols @@ -34,7 +34,7 @@ const { foo, ...rest } = obj >obj : Symbol(obj, Decl(objectRestReadonly.ts, 7, 5)) delete rest.baz ->rest.baz : Symbol(baz, Decl(objectRestReadonly.ts, 2, 13)) +>rest.baz : Symbol(baz) >rest : Symbol(rest, Decl(objectRestReadonly.ts, 13, 12)) ->baz : Symbol(baz, Decl(objectRestReadonly.ts, 2, 13)) +>baz : Symbol(baz) diff --git a/tests/baselines/reference/objectRestReadonly.types b/tests/baselines/reference/objectRestReadonly.types index 5f015aeb1e5..d21b5793c66 100644 --- a/tests/baselines/reference/objectRestReadonly.types +++ b/tests/baselines/reference/objectRestReadonly.types @@ -32,12 +32,12 @@ const obj: Readonly = { const { foo, ...rest } = obj >foo : string ->rest : { baz: string; quux: string; } +>rest : Rest, "foo"> >obj : Readonly delete rest.baz >delete rest.baz : boolean >rest.baz : string ->rest : { baz: string; quux: string; } +>rest : Rest, "foo"> >baz : string diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols index 857310bf87c..e3e6dcdc9a4 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols @@ -18,9 +18,9 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { "use strict"; "Some other prologue"; opts.baz(bar); ->opts.baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) +>opts.baz : Symbol(baz) >opts : Symbol(opts, Decl(parameterInitializerBeforeDestructuringEmit.ts, 5, 27)) ->baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) +>baz : Symbol(baz) >bar : Symbol(bar, Decl(parameterInitializerBeforeDestructuringEmit.ts, 5, 17)) } @@ -35,9 +35,9 @@ class C { "use strict"; "Some other prologue"; opts.baz(bar); ->opts.baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) +>opts.baz : Symbol(baz) >opts : Symbol(opts, Decl(parameterInitializerBeforeDestructuringEmit.ts, 12, 27)) ->baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) +>baz : Symbol(baz) >bar : Symbol(bar, Decl(parameterInitializerBeforeDestructuringEmit.ts, 12, 17)) } } diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types index bbdf5580a60..28f71d1362b 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types @@ -11,7 +11,7 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { >foobar : ({ bar, ...opts }?: Foo) => void >bar : any >{} : {} ->opts : { baz?: any; } +>opts : Rest >{} : {} "use strict"; @@ -23,7 +23,7 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { opts.baz(bar); >opts.baz(bar) : any >opts.baz : any ->opts : { baz?: any; } +>opts : Rest >baz : any >bar : any } @@ -34,7 +34,7 @@ class C { constructor({ bar = {}, ...opts }: Foo = {}) { >bar : any >{} : {} ->opts : { baz?: any; } +>opts : Rest >{} : {} "use strict"; @@ -46,7 +46,7 @@ class C { opts.baz(bar); >opts.baz(bar) : any >opts.baz : any ->opts : { baz?: any; } +>opts : Rest >baz : any >bar : any } diff --git a/tests/baselines/reference/parserOverloadOnConstants1.types b/tests/baselines/reference/parserOverloadOnConstants1.types index 6cac9a704a9..2a865af7ba7 100644 --- a/tests/baselines/reference/parserOverloadOnConstants1.types +++ b/tests/baselines/reference/parserOverloadOnConstants1.types @@ -1,18 +1,18 @@ === tests/cases/conformance/parser/ecmascript5/parserOverloadOnConstants1.ts === interface Document { createElement(tagName: string): HTMLElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : string createElement(tagName: 'canvas'): HTMLCanvasElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "canvas" createElement(tagName: 'div'): HTMLDivElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "div" createElement(tagName: 'span'): HTMLSpanElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "span" } diff --git a/tests/baselines/reference/restInvalidArgumentType.errors.txt b/tests/baselines/reference/restInvalidArgumentType.errors.txt index 0cc4faea557..7e0c852316a 100644 --- a/tests/baselines/reference/restInvalidArgumentType.errors.txt +++ b/tests/baselines/reference/restInvalidArgumentType.errors.txt @@ -1,11 +1,5 @@ -tests/cases/compiler/restInvalidArgumentType.ts(27,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(29,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(30,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(31,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(33,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(36,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(37,13): error TS2700: Rest types may only be created from object types. -tests/cases/compiler/restInvalidArgumentType.ts(39,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(40,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(42,13): error TS2700: Rest types may only be created from object types. tests/cases/compiler/restInvalidArgumentType.ts(43,13): error TS2700: Rest types may only be created from object types. @@ -16,7 +10,7 @@ tests/cases/compiler/restInvalidArgumentType.ts(51,13): error TS2700: Rest types tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types may only be created from object types. -==== tests/cases/compiler/restInvalidArgumentType.ts (16 errors) ==== +==== tests/cases/compiler/restInvalidArgumentType.ts (10 errors) ==== enum E { v1, v2 }; function f(p1: T, p2: T[]) { @@ -44,34 +38,22 @@ tests/cases/compiler/restInvalidArgumentType.ts(53,13): error TS2700: Rest types var a: any; var {...r1} = p1; // Error, generic type paramterre - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r2} = p2; // OK var {...r3} = t; // Error, generic type paramter - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r4} = i; // Error, index access - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r5} = k; // Error, index ~~ !!! error TS2700: Rest types may only be created from object types. var {...r6} = mapped_generic; // Error, generic mapped object type - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r7} = mapped; // OK, non-generic mapped type var {...r8} = union_generic; // Error, union with generic type parameter - ~~ -!!! error TS2700: Rest types may only be created from object types. var {...r9} = union_primitive; // Error, union with generic type parameter ~~ !!! error TS2700: Rest types may only be created from object types. var {...r10} = intersection_generic; // Error, intersection with generic type parameter - ~~~ -!!! error TS2700: Rest types may only be created from object types. var {...r11} = intersection_primitive; // Error, intersection with generic type parameter ~~~ !!! error TS2700: Rest types may only be created from object types. diff --git a/tests/baselines/reference/restInvalidArgumentType.types b/tests/baselines/reference/restInvalidArgumentType.types index ce59fb145f9..e04395b2407 100644 --- a/tests/baselines/reference/restInvalidArgumentType.types +++ b/tests/baselines/reference/restInvalidArgumentType.types @@ -67,19 +67,19 @@ function f(p1: T, p2: T[]) { >a : any var {...r1} = p1; // Error, generic type paramterre ->r1 : any +>r1 : T >p1 : T var {...r2} = p2; // OK ->r2 : { [n: number]: T; length: number; toString(): string; toLocaleString(): string; pop(): T; push(...items: T[]): number; concat(...items: ConcatArray[]): T[]; concat(...items: (T | ConcatArray)[]): T[]; join(separator?: string): string; reverse(): T[]; shift(): T; slice(start?: number, end?: number): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; splice(start: number, deleteCount?: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; unshift(...items: T[]): number; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; } +>r2 : T[] >p2 : T[] var {...r3} = t; // Error, generic type paramter ->r3 : any +>r3 : T >t : T var {...r4} = i; // Error, index access ->r4 : any +>r4 : T["b"] >i : T["b"] var {...r5} = k; // Error, index @@ -87,7 +87,7 @@ function f(p1: T, p2: T[]) { >k : keyof T var {...r6} = mapped_generic; // Error, generic mapped object type ->r6 : any +>r6 : { [P in keyof T]: T[P]; } >mapped_generic : { [P in keyof T]: T[P]; } var {...r7} = mapped; // OK, non-generic mapped type @@ -95,7 +95,7 @@ function f(p1: T, p2: T[]) { >mapped : { b: T["b"]; } var {...r8} = union_generic; // Error, union with generic type parameter ->r8 : any +>r8 : T | { a: number; } >union_generic : T | { a: number; } var {...r9} = union_primitive; // Error, union with generic type parameter @@ -103,7 +103,7 @@ function f(p1: T, p2: T[]) { >union_primitive : number | { a: number; } var {...r10} = intersection_generic; // Error, intersection with generic type parameter ->r10 : any +>r10 : T & { a: number; } >intersection_generic : T & { a: number; } var {...r11} = intersection_primitive; // Error, intersection with generic type parameter diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread.types b/tests/baselines/reference/unusedLocalsAndObjectSpread.types index 3fc4ae1e751..233ea57ae6f 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread.types +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread.types @@ -18,7 +18,7 @@ function one() { // 'a' is declared but never used const {a, ...bar} = foo; >a : number ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> >foo : { a: number; b: number; } console.log(bar); @@ -26,7 +26,7 @@ function one() { >console.log : (a: any) => void >console : { log(a: any): void; } >log : (a: any) => void ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> } function two() { @@ -44,7 +44,7 @@ function two() { const {a: _, ...bar} = foo; >a : any >_ : number ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> >foo : { a: number; b: number; } console.log(bar); @@ -52,7 +52,7 @@ function two() { >console.log : (a: any) => void >console : { log(a: any): void; } >log : (a: any) => void ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> } function three() { @@ -69,7 +69,7 @@ function three() { // 'a' is declared but never used const {a, ...bar} = foo; // bar should be unused >a : number ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> >foo : { a: number; b: number; } //console.log(bar); @@ -90,7 +90,7 @@ function four() { const {a: _, ...bar} = foo; // bar should be unused >a : any >_ : number ->bar : { b: number; } +>bar : Rest<{ a: number; b: number; }, "a"> >foo : { a: number; b: number; } //console.log(bar); From deeee77f184c40498a439ca92a2534ae16513810 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 1 Nov 2018 13:46:41 -0700 Subject: [PATCH 188/262] Check destructuring validity the same way element accesses and indexed accesses are checked (#24700) * Check destructuring validity the same way element accesses and indexed accesses are checked * Accept updated test baseline * Use raw apparent type instead of passing in flag to sometimes make one * Use `checkComputedPropertyName` --- src/compiler/checker.ts | 92 +++++++------------ .../reference/ES5For-of27.errors.txt | 8 +- .../reference/ES5For-of29.errors.txt | 8 +- .../reference/ES5For-of35.errors.txt | 8 +- ...blockScopedBindingUsedBeforeDef.errors.txt | 13 ++- ...putedPropertiesInDestructuring1.errors.txt | 32 ++++++- ...dPropertiesInDestructuring1_ES6.errors.txt | 32 ++++++- ...putedPropertiesInDestructuring2.errors.txt | 8 ++ ...dPropertiesInDestructuring2_ES6.errors.txt | 8 ++ .../declarationsAndAssignments.errors.txt | 8 +- ...niteAssignmentOfDestructuredVariable.types | 14 +-- ...redLateBoundNameHasCorrectTypes.errors.txt | 6 +- ...structuredMaappedTypeIsNotImplicitlyAny.js | 16 ++++ ...turedMaappedTypeIsNotImplicitlyAny.symbols | 24 +++++ ...ucturedMaappedTypeIsNotImplicitlyAny.types | 21 +++++ ...ectBindingPatternAndAssignment3.errors.txt | 8 +- ...structuringParameterProperties5.errors.txt | 12 +-- .../reference/downlevelLetConst16.errors.txt | 8 +- .../for-inStatementsDestructuring2.errors.txt | 8 +- .../reference/jsdocParamTag2.errors.txt | 8 +- ...ndDestructuringImplicitAnyError.errors.txt | 36 ++++---- ...teBoundDestructuringImplicitAnyError.types | 8 +- .../nonPrimitiveAccessProperty.errors.txt | 4 +- .../baselines/reference/objectRest.errors.txt | 62 +++++++++++++ tests/baselines/reference/objectRest.types | 4 +- ...ializersForwardReferencing1_es6.errors.txt | 5 +- .../restElementWithBindingPattern2.errors.txt | 4 +- ...structuredMaappedTypeIsNotImplicitlyAny.ts | 8 ++ 28 files changed, 335 insertions(+), 138 deletions(-) create mode 100644 tests/baselines/reference/computedPropertiesInDestructuring2.errors.txt create mode 100644 tests/baselines/reference/computedPropertiesInDestructuring2_ES6.errors.txt create mode 100644 tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.js create mode 100644 tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.symbols create mode 100644 tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.types create mode 100644 tests/baselines/reference/objectRest.errors.txt create mode 100644 tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2418c75f0cb..7df0414b90b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4635,6 +4635,10 @@ namespace ts { if (isTypeAny(parentType)) { return parentType; } + // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation + if (strictNullChecks && declaration.flags & NodeFlags.Ambient && isParameterDeclaration(declaration)) { + parentType = getNonNullableType(parentType); + } let type: Type | undefined; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { @@ -4654,53 +4658,13 @@ namespace ts { else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) const name = declaration.propertyName || declaration.name; - const isLate = isLateBindableName(name); - const isWellKnown = isComputedPropertyName(name) && isWellKnownSymbolSyntactically(name.expression); - if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { - const exprType = checkExpression((name as ComputedPropertyName).expression); - if (isTypeAssignableToKind(exprType, TypeFlags.ESSymbolLike)) { - if (noImplicitAny) { - error(declaration, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); - } - return anyType; - } - const indexerType = isTypeAssignableToKind(exprType, TypeFlags.NumberLike) && getIndexTypeOfType(parentType, IndexKind.Number) || getIndexTypeOfType(parentType, IndexKind.String); - if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(parentType, IndexKind.Number)) { - error(declaration, Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(declaration, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); - } - } - return indexerType || anyType; - } - - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - const nameType = isLate ? checkComputedPropertyName(name as ComputedPropertyName) as LiteralType | UniqueESSymbolType : undefined; - const text = isLate ? getLateBoundNameFromType(nameType!) : - isWellKnown ? getPropertyNameForKnownSymbolName(idText(((name as ComputedPropertyName).expression as PropertyAccessExpression).name)) : - getTextOfPropertyName(name); - - // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & NodeFlags.Ambient && isParameterDeclaration(declaration)) { - parentType = getNonNullableType(parentType); - } - if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, TypeFlags.ESSymbolLike)) { - if (noImplicitAny) { - error(declaration, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); - } - return anyType; - } - const declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); - type = declaredType && getFlowTypeOfReference(declaration, declaredType) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) || - getIndexTypeOfType(parentType, IndexKind.String); - if (!type) { - error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name)); - return errorType; - } + const exprType = isComputedPropertyName(name) + ? checkComputedPropertyName(name) + : isIdentifier(name) + ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) + : checkExpression(name); + const declaredType = checkIndexedAccessIndexType(getIndexedAccessType(getApparentType(parentType), exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -9359,12 +9323,16 @@ namespace ts { return false; } - function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | undefined, cacheSymbol: boolean, missingType: Type) { + function getPropertyTypeForIndexType(objectType: Type, indexType: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName | undefined, cacheSymbol: boolean, missingType: Type) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - const propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) : - undefined; + const propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) + : accessNode && isPropertyName(accessNode) + // late bound names are handled in the first branch, so here we only need to handle normal names + ? getPropertyNameForPropertyNameNode(accessNode) + : undefined; if (propName !== undefined) { const prop = getPropertyOfType(objectType, propName); if (prop) { @@ -9385,7 +9353,7 @@ namespace ts { } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, t => !(t).target.hasRestElement)) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + const indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } return mapType(objectType, t => getRestTypeOfTupleType(t) || undefinedType); @@ -9400,7 +9368,7 @@ namespace ts { undefined; if (indexInfo) { if (accessNode && !isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + const indexNode = getIndexNodeForAccessExpression(accessNode); error(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } else if (accessExpression && indexInfo.isReadonly && (isAssignmentTarget(accessExpression) || isDeleteTarget(accessExpression))) { @@ -9441,7 +9409,7 @@ namespace ts { return anyType; } if (accessNode) { - const indexNode = accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode.argumentExpression : accessNode.indexType; + const indexNode = getIndexNodeForAccessExpression(accessNode); if (indexType.flags & (TypeFlags.StringLiteral | TypeFlags.NumberLiteral)) { error(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + (indexType).value, typeToString(objectType)); } @@ -9458,6 +9426,16 @@ namespace ts { return missingType; } + function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName) { + return accessNode.kind === SyntaxKind.ElementAccessExpression + ? accessNode.argumentExpression + : accessNode.kind === SyntaxKind.IndexedAccessType + ? accessNode.indexType + : accessNode.kind === SyntaxKind.ComputedPropertyName + ? accessNode.expression + : accessNode; + } + function isGenericObjectType(type: Type): boolean { return maybeTypeOfKind(type, TypeFlags.InstantiableNonPrimitive | TypeFlags.GenericMappedType); } @@ -9521,7 +9499,7 @@ namespace ts { return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); } - function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode, missingType = accessNode ? errorType : unknownType): Type { + function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode | PropertyName, missingType = accessNode ? errorType : unknownType): Type { if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -23207,7 +23185,7 @@ namespace ts { forEach(node.types, checkSourceElement); } - function checkIndexedAccessIndexType(type: Type, accessNode: ElementAccessExpression | IndexedAccessTypeNode) { + function checkIndexedAccessIndexType(type: Type, accessNode: Node) { if (!(type.flags & TypeFlags.IndexedAccess)) { return type; } diff --git a/tests/baselines/reference/ES5For-of27.errors.txt b/tests/baselines/reference/ES5For-of27.errors.txt index 0c839859930..837a11cf7ee 100644 --- a/tests/baselines/reference/ES5For-of27.errors.txt +++ b/tests/baselines/reference/ES5For-of27.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,11): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,21): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,11): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,21): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts (2 errors) ==== for (var {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of29.errors.txt b/tests/baselines/reference/ES5For-of29.errors.txt index e669b070222..c23ff1af211 100644 --- a/tests/baselines/reference/ES5For-of29.errors.txt +++ b/tests/baselines/reference/ES5For-of29.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,13): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,23): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,13): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,23): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts (2 errors) ==== for (const {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of35.errors.txt b/tests/baselines/reference/ES5For-of35.errors.txt index 8c43d959888..c22dc96e42d 100644 --- a/tests/baselines/reference/ES5For-of35.errors.txt +++ b/tests/baselines/reference/ES5For-of35.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,13): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,23): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,13): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,23): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts (2 errors) ==== for (const {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt b/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt index 042f5e6de4f..4f04f2babc5 100644 --- a/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt +++ b/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt @@ -1,23 +1,32 @@ tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(2,12): error TS2448: Block-scoped variable 'a' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(2,12): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(5,12): error TS2448: Block-scoped variable 'a' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(5,12): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(8,7): error TS2448: Block-scoped variable 'b' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(8,7): error TS2538: Type 'any' cannot be used as an index type. -==== tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts (3 errors) ==== +==== tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts (6 errors) ==== // 1: for (let {[a]: a} of [{ }]) continue; ~ !!! error TS2448: Block-scoped variable 'a' used before its declaration. !!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:2:16: 'a' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. // 2: for (let {[a]: a} = { }; false; ) continue; ~ !!! error TS2448: Block-scoped variable 'a' used before its declaration. !!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:5:16: 'a' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. // 3: let {[b]: b} = { }; ~ !!! error TS2448: Block-scoped variable 'b' used before its declaration. -!!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:8:11: 'b' is declared here. \ No newline at end of file +!!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:8:11: 'b' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. \ No newline at end of file diff --git a/tests/baselines/reference/computedPropertiesInDestructuring1.errors.txt b/tests/baselines/reference/computedPropertiesInDestructuring1.errors.txt index d2d63a48174..31b938fb3fb 100644 --- a/tests/baselines/reference/computedPropertiesInDestructuring1.errors.txt +++ b/tests/baselines/reference/computedPropertiesInDestructuring1.errors.txt @@ -1,33 +1,63 @@ +tests/cases/compiler/computedPropertiesInDestructuring1.ts(3,7): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(8,7): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(10,8): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(11,8): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(14,15): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(15,15): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(16,16): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(17,16): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. tests/cases/compiler/computedPropertiesInDestructuring1.ts(20,8): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(20,8): error TS2538: Type 'any' cannot be used as an index type. +tests/cases/compiler/computedPropertiesInDestructuring1.ts(21,8): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/computedPropertiesInDestructuring1.ts(21,12): error TS2339: Property 'toExponential' does not exist on type 'string'. tests/cases/compiler/computedPropertiesInDestructuring1.ts(33,4): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. tests/cases/compiler/computedPropertiesInDestructuring1.ts(34,5): error TS2365: Operator '+' cannot be applied to types '1' and '{}'. -==== tests/cases/compiler/computedPropertiesInDestructuring1.ts (4 errors) ==== +==== tests/cases/compiler/computedPropertiesInDestructuring1.ts (14 errors) ==== // destructuring in variable declarations let foo = "bar"; let {[foo]: bar} = {bar: "bar"}; + ~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let {["bar"]: bar2} = {bar: "bar"}; let foo2 = () => "bar"; let {[foo2()]: bar3} = {bar: "bar"}; + ~~~~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let [{[foo]: bar4}] = [{bar: "bar"}]; + ~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let [{[foo2()]: bar5}] = [{bar: "bar"}]; + ~~~~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. function f1({["bar"]: x}: { bar: number }) {} function f2({[foo]: x}: { bar: number }) {} + ~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f3({[foo2()]: x}: { bar: number }) {} + ~~~~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f4([{[foo]: x}]: [{ bar: number }]) {} + ~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f5([{[foo2()]: x}]: [{ bar: number }]) {} + ~~~~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. // report errors on type errors in computed properties used in destructuring let [{[foo()]: bar6}] = [{bar: "bar"}]; ~~~~~ !!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + ~~~~~ +!!! error TS2538: Type 'any' cannot be used as an index type. let [{[foo.toExponential()]: bar7}] = [{bar: "bar"}]; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2538: Type 'any' cannot be used as an index type. ~~~~~~~~~~~~~ !!! error TS2339: Property 'toExponential' does not exist on type 'string'. diff --git a/tests/baselines/reference/computedPropertiesInDestructuring1_ES6.errors.txt b/tests/baselines/reference/computedPropertiesInDestructuring1_ES6.errors.txt index fa4d29cf426..610b8e56ab3 100644 --- a/tests/baselines/reference/computedPropertiesInDestructuring1_ES6.errors.txt +++ b/tests/baselines/reference/computedPropertiesInDestructuring1_ES6.errors.txt @@ -1,34 +1,64 @@ +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(3,7): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(9,7): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(11,8): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(12,8): error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(15,15): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(16,15): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(17,16): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(18,16): error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(21,8): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(21,8): error TS2538: Type 'any' cannot be used as an index type. +tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(22,8): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(22,12): error TS2339: Property 'toExponential' does not exist on type 'string'. tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(34,4): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts(35,5): error TS2365: Operator '+' cannot be applied to types '1' and '{}'. -==== tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts (4 errors) ==== +==== tests/cases/compiler/computedPropertiesInDestructuring1_ES6.ts (14 errors) ==== // destructuring in variable declarations let foo = "bar"; let {[foo]: bar} = {bar: "bar"}; + ~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let {["bar"]: bar2} = {bar: "bar"}; let {[11]: bar2_1} = {11: "bar"}; let foo2 = () => "bar"; let {[foo2()]: bar3} = {bar: "bar"}; + ~~~~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let [{[foo]: bar4}] = [{bar: "bar"}]; + ~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. let [{[foo2()]: bar5}] = [{bar: "bar"}]; + ~~~~~~ +!!! error TS2537: Type '{ bar: string; }' has no matching index signature for type 'string'. function f1({["bar"]: x}: { bar: number }) {} function f2({[foo]: x}: { bar: number }) {} + ~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f3({[foo2()]: x}: { bar: number }) {} + ~~~~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f4([{[foo]: x}]: [{ bar: number }]) {} + ~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. function f5([{[foo2()]: x}]: [{ bar: number }]) {} + ~~~~~~ +!!! error TS2537: Type '{ bar: number; }' has no matching index signature for type 'string'. // report errors on type errors in computed properties used in destructuring let [{[foo()]: bar6}] = [{bar: "bar"}]; ~~~~~ !!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + ~~~~~ +!!! error TS2538: Type 'any' cannot be used as an index type. let [{[foo.toExponential()]: bar7}] = [{bar: "bar"}]; + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2538: Type 'any' cannot be used as an index type. ~~~~~~~~~~~~~ !!! error TS2339: Property 'toExponential' does not exist on type 'string'. diff --git a/tests/baselines/reference/computedPropertiesInDestructuring2.errors.txt b/tests/baselines/reference/computedPropertiesInDestructuring2.errors.txt new file mode 100644 index 00000000000..da858e47c89 --- /dev/null +++ b/tests/baselines/reference/computedPropertiesInDestructuring2.errors.txt @@ -0,0 +1,8 @@ +tests/cases/compiler/computedPropertiesInDestructuring2.ts(2,7): error TS2537: Type '{}' has no matching index signature for type 'string'. + + +==== tests/cases/compiler/computedPropertiesInDestructuring2.ts (1 errors) ==== + let foo2 = () => "bar"; + let {[foo2()]: bar3} = {}; + ~~~~~~ +!!! error TS2537: Type '{}' has no matching index signature for type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/computedPropertiesInDestructuring2_ES6.errors.txt b/tests/baselines/reference/computedPropertiesInDestructuring2_ES6.errors.txt new file mode 100644 index 00000000000..529cc2ebef8 --- /dev/null +++ b/tests/baselines/reference/computedPropertiesInDestructuring2_ES6.errors.txt @@ -0,0 +1,8 @@ +tests/cases/compiler/computedPropertiesInDestructuring2_ES6.ts(2,7): error TS2537: Type '{}' has no matching index signature for type 'string'. + + +==== tests/cases/compiler/computedPropertiesInDestructuring2_ES6.ts (1 errors) ==== + let foo2 = () => "bar"; + let {[foo2()]: bar3} = {}; + ~~~~~~ +!!! error TS2537: Type '{}' has no matching index signature for type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/declarationsAndAssignments.errors.txt b/tests/baselines/reference/declarationsAndAssignments.errors.txt index 46536d6fff0..3ae6d587da5 100644 --- a/tests/baselines/reference/declarationsAndAssignments.errors.txt +++ b/tests/baselines/reference/declarationsAndAssignments.errors.txt @@ -15,8 +15,8 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(67,9): e tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(68,9): error TS2461: Type '{ 0: number; 1: number; }' is not an array type. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(73,11): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(73,14): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. -tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,11): error TS2459: Type 'undefined[]' has no property 'a' and no string index signature. -tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,14): error TS2459: Type 'undefined[]' has no property 'b' and no string index signature. +tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,11): error TS2339: Property 'a' does not exist on type 'undefined[]'. +tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(74,14): error TS2339: Property 'b' does not exist on type 'undefined[]'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(106,17): error TS2322: Type '{ y: boolean; }' is not assignable to type '{ x: any; y?: boolean; }'. Property 'x' is missing in type '{ y: boolean; }'. tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,6): error TS2322: Type 'string' is not assignable to type 'number'. @@ -133,9 +133,9 @@ tests/cases/conformance/es6/destructuring/declarationsAndAssignments.ts(138,9): !!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value. var { a, b } = []; // Error ~ -!!! error TS2459: Type 'undefined[]' has no property 'a' and no string index signature. +!!! error TS2339: Property 'a' does not exist on type 'undefined[]'. ~ -!!! error TS2459: Type 'undefined[]' has no property 'b' and no string index signature. +!!! error TS2339: Property 'b' does not exist on type 'undefined[]'. } function f11() { diff --git a/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types b/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types index 96d632736dd..fb40a9b492e 100644 --- a/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types +++ b/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types @@ -18,20 +18,20 @@ class C { >method : () => void let { a, b } = this.foo; ->a : T["a"] ->b : T["b"] +>a : { [P in keyof T]: T[P]; }["a"] +>b : { [P in keyof T]: T[P]; }["b"] >this.foo : { [P in keyof T]: T[P]; } >this : this >foo : { [P in keyof T]: T[P]; } !(a && b); >!(a && b) : false ->(a && b) : T["b"] ->a && b : T["b"] ->a : T["a"] ->b : T["b"] +>(a && b) : { [P in keyof T]: T[P]; }["b"] +>a && b : { [P in keyof T]: T[P]; }["b"] +>a : { [P in keyof T]: T[P]; }["a"] +>b : { [P in keyof T]: T[P]; }["b"] a; ->a : T["a"] +>a : { [P in keyof T]: T[P]; }["a"] } } diff --git a/tests/baselines/reference/destructuredLateBoundNameHasCorrectTypes.errors.txt b/tests/baselines/reference/destructuredLateBoundNameHasCorrectTypes.errors.txt index 6a5c50021db..100ce2d9a08 100644 --- a/tests/baselines/reference/destructuredLateBoundNameHasCorrectTypes.errors.txt +++ b/tests/baselines/reference/destructuredLateBoundNameHasCorrectTypes.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,7): error TS2459: Type '{ prop: string; }' has no property '[notPresent]' and no string index signature. +tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,8): error TS2339: Property 'prop2' does not exist on type '{ prop: string; }'. ==== tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts (1 errors) ==== @@ -13,6 +13,6 @@ tests/cases/compiler/destructuredLateBoundNameHasCorrectTypes.ts(11,7): error TS const notPresent = "prop2"; let { [notPresent]: computed2 } = { prop: "b" }; - ~~~~~~~~~~~~ -!!! error TS2459: Type '{ prop: string; }' has no property '[notPresent]' and no string index signature. + ~~~~~~~~~~ +!!! error TS2339: Property 'prop2' does not exist on type '{ prop: string; }'. \ No newline at end of file diff --git a/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.js b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.js new file mode 100644 index 00000000000..3fe1f2febcc --- /dev/null +++ b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.js @@ -0,0 +1,16 @@ +//// [destructuredMaappedTypeIsNotImplicitlyAny.ts] +function foo(key: T, obj: { [_ in T]: number }) { + const { [key]: bar } = obj; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature. + bar; // bar : any + + // Note: this does work: + const lorem = obj[key]; +} + +//// [destructuredMaappedTypeIsNotImplicitlyAny.js] +function foo(key, obj) { + var _a = key, bar = obj[_a]; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature. + bar; // bar : any + // Note: this does work: + var lorem = obj[key]; +} diff --git a/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.symbols b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.symbols new file mode 100644 index 00000000000..93bd2be6638 --- /dev/null +++ b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.symbols @@ -0,0 +1,24 @@ +=== tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts === +function foo(key: T, obj: { [_ in T]: number }) { +>foo : Symbol(foo, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 0)) +>T : Symbol(T, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 13)) +>key : Symbol(key, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 31)) +>T : Symbol(T, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 13)) +>obj : Symbol(obj, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 38)) +>_ : Symbol(_, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 47)) +>T : Symbol(T, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 13)) + + const { [key]: bar } = obj; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature. +>key : Symbol(key, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 31)) +>bar : Symbol(bar, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 1, 11)) +>obj : Symbol(obj, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 38)) + + bar; // bar : any +>bar : Symbol(bar, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 1, 11)) + + // Note: this does work: + const lorem = obj[key]; +>lorem : Symbol(lorem, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 5, 9)) +>obj : Symbol(obj, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 38)) +>key : Symbol(key, Decl(destructuredMaappedTypeIsNotImplicitlyAny.ts, 0, 31)) +} diff --git a/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.types b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.types new file mode 100644 index 00000000000..493eabe1e2a --- /dev/null +++ b/tests/baselines/reference/destructuredMaappedTypeIsNotImplicitlyAny.types @@ -0,0 +1,21 @@ +=== tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts === +function foo(key: T, obj: { [_ in T]: number }) { +>foo : (key: T, obj: { [_ in T]: number; }) => void +>key : T +>obj : { [_ in T]: number; } + + const { [key]: bar } = obj; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature. +>key : T +>bar : { [_ in T]: number; }[T] +>obj : { [_ in T]: number; } + + bar; // bar : any +>bar : { [_ in T]: number; }[T] + + // Note: this does work: + const lorem = obj[key]; +>lorem : { [_ in T]: number; }[T] +>obj[key] : { [_ in T]: number; }[T] +>obj : { [_ in T]: number; } +>key : T +} diff --git a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt index 33344b9b5eb..5a906d7d43e 100644 --- a/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt +++ b/tests/baselines/reference/destructuringObjectBindingPatternAndAssignment3.errors.txt @@ -1,8 +1,8 @@ tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(2,7): error TS1005: ',' expected. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(3,5): error TS2322: Type '{ i: number; }' is not assignable to type 'string | number'. Type '{ i: number; }' is not assignable to type 'number'. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(3,6): error TS2459: Type 'string | number' has no property 'i' and no string index signature. -tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(4,6): error TS2459: Type 'string | number | {}' has no property 'i1' and no string index signature. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(3,6): error TS2339: Property 'i' does not exist on type 'string | number'. +tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(4,6): error TS2339: Property 'i1' does not exist on type 'string | number | {}'. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(5,12): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(5,21): error TS2353: Object literal may only specify known properties, and 'f212' does not exist in type '{ f21: any; }'. tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAssignment3.ts(6,7): error TS1005: ':' expected. @@ -20,10 +20,10 @@ tests/cases/conformance/es6/destructuring/destructuringObjectBindingPatternAndAs !!! error TS2322: Type '{ i: number; }' is not assignable to type 'string | number'. !!! error TS2322: Type '{ i: number; }' is not assignable to type 'number'. ~ -!!! error TS2459: Type 'string | number' has no property 'i' and no string index signature. +!!! error TS2339: Property 'i' does not exist on type 'string | number'. var {i1}: string | number| {} = { i1: 2 }; ~~ -!!! error TS2459: Type 'string | number | {}' has no property 'i1' and no string index signature. +!!! error TS2339: Property 'i1' does not exist on type 'string | number | {}'. var { f2: {f21} = { f212: "string" } }: any = undefined; ~~~ !!! error TS2525: Initializer provides no value for this binding element and the binding element has no default value. diff --git a/tests/baselines/reference/destructuringParameterProperties5.errors.txt b/tests/baselines/reference/destructuringParameterProperties5.errors.txt index 44e013fad0b..fa57ae150a0 100644 --- a/tests/baselines/reference/destructuringParameterProperties5.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties5.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,17): error TS1187: A parameter property may not be declared using a binding pattern. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,27): error TS2459: Type 'ObjType1' has no property 'x1' and no string index signature. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,31): error TS2459: Type 'ObjType1' has no property 'x2' and no string index signature. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,35): error TS2459: Type 'ObjType1' has no property 'x3' and no string index signature. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,27): error TS2339: Property 'x1' does not exist on type 'ObjType1'. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,31): error TS2339: Property 'x2' does not exist on type 'ObjType1'. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,35): error TS2339: Property 'x3' does not exist on type 'ObjType1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,29): error TS2339: Property 'x1' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,40): error TS2339: Property 'x2' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(7,51): error TS2339: Property 'x3' does not exist on type 'C1'. @@ -22,11 +22,11 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS1187: A parameter property may not be declared using a binding pattern. ~~ -!!! error TS2459: Type 'ObjType1' has no property 'x1' and no string index signature. +!!! error TS2339: Property 'x1' does not exist on type 'ObjType1'. ~~ -!!! error TS2459: Type 'ObjType1' has no property 'x2' and no string index signature. +!!! error TS2339: Property 'x2' does not exist on type 'ObjType1'. ~~ -!!! error TS2459: Type 'ObjType1' has no property 'x3' and no string index signature. +!!! error TS2339: Property 'x3' does not exist on type 'ObjType1'. var foo: any = x1 || x2 || x3 || y || z; var bar: any = this.x1 || this.x2 || this.x3 || this.y || this.z; ~~ diff --git a/tests/baselines/reference/downlevelLetConst16.errors.txt b/tests/baselines/reference/downlevelLetConst16.errors.txt index 905d1a607e8..955c79378fe 100644 --- a/tests/baselines/reference/downlevelLetConst16.errors.txt +++ b/tests/baselines/reference/downlevelLetConst16.errors.txt @@ -1,9 +1,9 @@ tests/cases/compiler/downlevelLetConst16.ts(151,15): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/compiler/downlevelLetConst16.ts(164,17): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. tests/cases/compiler/downlevelLetConst16.ts(195,14): error TS2461: Type 'undefined' is not an array type. -tests/cases/compiler/downlevelLetConst16.ts(202,15): error TS2459: Type 'undefined' has no property 'a' and no string index signature. +tests/cases/compiler/downlevelLetConst16.ts(202,15): error TS2339: Property 'a' does not exist on type 'undefined'. tests/cases/compiler/downlevelLetConst16.ts(216,16): error TS2461: Type 'undefined' is not an array type. -tests/cases/compiler/downlevelLetConst16.ts(223,17): error TS2459: Type 'undefined' has no property 'a' and no string index signature. +tests/cases/compiler/downlevelLetConst16.ts(223,17): error TS2339: Property 'a' does not exist on type 'undefined'. ==== tests/cases/compiler/downlevelLetConst16.ts (6 errors) ==== @@ -216,7 +216,7 @@ tests/cases/compiler/downlevelLetConst16.ts(223,17): error TS2459: Type 'undefin function foo9() { for (let {a: x} of []) { ~ -!!! error TS2459: Type 'undefined' has no property 'a' and no string index signature. +!!! error TS2339: Property 'a' does not exist on type 'undefined'. use(x); } use(x); @@ -241,7 +241,7 @@ tests/cases/compiler/downlevelLetConst16.ts(223,17): error TS2459: Type 'undefin function foo12() { for (const {a: x} of []) { ~ -!!! error TS2459: Type 'undefined' has no property 'a' and no string index signature. +!!! error TS2339: Property 'a' does not exist on type 'undefined'. use(x); } use(x); diff --git a/tests/baselines/reference/for-inStatementsDestructuring2.errors.txt b/tests/baselines/reference/for-inStatementsDestructuring2.errors.txt index 7589610a64e..5d80cf26ebc 100644 --- a/tests/baselines/reference/for-inStatementsDestructuring2.errors.txt +++ b/tests/baselines/reference/for-inStatementsDestructuring2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts(1,10): error TS2491: The left-hand side of a 'for...in' statement cannot be a destructuring pattern. -tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts(1,11): error TS2459: Type 'string' has no property 'a' and no string index signature. -tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts(1,14): error TS2459: Type 'string' has no property 'b' and no string index signature. +tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts(1,11): error TS2339: Property 'a' does not exist on type 'String'. +tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts(1,14): error TS2339: Property 'b' does not exist on type 'String'. ==== tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructuring2.ts (3 errors) ==== @@ -8,6 +8,6 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsDestructurin ~~~~~~ !!! error TS2491: The left-hand side of a 'for...in' statement cannot be a destructuring pattern. ~ -!!! error TS2459: Type 'string' has no property 'a' and no string index signature. +!!! error TS2339: Property 'a' does not exist on type 'String'. ~ -!!! error TS2459: Type 'string' has no property 'b' and no string index signature. \ No newline at end of file +!!! error TS2339: Property 'b' does not exist on type 'String'. \ No newline at end of file diff --git a/tests/baselines/reference/jsdocParamTag2.errors.txt b/tests/baselines/reference/jsdocParamTag2.errors.txt index e19140b3f9d..cbf6140ee7d 100644 --- a/tests/baselines/reference/jsdocParamTag2.errors.txt +++ b/tests/baselines/reference/jsdocParamTag2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/jsdoc/0.js(56,20): error TS8024: JSDoc '@param' tag has name 'obj', but there is no parameter with that name. -tests/cases/conformance/jsdoc/0.js(61,19): error TS2459: Type 'string' has no property 'a' and no string index signature. -tests/cases/conformance/jsdoc/0.js(61,22): error TS2459: Type 'string' has no property 'b' and no string index signature. +tests/cases/conformance/jsdoc/0.js(61,19): error TS2339: Property 'a' does not exist on type 'String'. +tests/cases/conformance/jsdoc/0.js(61,22): error TS2339: Property 'b' does not exist on type 'String'. tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has name 'y', but there is no parameter with that name. @@ -69,9 +69,9 @@ tests/cases/conformance/jsdoc/0.js(63,20): error TS8024: JSDoc '@param' tag has */ function bad1(x, {a, b}) {} ~ -!!! error TS2459: Type 'string' has no property 'a' and no string index signature. +!!! error TS2339: Property 'a' does not exist on type 'String'. ~ -!!! error TS2459: Type 'string' has no property 'b' and no string index signature. +!!! error TS2339: Property 'b' does not exist on type 'String'. /** * @param {string} y - here, y's type gets ignored but obj's is fine ~ diff --git a/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.errors.txt b/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.errors.txt index 2e926ac1b83..edba02d2939 100644 --- a/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.errors.txt +++ b/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.errors.txt @@ -1,16 +1,16 @@ -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(2,15): error TS7017: Element implicitly has an 'any' type because type '{ prop: string; }' has no index signature. -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(13,15): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(21,15): error TS2536: Type 'unique symbol' cannot be used to index type '{ [idx: number]: string; }'. -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(23,15): error TS2536: Type 'unique symbol' cannot be used to index type '{ [idx: string]: string; }'. -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(25,16): error TS2536: Type 'symbol' cannot be used to index type '{ [idx: number]: string; }'. -tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(27,16): error TS2536: Type 'symbol' cannot be used to index type '{ [idx: string]: string; }'. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(2,7): error TS2537: Type '{ prop: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(13,7): error TS2537: Type '{ [idx: number]: string; }' has no matching index signature for type 'string'. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(21,7): error TS2538: Type 'unique symbol' cannot be used as an index type. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(23,7): error TS2538: Type 'unique symbol' cannot be used as an index type. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(25,7): error TS2538: Type 'symbol' cannot be used as an index type. +tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(27,7): error TS2538: Type 'symbol' cannot be used as an index type. ==== tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts (6 errors) ==== let named = "foo"; let {[named]: prop} = {prop: "foo"}; - ~~~~ -!!! error TS7017: Element implicitly has an 'any' type because type '{ prop: string; }' has no index signature. + ~~~~~ +!!! error TS2537: Type '{ prop: string; }' has no matching index signature for type 'string'. void prop; const numIndexed: {[idx: number]: string} = null as any; @@ -22,8 +22,8 @@ tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(27,16): error TS2 let symed2 = Symbol(); let {[named]: prop2} = numIndexed; - ~~~~~ -!!! error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. + ~~~~~ +!!! error TS2537: Type '{ [idx: number]: string; }' has no matching index signature for type 'string'. void prop2; let {[numed]: prop3} = numIndexed; void prop3; @@ -32,18 +32,18 @@ tests/cases/compiler/lateBoundDestructuringImplicitAnyError.ts(27,16): error TS2 let {[numed]: prop5} = strIndexed; void prop5; let {[symed]: prop6} = numIndexed; - ~~~~~ -!!! error TS2536: Type 'unique symbol' cannot be used to index type '{ [idx: number]: string; }'. + ~~~~~ +!!! error TS2538: Type 'unique symbol' cannot be used as an index type. void prop6; let {[symed]: prop7} = strIndexed; - ~~~~~ -!!! error TS2536: Type 'unique symbol' cannot be used to index type '{ [idx: string]: string; }'. + ~~~~~ +!!! error TS2538: Type 'unique symbol' cannot be used as an index type. void prop7; let {[symed2]: prop8} = numIndexed; - ~~~~~ -!!! error TS2536: Type 'symbol' cannot be used to index type '{ [idx: number]: string; }'. + ~~~~~~ +!!! error TS2538: Type 'symbol' cannot be used as an index type. void prop8; let {[symed2]: prop9} = strIndexed; - ~~~~~ -!!! error TS2536: Type 'symbol' cannot be used to index type '{ [idx: string]: string; }'. + ~~~~~~ +!!! error TS2538: Type 'symbol' cannot be used as an index type. void prop9; \ No newline at end of file diff --git a/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.types b/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.types index 92d2c4c662c..60c220095ad 100644 --- a/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.types +++ b/tests/baselines/reference/lateBoundDestructuringImplicitAnyError.types @@ -87,12 +87,12 @@ void prop6; let {[symed]: prop7} = strIndexed; >symed : unique symbol ->prop7 : any +>prop7 : string >strIndexed : { [idx: string]: string; } void prop7; >void prop7 : undefined ->prop7 : any +>prop7 : string let {[symed2]: prop8} = numIndexed; >symed2 : symbol @@ -105,10 +105,10 @@ void prop8; let {[symed2]: prop9} = strIndexed; >symed2 : symbol ->prop9 : any +>prop9 : string >strIndexed : { [idx: string]: string; } void prop9; >void prop9 : undefined ->prop9 : any +>prop9 : string diff --git a/tests/baselines/reference/nonPrimitiveAccessProperty.errors.txt b/tests/baselines/reference/nonPrimitiveAccessProperty.errors.txt index 0a6dfa66b86..c584dba6462 100644 --- a/tests/baselines/reference/nonPrimitiveAccessProperty.errors.txt +++ b/tests/baselines/reference/nonPrimitiveAccessProperty.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/types/nonPrimitive/nonPrimitiveAccessProperty.ts(3,3): error TS2339: Property 'nonExist' does not exist on type 'object'. -tests/cases/conformance/types/nonPrimitive/nonPrimitiveAccessProperty.ts(5,7): error TS2459: Type 'object' has no property 'destructuring' and no string index signature. +tests/cases/conformance/types/nonPrimitive/nonPrimitiveAccessProperty.ts(5,7): error TS2339: Property 'destructuring' does not exist on type '{}'. ==== tests/cases/conformance/types/nonPrimitive/nonPrimitiveAccessProperty.ts (2 errors) ==== @@ -11,6 +11,6 @@ tests/cases/conformance/types/nonPrimitive/nonPrimitiveAccessProperty.ts(5,7): e var { destructuring } = a; // error ~~~~~~~~~~~~~ -!!! error TS2459: Type 'object' has no property 'destructuring' and no string index signature. +!!! error TS2339: Property 'destructuring' does not exist on type '{}'. var { ...rest } = a; // ok \ No newline at end of file diff --git a/tests/baselines/reference/objectRest.errors.txt b/tests/baselines/reference/objectRest.errors.txt new file mode 100644 index 00000000000..709a2d3cdd6 --- /dev/null +++ b/tests/baselines/reference/objectRest.errors.txt @@ -0,0 +1,62 @@ +tests/cases/conformance/types/rest/objectRest.ts(7,12): error TS2339: Property '0' does not exist on type 'String'. +tests/cases/conformance/types/rest/objectRest.ts(7,20): error TS2339: Property '1' does not exist on type 'String'. +tests/cases/conformance/types/rest/objectRest.ts(43,8): error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. +tests/cases/conformance/types/rest/objectRest.ts(43,35): error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. + + +==== tests/cases/conformance/types/rest/objectRest.ts (4 errors) ==== + var o = { a: 1, b: 'no' } + var { ...clone } = o; + var { a, ...justB } = o; + var { a, b: renamed, ...empty } = o; + var { ['b']: renamed, ...justA } = o; + var { 'b': renamed, ...justA } = o; + var { b: { '0': n, '1': oooo }, ...justA } = o; + ~~~ +!!! error TS2339: Property '0' does not exist on type 'String'. + ~~~ +!!! error TS2339: Property '1' does not exist on type 'String'. + + let o2 = { c: 'terrible idea?', d: 'yes' }; + var { d: renamed, ...d } = o2; + + let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; + var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; + + let complex: { x: { ka, ki }, y: number }; + var { x: { ka, ...nested }, y: other, ...rest } = complex; + ({x: { ka, ...nested }, y: other, ...rest} = complex); + var { x, ...fresh } = { x: 1, y: 2 }; + ({ x, ...fresh } = { x: 1, y: 2 }); + + class Removable { + private x: number; + protected y: number; + set z(value: number) { } + get both(): number { return 12 } + set both(value: number) { } + m() { } + removed: string; + remainder: string; + } + interface I { + m(): void; + removed: string; + remainder: string; + } + var removable = new Removable(); + var { removed, ...removableRest } = removable; + var i: I = removable; + var { removed, ...removableRest2 } = i; + + let computed = 'b'; + let computed2 = 'a'; + var { [computed]: stillNotGreat, [computed2]: soSo, ...o } = o; + ~~~~~~~~ +!!! error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. + ~~~~~~~~~ +!!! error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. + ({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); + + var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; + \ No newline at end of file diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types index cb50daf9c4b..dfce7e47912 100644 --- a/tests/baselines/reference/objectRest.types +++ b/tests/baselines/reference/objectRest.types @@ -36,8 +36,8 @@ var { 'b': renamed, ...justA } = o; var { b: { '0': n, '1': oooo }, ...justA } = o; >b : any ->n : string ->oooo : string +>n : any +>oooo : any >justA : { a: number; } >o : { a: number; b: string; } diff --git a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt index 59280d2006a..c65f327161e 100644 --- a/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt +++ b/tests/baselines/reference/parameterInitializersForwardReferencing1_es6.errors.txt @@ -1,9 +1,10 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(13,20): error TS2373: Initializer of parameter 'bar' cannot reference identifier 'foo' declared after it. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(21,18): error TS2372: Parameter 'a' cannot be referenced in its initializer. tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(25,22): error TS2372: Parameter 'async' cannot be referenced in its initializer. +tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts(29,15): error TS2537: Type 'any[]' has no matching index signature for type 'string'. -==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts (3 errors) ==== +==== tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.ts (4 errors) ==== let foo: string = ""; function f1 (bar = foo) { // unexpected compiler error; works at runtime @@ -39,6 +40,8 @@ tests/cases/conformance/functions/parameterInitializersForwardReferencing1_es6.t } function f7({[foo]: bar}: any[]) { + ~~~ +!!! error TS2537: Type 'any[]' has no matching index signature for type 'string'. let foo: number = 2; } diff --git a/tests/baselines/reference/restElementWithBindingPattern2.errors.txt b/tests/baselines/reference/restElementWithBindingPattern2.errors.txt index 8e744ac54a3..44e2c8f13ed 100644 --- a/tests/baselines/reference/restElementWithBindingPattern2.errors.txt +++ b/tests/baselines/reference/restElementWithBindingPattern2.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/destructuring/restElementWithBindingPattern2.ts(1,16): error TS2459: Type 'number[]' has no property 'b' and no string index signature. +tests/cases/conformance/es6/destructuring/restElementWithBindingPattern2.ts(1,16): error TS2339: Property 'b' does not exist on type 'number[]'. ==== tests/cases/conformance/es6/destructuring/restElementWithBindingPattern2.ts (1 errors) ==== var [...{0: a, b }] = [0, 1]; ~ -!!! error TS2459: Type 'number[]' has no property 'b' and no string index signature. \ No newline at end of file +!!! error TS2339: Property 'b' does not exist on type 'number[]'. \ No newline at end of file diff --git a/tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts b/tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts new file mode 100644 index 00000000000..4fd88fd5c8e --- /dev/null +++ b/tests/cases/compiler/destructuredMaappedTypeIsNotImplicitlyAny.ts @@ -0,0 +1,8 @@ +// @noImplicitAny: true +function foo(key: T, obj: { [_ in T]: number }) { + const { [key]: bar } = obj; // Element implicitly has an 'any' type because type '{ [_ in T]: number; }' has no index signature. + bar; // bar : any + + // Note: this does work: + const lorem = obj[key]; +} \ No newline at end of file From eabbaa415f510d1edf4b67d498155bb1915d082d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 1 Nov 2018 15:10:21 -0700 Subject: [PATCH 189/262] Fix `symbolCanBeReferencedAtTypeLocation` for namespace that exports itself (#28295) --- src/services/completions.ts | 24 ++++++------------- .../completionsRecursiveNamespace.ts | 9 +++++++ 2 files changed, 16 insertions(+), 17 deletions(-) create mode 100644 tests/cases/fourslash/completionsRecursiveNamespace.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index f1e33087fdc..1573db9a249 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1128,23 +1128,13 @@ namespace ts.Completions { return false; } - function symbolCanBeReferencedAtTypeLocation(symbol: Symbol): boolean { - symbol = symbol.exportSymbol || symbol; - - // This is an alias, follow what it aliases - symbol = skipAlias(symbol, typeChecker); - - if (symbol.flags & SymbolFlags.Type) { - return true; - } - - if (symbol.flags & SymbolFlags.Module) { - const exportedSymbols = typeChecker.getExportsOfModule(symbol); - // If the exported symbols contains type, - // symbol can be referenced at locations where type is allowed - return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation); - } - return false; + /** True if symbol is a type or a module containing at least one type. */ + function symbolCanBeReferencedAtTypeLocation(symbol: Symbol, seenModules = createMap()): boolean { + const sym = skipAlias(symbol.exportSymbol || symbol, typeChecker); + return !!(sym.flags & SymbolFlags.Type) || + !!(sym.flags & SymbolFlags.Module) && + addToSeen(seenModules, getSymbolId(sym)) && + typeChecker.getExportsOfModule(sym).some(e => symbolCanBeReferencedAtTypeLocation(e, seenModules)); } function getSymbolsFromOtherSourceFileExports(symbols: Symbol[], tokenText: string, target: ScriptTarget): void { diff --git a/tests/cases/fourslash/completionsRecursiveNamespace.ts b/tests/cases/fourslash/completionsRecursiveNamespace.ts new file mode 100644 index 00000000000..687399b587e --- /dev/null +++ b/tests/cases/fourslash/completionsRecursiveNamespace.ts @@ -0,0 +1,9 @@ +/// + +////declare namespace N { +//// export import M = N; +////} +////type T = N./**/ + +// Previously this would crash in `symbolCanBeReferencedAtTypeLocation` due to the namespace exporting itself. +verify.completions({ marker: "", exact: undefined }); From 77ef9cedab43f99036ba569f8377d30c88aefd02 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 1 Nov 2018 10:12:46 -0700 Subject: [PATCH 190/262] Report error summary in pretty mode during normal compilation --- src/compiler/commandLineParser.ts | 14 ++--- src/compiler/diagnosticMessages.json | 8 +++ src/compiler/tsbuild.ts | 57 ++++++++++++------- src/compiler/watch.ts | 37 ++++++++---- src/harness/harness.ts | 3 + src/tsc/tsc.ts | 20 ++++++- .../deeplyNestedAssignabilityIssue.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans1.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans2.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans3.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans4.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans5.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans6.errors.txt | 4 +- ...uplicateIdentifierRelatedSpans7.errors.txt | 4 +- ...opPrettyErrorRelatedInformation.errors.txt | 4 +- ...LineContextDiagnosticWithPretty.errors.txt | 4 +- .../prettyContextNotDebugAssertion.errors.txt | 4 +- .../reference/typedefCrossModule5.errors.txt | 4 +- 18 files changed, 134 insertions(+), 53 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 18987466352..078a158f8f8 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -104,6 +104,13 @@ namespace ts { category: Diagnostics.Advanced_Options, description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, { name: "traceResolution", @@ -157,13 +164,6 @@ namespace ts { category: Diagnostics.Command_line_Options, description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date }, - { - name: "pretty", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, { name: "showConfig", type: "boolean", diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 01aa861cabb..e2dd0a1b7cd 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3771,6 +3771,14 @@ "category": "Message", "code": 6215 }, + "Found 1 error.": { + "category": "Message", + "code": 6216 + }, + "Found {0} errors.": { + "category": "Message", + "code": 6217 + }, "Projects to reference": { "category": "Message", diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index c2215b22ebf..4b9e75102b6 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -29,6 +29,9 @@ namespace ts { preserveWatchOutput?: boolean; listEmittedFiles?: boolean; listFiles?: boolean; + pretty?: boolean; + + traceResolution?: boolean; } enum BuildResultFlags { @@ -316,7 +319,7 @@ namespace ts { return fileExtensionIs(fileName, Extension.Dts); } - export interface SolutionBuilderHost extends CompilerHost { + export interface SolutionBuilderHostBase extends CompilerHost { getModifiedTime(fileName: string): Date | undefined; setModifiedTime(fileName: string, date: Date): void; deleteFile(fileName: string): void; @@ -325,13 +328,18 @@ namespace ts { reportSolutionBuilderStatus: DiagnosticReporter; } - export interface SolutionBuilderWithWatchHost extends SolutionBuilderHost, WatchHost { + export interface SolutionBuilderHost extends SolutionBuilderHostBase { + reportErrorSummary?: ReportEmitErrorSummary; + } + + export interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost { } export interface SolutionBuilder { buildAllProjects(): ExitStatus; cleanAllProjects(): ExitStatus; + // TODO:: All the below ones should technically only be in watch mode. but thats for later time /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; @@ -340,7 +348,9 @@ namespace ts { /*@internal*/ buildInvalidatedProject(): void; /*@internal*/ resetBuildContext(opts?: BuildOptions): void; + } + export interface SolutionBuilderWithWatch extends SolutionBuilder { /*@internal*/ startWatching(): void; } @@ -355,8 +365,8 @@ namespace ts { }; } - export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { - const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) as SolutionBuilderHost; + function createSolutionBuilderHostBase(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { + const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) as SolutionBuilderHostBase; host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime!(path) : () => undefined; host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime!(path, date) : noop; host.deleteFile = system.deleteFile ? path => system.deleteFile!(path) : noop; @@ -365,8 +375,14 @@ namespace ts { return host; } - export function createSolutionBuilderWithWatchHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { - const host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; + export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) { + const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost; + host.reportErrorSummary = reportErrorSummary; + return host; + } + + export function createSolutionBuilderWithWatchHost(system?: System, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { + const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; const watchHost = createWatchHost(system, reportWatchStatus); host.onWatchStatusChange = watchHost.onWatchStatusChange; host.watchFile = watchHost.watchFile; @@ -390,7 +406,9 @@ namespace ts { * TODO: use SolutionBuilderWithWatchHost => watchedSolution * use SolutionBuilderHost => Solution */ - export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder { + export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder; + export function createSolutionBuilder(host: SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilderWithWatch; + export function createSolutionBuilder(host: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilderWithWatch { const hostWithWatch = host as SolutionBuilderWithWatchHost; const currentDirectory = host.getCurrentDirectory(); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); @@ -803,9 +821,7 @@ namespace ts { globalDependencyGraph = undefined; } projectStatus.removeKey(resolved); - if (options.watch) { - diagnostics.removeKey(resolved); - } + diagnostics.removeKey(resolved); addProjToQueue(resolved, reloadLevel); } @@ -874,7 +890,7 @@ namespace ts { } function reportErrorSummary() { - if (options.watch) { + if (options.watch || (host as SolutionBuilderHost).reportErrorSummary) { // Report errors from the other projects getGlobalDependencyGraph().buildQueue.forEach(project => { if (!projectErrorsReported.hasKey(project)) { @@ -882,8 +898,13 @@ namespace ts { } }); let totalErrors = 0; - diagnostics.forEach(singleProjectErrors => totalErrors += singleProjectErrors.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); - reportWatchStatus(totalErrors === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors); + diagnostics.forEach(singleProjectErrors => totalErrors += getErrorCountForSummary(singleProjectErrors)); + if (options.watch) { + reportWatchStatus(getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); + } + else { + (host as SolutionBuilderHost).reportErrorSummary!(totalErrors); + } } } @@ -1066,9 +1087,7 @@ namespace ts { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - if (options.watch) { - diagnostics.removeKey(proj); - } + diagnostics.removeKey(proj); projectStatus.setValue(proj, status); return resultFlags; @@ -1207,10 +1226,8 @@ namespace ts { function reportAndStoreErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { reportErrors(errors); - if (options.watch) { - projectErrorsReported.setValue(proj, true); - diagnostics.setValue(proj, errors); - } + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); } function reportErrors(errors: ReadonlyArray) { diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index f9ce3055f63..345991baefc 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -106,6 +106,21 @@ namespace ts { export type ReportEmitErrorSummary = (errorCount: number) => void; + export function getErrorCountForSummary(diagnostics: ReadonlyArray) { + return countWhere(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error); + } + + export function getWatchErrorSummaryDiagnosticMessage(errorCount: number) { + return errorCount === 1 ? + Diagnostics.Found_1_error_Watching_for_file_changes : + Diagnostics.Found_0_errors_Watching_for_file_changes; + } + + export function getErrorSummaryText(errorCount: number, newLine: string) { + const d = createCompilerDiagnostic(errorCount === 1 ? Diagnostics.Found_1_error : Diagnostics.Found_0_errors, errorCount); + return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`; + } + /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ @@ -151,7 +166,7 @@ namespace ts { } if (reportSummary) { - reportSummary(diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); + reportSummary(getErrorCountForSummary(diagnostics)); } if (emitSkipped && diagnostics.length > 0) { @@ -227,16 +242,16 @@ namespace ts { const compilerOptions = builderProgram.getCompilerOptions(); const newLine = getNewLineCharacter(compilerOptions, () => system.newLine); - const reportSummary = (errorCount: number) => { - if (errorCount === 1) { - onWatchStatusChange!(createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); - } - else { - onWatchStatusChange!(createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); - } - }; - - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); + emitFilesAndReportErrors( + builderProgram, + reportDiagnostic, + writeFileName, + errorCount => onWatchStatusChange!( + createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), + newLine, + compilerOptions + ) + ); } } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index c19c1ab141e..d17eae4f80a 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1325,6 +1325,9 @@ namespace Harness { const [, content] = value; outputLines += content; } + if (pretty) { + outputLines += ts.getErrorSummaryText(ts.getErrorCountForSummary(diagnostics), IO.newLine()); + } return outputLines; } diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index 549f79f9025..d3a60f58d05 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -200,19 +200,28 @@ namespace ts { } // TODO: change this to host if watch => watchHost otherwiue without wathc - const builder = createSolutionBuilder(createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); + const builder = createSolutionBuilder(buildOptions.watch ? + createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()) : + createSolutionBuilderHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createReportErrorSummary(buildOptions)), + projects, buildOptions); if (buildOptions.clean) { return sys.exit(builder.cleanAllProjects()); } if (buildOptions.watch) { builder.buildAllProjects(); - return builder.startWatching(); + return (builder as SolutionBuilderWithWatch).startWatching(); } return sys.exit(builder.buildAllProjects()); } + function createReportErrorSummary(options: CompilerOptions | BuildOptions): ReportEmitErrorSummary | undefined { + return shouldBePretty(options) ? + errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) : + undefined; + } + function performCompilation(rootNames: string[], projectReferences: ReadonlyArray | undefined, options: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { const host = createCompilerHost(options); enableStatistics(options); @@ -225,7 +234,12 @@ namespace ts { configFileParsingDiagnostics }; const program = createProgram(programOptions); - const exitStatus = emitFilesAndReportErrors(program, reportDiagnostic, s => sys.write(s + sys.newLine)); + const exitStatus = emitFilesAndReportErrors( + program, + reportDiagnostic, + s => sys.write(s + sys.newLine), + createReportErrorSummary(options) + ); reportStatistics(program); return sys.exit(exitStatus); } diff --git a/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt b/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt index 772d1e4f5a3..4b81299983e 100644 --- a/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt +++ b/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt @@ -58,4 +58,6 @@ } } } - \ No newline at end of file + +Found 2 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt index 9a963614b61..ed4a93ad107 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt @@ -91,4 +91,6 @@ ~~~ !!! error TS2451: Cannot redeclare block-scoped variable 'Bar'. !!! related TS6203 tests/cases/compiler/file1.ts:2:7: 'Bar' was also declared here. - \ No newline at end of file + +Found 6 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt index c6d6291e66a..e149ce706f1 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt @@ -44,4 +44,6 @@ class G { } class H { } class I { } - \ No newline at end of file + +Found 2 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt index 2fb1879933c..81c8f5c0c00 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt @@ -84,4 +84,6 @@ !!! error TS2300: Duplicate identifier 'duplicate3'. !!! related TS6203 tests/cases/compiler/file1.ts:4:5: 'duplicate3' was also declared here. } - \ No newline at end of file + +Found 6 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt index 9512e55733e..b6cd9e2fe4e 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt @@ -46,4 +46,6 @@ duplicate7(): number; duplicate8(): number; } - \ No newline at end of file + +Found 2 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt index 497a0642296..ae55bedd138 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt @@ -91,4 +91,6 @@ } } export {} - \ No newline at end of file + +Found 6 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt index db980204718..c380c59c48a 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt @@ -91,4 +91,6 @@ !!! error TS2300: Duplicate identifier 'duplicate3'. !!! related TS6203 tests/cases/compiler/file2.ts:7:9: 'duplicate3' was also declared here. } - } \ No newline at end of file + } +Found 6 errors. + diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt index 7b568736ff3..6e5c0ab902c 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt @@ -55,4 +55,6 @@ duplicate8: () => string; duplicate9: () => string; } - } \ No newline at end of file + } +Found 2 errors. + diff --git a/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt b/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt index 14c054c466c..8222133a9de 100644 --- a/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt +++ b/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt @@ -22,4 +22,6 @@ !!! error TS2345: Argument of type '{ default: () => void; }' is not assignable to parameter of type '() => void'. !!! error TS2345: Type '{ default: () => void; }' provides no match for the signature '(): void'. !!! related TS7038 tests/cases/compiler/index.ts:1:1: Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead. - \ No newline at end of file + +Found 1 error. + diff --git a/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt b/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt index 525f30415d1..44b13d7ea8e 100644 --- a/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt +++ b/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt @@ -20,4 +20,6 @@ !!! error TS2322: Type '{ a: { b: string; }; }' is not assignable to type '{ c: string; }'. !!! error TS2322: Object literal may only specify known properties, and 'a' does not exist in type '{ c: string; }'. }; - \ No newline at end of file + +Found 1 error. + diff --git a/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt b/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt index d983f0d973e..008d3d3d817 100644 --- a/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt +++ b/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt @@ -8,4 +8,6 @@ if (true) { -!!! error TS1005: '}' expected. \ No newline at end of file +!!! error TS1005: '}' expected. +Found 1 error. + diff --git a/tests/baselines/reference/typedefCrossModule5.errors.txt b/tests/baselines/reference/typedefCrossModule5.errors.txt index 2784f0e1896..6ee46827441 100644 --- a/tests/baselines/reference/typedefCrossModule5.errors.txt +++ b/tests/baselines/reference/typedefCrossModule5.errors.txt @@ -55,4 +55,6 @@ ~~~ !!! error TS2451: Cannot redeclare block-scoped variable 'Bar'. !!! related TS6203 tests/cases/conformance/jsdoc/mod1.js:2:7: 'Bar' was also declared here. - \ No newline at end of file + +Found 4 errors. + From 0b194a2b34ded03de3294763336767e0283d24fa Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 16:48:12 -0700 Subject: [PATCH 191/262] Define Rest as Pick> to ensure it is homomorphic --- src/lib/es5.d.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 70e7e805899..98b4e3c625f 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1416,13 +1416,6 @@ type Pick = { [P in K]: T[P]; }; -/** - * From T, omit a set of properties whose keys are in the union K - */ -type Rest = { - [P in Exclude]: T[P]; -}; - /** * Construct a type with a set of properties K of type T */ @@ -1445,6 +1438,11 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; +/** + * From T, pick all properties except those in the union K + */ +type Rest = Pick>; + /** * Obtain the parameters of a function type in a tuple */ From 396642d03e51331b9d86e1270b0048fde083e8b2 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 17:49:49 -0700 Subject: [PATCH 192/262] Only create Rest types when object and/or key type is generic --- src/compiler/checker.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f8c2bc12f63..b0bc866fded 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4600,15 +4600,24 @@ namespace ts { if (source.flags & TypeFlags.Union) { return mapType(source, t => getRestType(t, properties, symbol)); } - const restTypeAlias = getGlobalRestSymbol(); - if (!restTypeAlias) { - return errorType; + const omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName)); + if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + const restTypeAlias = getGlobalRestSymbol(); + return !restTypeAlias ? errorType : + omitKeyType.flags & TypeFlags.Never ? source : + getTypeAliasInstantiation(restTypeAlias, [source, omitKeyType]); } - const omitTypes = getUnionType(map(properties, getLiteralTypeFromPropertyName)); - if (omitTypes.flags & TypeFlags.Never) { - return source; + const members = createSymbolTable(); + for (const prop of getPropertiesOfType(source)) { + if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, TypeFlags.StringOrNumberLiteralOrUnique), omitKeyType) + && !(getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected)) + && isSpreadableProperty(prop)) { + members.set(prop.escapedName, getSpreadSymbol(prop)); + } } - return getTypeAliasInstantiation(restTypeAlias, [source, omitTypes]); + const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); + const numberIndexInfo = getIndexInfoOfType(source, IndexKind.Number); + return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); } /** Return the inferred type for a binding element */ From f55805955de50dd0068f5be3812685b5fb403402 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 1 Nov 2018 17:50:08 -0700 Subject: [PATCH 193/262] Accept new baselines --- .../asyncFunctionTempVariableScoping.types | 2 +- ...turingDoesNotElideFollowingStatement.types | 2 +- .../importHelpersInAmbientContext.types | 4 +-- .../nonPrimitiveAccessProperty.types | 2 +- .../baselines/reference/objectRest.errors.txt | 12 +++---- tests/baselines/reference/objectRest.types | 34 +++++++++---------- .../reference/objectRestAssignment.types | 8 ++--- .../baselines/reference/objectRestForOf.types | 6 ++-- .../reference/objectRestNegative.errors.txt | 4 +-- .../reference/objectRestNegative.types | 10 +++--- .../reference/objectRestParameter.symbols | 12 +++---- .../reference/objectRestParameter.types | 18 +++++----- .../reference/objectRestParameterES5.symbols | 12 +++---- .../reference/objectRestParameterES5.types | 18 +++++----- .../reference/objectRestReadonly.symbols | 4 +-- .../reference/objectRestReadonly.types | 4 +-- ...InitializerBeforeDestructuringEmit.symbols | 8 ++--- ...erInitializerBeforeDestructuringEmit.types | 8 ++--- .../reference/restInvalidArgumentType.types | 2 +- .../unusedLocalsAndObjectSpread.types | 12 +++---- 20 files changed, 91 insertions(+), 91 deletions(-) diff --git a/tests/baselines/reference/asyncFunctionTempVariableScoping.types b/tests/baselines/reference/asyncFunctionTempVariableScoping.types index cc477523cb9..30b23994903 100644 --- a/tests/baselines/reference/asyncFunctionTempVariableScoping.types +++ b/tests/baselines/reference/asyncFunctionTempVariableScoping.types @@ -5,7 +5,7 @@ async ({ foo, bar, ...rest }) => bar(await foo); >async ({ foo, bar, ...rest }) => bar(await foo) : ({ foo, bar, ...rest }: { [x: string]: any; foo: any; bar: any; }) => Promise >foo : any >bar : any ->rest : Rest<{ [x: string]: any; foo: any; bar: any; }, "foo" | "bar"> +>rest : { [x: string]: any; } >bar(await foo) : any >bar : any >await foo : any diff --git a/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types b/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types index 600c4f9d717..246c6d2e7db 100644 --- a/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types +++ b/tests/baselines/reference/forLoopWithDestructuringDoesNotElideFollowingStatement.types @@ -10,7 +10,7 @@ let array = [{a: 0, b: 1}] for (let { a, ...rest } of array) >a : number ->rest : Rest<{ a: number; b: number; }, "a"> +>rest : { b: number; } >array : { a: number; b: number; }[] void a diff --git a/tests/baselines/reference/importHelpersInAmbientContext.types b/tests/baselines/reference/importHelpersInAmbientContext.types index 794bdb2e418..0c3365d7d93 100644 --- a/tests/baselines/reference/importHelpersInAmbientContext.types +++ b/tests/baselines/reference/importHelpersInAmbientContext.types @@ -33,7 +33,7 @@ interface Foo { } export var { a, ...x } : Foo; >a : number ->x : Rest +>x : { b: string; } === tests/cases/compiler/b.ts === export {}; @@ -72,7 +72,7 @@ declare namespace N { } export var { a, ...x } : Foo; >a : number ->x : Rest +>x : { b: string; } } === tests/cases/compiler/tslib.d.ts === diff --git a/tests/baselines/reference/nonPrimitiveAccessProperty.types b/tests/baselines/reference/nonPrimitiveAccessProperty.types index 5218aa20fda..900df294d9b 100644 --- a/tests/baselines/reference/nonPrimitiveAccessProperty.types +++ b/tests/baselines/reference/nonPrimitiveAccessProperty.types @@ -19,6 +19,6 @@ var { destructuring } = a; // error >a : object var { ...rest } = a; // ok ->rest : object +>rest : {} >a : object diff --git a/tests/baselines/reference/objectRest.errors.txt b/tests/baselines/reference/objectRest.errors.txt index 48d8bd3f328..2cee03225c3 100644 --- a/tests/baselines/reference/objectRest.errors.txt +++ b/tests/baselines/reference/objectRest.errors.txt @@ -2,9 +2,9 @@ tests/cases/conformance/types/rest/objectRest.ts(7,12): error TS2339: Property ' tests/cases/conformance/types/rest/objectRest.ts(7,20): error TS2339: Property '1' does not exist on type 'String'. tests/cases/conformance/types/rest/objectRest.ts(43,8): error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. tests/cases/conformance/types/rest/objectRest.ts(43,35): error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. -tests/cases/conformance/types/rest/objectRest.ts(43,57): error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type 'Rest<{ a: number; b: string; }, string>'. -tests/cases/conformance/types/rest/objectRest.ts(44,53): error TS2322: Type 'Rest<{ a: number; b: string; }, string>' is not assignable to type '{ a: number; b: string; }'. - Property 'a' is missing in type 'Rest<{ a: number; b: string; }, string>'. +tests/cases/conformance/types/rest/objectRest.ts(43,57): error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type '{}'. +tests/cases/conformance/types/rest/objectRest.ts(44,53): error TS2322: Type '{}' is not assignable to type '{ a: number; b: string; }'. + Property 'a' is missing in type '{}'. ==== tests/cases/conformance/types/rest/objectRest.ts (6 errors) ==== @@ -60,11 +60,11 @@ tests/cases/conformance/types/rest/objectRest.ts(44,53): error TS2322: Type 'Res ~~~~~~~~~ !!! error TS2537: Type '{ a: number; b: string; }' has no matching index signature for type 'string'. ~ -!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type 'Rest<{ a: number; b: string; }, string>'. +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'o' must be of type '{ a: number; b: string; }', but here has type '{}'. ({ [computed]: stillNotGreat, [computed2]: soSo, ...o } = o); ~ -!!! error TS2322: Type 'Rest<{ a: number; b: string; }, string>' is not assignable to type '{ a: number; b: string; }'. -!!! error TS2322: Property 'a' is missing in type 'Rest<{ a: number; b: string; }, string>'. +!!! error TS2322: Type '{}' is not assignable to type '{ a: number; b: string; }'. +!!! error TS2322: Property 'a' is missing in type '{}'. var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes; \ No newline at end of file diff --git a/tests/baselines/reference/objectRest.types b/tests/baselines/reference/objectRest.types index 6a5f823e9dd..dfce7e47912 100644 --- a/tests/baselines/reference/objectRest.types +++ b/tests/baselines/reference/objectRest.types @@ -13,32 +13,32 @@ var { ...clone } = o; var { a, ...justB } = o; >a : number ->justB : Rest<{ a: number; b: string; }, "a"> +>justB : { b: string; } >o : { a: number; b: string; } var { a, b: renamed, ...empty } = o; >a : number >b : any >renamed : string ->empty : Rest<{ a: number; b: string; }, "a" | "b"> +>empty : {} >o : { a: number; b: string; } var { ['b']: renamed, ...justA } = o; >'b' : "b" >renamed : string ->justA : Rest<{ a: number; b: string; }, "b"> +>justA : { a: number; } >o : { a: number; b: string; } var { 'b': renamed, ...justA } = o; >renamed : string ->justA : Rest<{ a: number; b: string; }, "b"> +>justA : { a: number; } >o : { a: number; b: string; } var { b: { '0': n, '1': oooo }, ...justA } = o; >b : any >n : any >oooo : any ->justA : Rest<{ a: number; b: string; }, "b"> +>justA : { a: number; } >o : { a: number; b: string; } let o2 = { c: 'terrible idea?', d: 'yes' }; @@ -52,7 +52,7 @@ let o2 = { c: 'terrible idea?', d: 'yes' }; var { d: renamed, ...d } = o2; >d : any >renamed : string ->d : Rest<{ c: string; d: string; }, "d"> +>d : { c: string; } >o2 : { c: string; d: string; } let nestedrest: { x: number, n1: { y: number, n2: { z: number, n3: { n4: number } } }, rest: number, restrest: number }; @@ -75,7 +75,7 @@ var { x, n1: { y, n2: { z, n3: { ...nr } } }, ...restrest } = nestedrest; >z : number >n3 : any >nr : { n4: number; } ->restrest : Rest<{ x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; }, "x" | "n1"> +>restrest : { rest: number; restrest: number; } >nestedrest : { x: number; n1: { y: number; n2: { z: number; n3: { n4: number; }; }; }; rest: number; restrest: number; } let complex: { x: { ka, ki }, y: number }; @@ -88,10 +88,10 @@ let complex: { x: { ka, ki }, y: number }; var { x: { ka, ...nested }, y: other, ...rest } = complex; >x : any >ka : any ->nested : Rest<{ ka: any; ki: any; }, "ka"> +>nested : { ki: any; } >y : any >other : number ->rest : Rest<{ x: { ka: any; ki: any; }; y: number; }, "x" | "y"> +>rest : {} >complex : { x: { ka: any; ki: any; }; y: number; } ({x: { ka, ...nested }, y: other, ...rest} = complex); @@ -101,15 +101,15 @@ var { x: { ka, ...nested }, y: other, ...rest } = complex; >x : { ki: any; ka: any; } >{ ka, ...nested } : { ki: any; ka: any; } >ka : any ->nested : Rest<{ ka: any; ki: any; }, "ka"> +>nested : { ki: any; } >y : number >other : number ->rest : Rest<{ x: { ka: any; ki: any; }; y: number; }, "x" | "y"> +>rest : {} >complex : { x: { ka: any; ki: any; }; y: number; } var { x, ...fresh } = { x: 1, y: 2 }; >x : number ->fresh : Rest<{ x: number; y: number; }, "x"> +>fresh : { y: number; } >{ x: 1, y: 2 } : { x: number; y: number; } >x : number >1 : 1 @@ -121,7 +121,7 @@ var { x, ...fresh } = { x: 1, y: 2 }; >{ x, ...fresh } = { x: 1, y: 2 } : { x: number; y: number; } >{ x, ...fresh } : { y: number; x: number; } >x : number ->fresh : Rest<{ x: number; y: number; }, "x"> +>fresh : { y: number; } >{ x: 1, y: 2 } : { x: number; y: number; } >x : number >1 : 1 @@ -175,7 +175,7 @@ var removable = new Removable(); var { removed, ...removableRest } = removable; >removed : string ->removableRest : Rest +>removableRest : { remainder: string; } >removable : Removable var i: I = removable; @@ -184,7 +184,7 @@ var i: I = removable; var { removed, ...removableRest2 } = i; >removed : string ->removableRest2 : Rest +>removableRest2 : { m(): void; remainder: string; } >i : I let computed = 'b'; @@ -221,10 +221,10 @@ var noContextualType = ({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmp >({ aNumber = 12, ...notEmptyObject }) => aNumber + notEmptyObject.anythingGoes : ({ aNumber, ...notEmptyObject }: { [x: string]: any; aNumber?: number; }) => any >aNumber : number >12 : 12 ->notEmptyObject : Rest<{ [x: string]: any; aNumber?: number; }, "aNumber"> +>notEmptyObject : { [x: string]: any; } >aNumber + notEmptyObject.anythingGoes : any >aNumber : number >notEmptyObject.anythingGoes : any ->notEmptyObject : Rest<{ [x: string]: any; aNumber?: number; }, "aNumber"> +>notEmptyObject : { [x: string]: any; } >anythingGoes : any diff --git a/tests/baselines/reference/objectRestAssignment.types b/tests/baselines/reference/objectRestAssignment.types index 04507f688cb..c0c84b6d5e3 100644 --- a/tests/baselines/reference/objectRestAssignment.types +++ b/tests/baselines/reference/objectRestAssignment.types @@ -52,8 +52,8 @@ var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; >y : { ka: string; x: string; }[] >b : any >z : string ->c : Rest<{ z: string; ki: string; ku: string; }, "z"> ->rest2 : Rest<{ a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; }, "a" | "b"> +>c : { ki: string; ku: string; } +>rest2 : { ke: string; ko: string; } >overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } ({ a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit); @@ -69,7 +69,7 @@ var { a: [{ ...nested2 }, ...y], b: { z, ...c }, ...rest2 } = overEmit; >b : { ki: string; ku: string; z: string; } >{ z, ...c } : { ki: string; ku: string; z: string; } >z : string ->c : Rest<{ z: string; ki: string; ku: string; }, "z"> ->rest2 : Rest<{ a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; }, "a" | "b"> +>c : { ki: string; ku: string; } +>rest2 : { ke: string; ko: string; } >overEmit : { a: { ka: string; x: string; }[]; b: { z: string; ki: string; ku: string; }; ke: string; ko: string; } diff --git a/tests/baselines/reference/objectRestForOf.types b/tests/baselines/reference/objectRestForOf.types index 107a38ecea6..30e10999bc7 100644 --- a/tests/baselines/reference/objectRestForOf.types +++ b/tests/baselines/reference/objectRestForOf.types @@ -6,13 +6,13 @@ let array: { x: number, y: string }[]; for (let { x, ...restOf } of array) { >x : number ->restOf : Rest<{ x: number; y: string; }, "x"> +>restOf : { y: string; } >array : { x: number; y: string; }[] [x, restOf]; ->[x, restOf] : (number | Rest<{ x: number; y: string; }, "x">)[] +>[x, restOf] : (number | { y: string; })[] >x : number ->restOf : Rest<{ x: number; y: string; }, "x"> +>restOf : { y: string; } } let xx: number; >xx : number diff --git a/tests/baselines/reference/objectRestNegative.errors.txt b/tests/baselines/reference/objectRestNegative.errors.txt index 8e599f26639..42b25d137ef 100644 --- a/tests/baselines/reference/objectRestNegative.errors.txt +++ b/tests/baselines/reference/objectRestNegative.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(2,10): error TS2462: A rest element must be last in a destructuring pattern. -tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Type 'Rest<{ a: number; b: string; }, "b">' is not assignable to type '{ a: string; }'. +tests/cases/conformance/types/rest/objectRestNegative.ts(6,10): error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. Types of property 'a' are incompatible. Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/rest/objectRestNegative.ts(9,31): error TS2462: A rest element must be last in a destructuring pattern. @@ -18,7 +18,7 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(17,9): error TS2701: Th let notAssignable: { a: string }; ({ b, ...notAssignable } = o); ~~~~~~~~~~~~~ -!!! error TS2322: Type 'Rest<{ a: number; b: string; }, "b">' is not assignable to type '{ a: string; }'. +!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ a: string; }'. !!! error TS2322: Types of property 'a' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. diff --git a/tests/baselines/reference/objectRestNegative.types b/tests/baselines/reference/objectRestNegative.types index 8287f870599..58ed1902f6d 100644 --- a/tests/baselines/reference/objectRestNegative.types +++ b/tests/baselines/reference/objectRestNegative.types @@ -8,7 +8,7 @@ let o = { a: 1, b: 'no' }; >'no' : "no" var { ...mustBeLast, a } = o; ->mustBeLast : Rest<{ a: number; b: string; }, "a"> +>mustBeLast : { b: string; } >a : number >o : { a: number; b: string; } @@ -30,24 +30,24 @@ let notAssignable: { a: string }; function stillMustBeLast({ ...mustBeLast, a }: { a: number, b: string }): void { >stillMustBeLast : ({ ...mustBeLast, a }: { a: number; b: string; }) => void ->mustBeLast : Rest<{ a: number; b: string; }, "a"> +>mustBeLast : { b: string; } >a : number >a : number >b : string } function generic(t: T) { ->generic : (t: T) => Rest +>generic : (t: T) => Pick> >x : any >y : any >t : T let { x, ...rest } = t; >x : any ->rest : Rest +>rest : Pick> >t : T return rest; ->rest : Rest +>rest : Pick> } let rest: { b: string } diff --git a/tests/baselines/reference/objectRestParameter.symbols b/tests/baselines/reference/objectRestParameter.symbols index 536689ae567..f629f46e8e9 100644 --- a/tests/baselines/reference/objectRestParameter.symbols +++ b/tests/baselines/reference/objectRestParameter.symbols @@ -21,9 +21,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >x : Symbol(x, Decl(objectRestParameter.ts, 3, 34)) >a : Symbol(a, Decl(objectRestParameter.ts, 4, 11)) >rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) ->rest.y : Symbol(y) +>rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) >rest : Symbol(rest, Decl(objectRestParameter.ts, 4, 17)) ->y : Symbol(y) +>y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly : Symbol(suddenly, Decl(objectRestParameter.ts, 1, 1)) @@ -35,12 +35,12 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >z : Symbol(z, Decl(objectRestParameter.ts, 5, 56)) >ka : Symbol(ka, Decl(objectRestParameter.ts, 5, 62)) >y : Symbol(y, Decl(objectRestParameter.ts, 5, 71)) ->rest.y : Symbol(y) +>rest.y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) >rest : Symbol(rest, Decl(objectRestParameter.ts, 5, 37)) ->y : Symbol(y) ->nested.ka : Symbol(ka) +>y : Symbol(y, Decl(objectRestParameter.ts, 3, 48)) +>nested.ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) >nested : Symbol(nested, Decl(objectRestParameter.ts, 5, 24)) ->ka : Symbol(ka) +>ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42)) class C { >C : Symbol(C, Decl(objectRestParameter.ts, 5, 107)) diff --git a/tests/baselines/reference/objectRestParameter.types b/tests/baselines/reference/objectRestParameter.types index c3d1c4f01f2..831ac9df59f 100644 --- a/tests/baselines/reference/objectRestParameter.types +++ b/tests/baselines/reference/objectRestParameter.types @@ -2,7 +2,7 @@ function cloneAgain({ a, ...clone }: { a: number, b: string }): void { >cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string } @@ -22,9 +22,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >rest.y : string ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >y : string suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); @@ -34,8 +34,8 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >x : any >z : any >12 : 12 ->nested : Rest<{ z: any; ka: any; }, "z"> ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>nested : { ka: any; } +>rest : { y: string; } >{ x: { z: 1, ka: 1 }, y: 'noo' } : { x: { z: number; ka: number; }; y: string; } >x : { z: number; ka: number; } >{ z: 1, ka: 1 } : { z: number; ka: number; } @@ -47,10 +47,10 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >'noo' : "noo" >rest.y + nested.ka : string >rest.y : string ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >y : string >nested.ka : any ->nested : Rest<{ z: any; ka: any; }, "z"> +>nested : { ka: any; } >ka : any class C { @@ -59,7 +59,7 @@ class C { m({ a, ...clone }: { a: number, b: string}): void { >m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string @@ -68,7 +68,7 @@ class C { set p({ a, ...clone }: { a: number, b: string}) { >p : { a: number; b: string; } >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string diff --git a/tests/baselines/reference/objectRestParameterES5.symbols b/tests/baselines/reference/objectRestParameterES5.symbols index c397e137799..4c6b8115169 100644 --- a/tests/baselines/reference/objectRestParameterES5.symbols +++ b/tests/baselines/reference/objectRestParameterES5.symbols @@ -21,9 +21,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >x : Symbol(x, Decl(objectRestParameterES5.ts, 3, 34)) >a : Symbol(a, Decl(objectRestParameterES5.ts, 4, 11)) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 4, 17)) ->rest.y : Symbol(y) +>rest.y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 4, 17)) ->y : Symbol(y) +>y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); >suddenly : Symbol(suddenly, Decl(objectRestParameterES5.ts, 1, 1)) @@ -35,12 +35,12 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >z : Symbol(z, Decl(objectRestParameterES5.ts, 5, 56)) >ka : Symbol(ka, Decl(objectRestParameterES5.ts, 5, 62)) >y : Symbol(y, Decl(objectRestParameterES5.ts, 5, 71)) ->rest.y : Symbol(y) +>rest.y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) >rest : Symbol(rest, Decl(objectRestParameterES5.ts, 5, 37)) ->y : Symbol(y) ->nested.ka : Symbol(ka) +>y : Symbol(y, Decl(objectRestParameterES5.ts, 3, 48)) +>nested.ka : Symbol(ka, Decl(objectRestParameterES5.ts, 3, 42)) >nested : Symbol(nested, Decl(objectRestParameterES5.ts, 5, 24)) ->ka : Symbol(ka) +>ka : Symbol(ka, Decl(objectRestParameterES5.ts, 3, 42)) class C { >C : Symbol(C, Decl(objectRestParameterES5.ts, 5, 107)) diff --git a/tests/baselines/reference/objectRestParameterES5.types b/tests/baselines/reference/objectRestParameterES5.types index 329f69bedcd..1b8dd29e29e 100644 --- a/tests/baselines/reference/objectRestParameterES5.types +++ b/tests/baselines/reference/objectRestParameterES5.types @@ -2,7 +2,7 @@ function cloneAgain({ a, ...clone }: { a: number, b: string }): void { >cloneAgain : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string } @@ -22,9 +22,9 @@ suddenly(({ x: a, ...rest }) => rest.y); >({ x: a, ...rest }) => rest.y : ({ x: a, ...rest }: { x: { z: any; ka: any; }; y: string; }) => string >x : any >a : { z: any; ka: any; } ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >rest.y : string ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >y : string suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka); @@ -34,8 +34,8 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >x : any >z : any >12 : 12 ->nested : Rest<{ z: any; ka: any; }, "z"> ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>nested : { ka: any; } +>rest : { y: string; } >{ x: { z: 1, ka: 1 }, y: 'noo' } : { x: { z: number; ka: number; }; y: string; } >x : { z: number; ka: number; } >{ z: 1, ka: 1 } : { z: number; ka: number; } @@ -47,10 +47,10 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' >'noo' : "noo" >rest.y + nested.ka : string >rest.y : string ->rest : Rest<{ x: { z: any; ka: any; }; y: string; }, "x"> +>rest : { y: string; } >y : string >nested.ka : any ->nested : Rest<{ z: any; ka: any; }, "z"> +>nested : { ka: any; } >ka : any class C { @@ -59,7 +59,7 @@ class C { m({ a, ...clone }: { a: number, b: string}): void { >m : ({ a, ...clone }: { a: number; b: string; }) => void >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string @@ -68,7 +68,7 @@ class C { set p({ a, ...clone }: { a: number, b: string}) { >p : { a: number; b: string; } >a : number ->clone : Rest<{ a: number; b: string; }, "a"> +>clone : { b: string; } >a : number >b : string diff --git a/tests/baselines/reference/objectRestReadonly.symbols b/tests/baselines/reference/objectRestReadonly.symbols index ef32c8b616a..f2a7504e9b5 100644 --- a/tests/baselines/reference/objectRestReadonly.symbols +++ b/tests/baselines/reference/objectRestReadonly.symbols @@ -34,7 +34,7 @@ const { foo, ...rest } = obj >obj : Symbol(obj, Decl(objectRestReadonly.ts, 7, 5)) delete rest.baz ->rest.baz : Symbol(baz) +>rest.baz : Symbol(baz, Decl(objectRestReadonly.ts, 2, 13)) >rest : Symbol(rest, Decl(objectRestReadonly.ts, 13, 12)) ->baz : Symbol(baz) +>baz : Symbol(baz, Decl(objectRestReadonly.ts, 2, 13)) diff --git a/tests/baselines/reference/objectRestReadonly.types b/tests/baselines/reference/objectRestReadonly.types index d21b5793c66..5f015aeb1e5 100644 --- a/tests/baselines/reference/objectRestReadonly.types +++ b/tests/baselines/reference/objectRestReadonly.types @@ -32,12 +32,12 @@ const obj: Readonly = { const { foo, ...rest } = obj >foo : string ->rest : Rest, "foo"> +>rest : { baz: string; quux: string; } >obj : Readonly delete rest.baz >delete rest.baz : boolean >rest.baz : string ->rest : Rest, "foo"> +>rest : { baz: string; quux: string; } >baz : string diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols index e3e6dcdc9a4..857310bf87c 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.symbols @@ -18,9 +18,9 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { "use strict"; "Some other prologue"; opts.baz(bar); ->opts.baz : Symbol(baz) +>opts.baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) >opts : Symbol(opts, Decl(parameterInitializerBeforeDestructuringEmit.ts, 5, 27)) ->baz : Symbol(baz) +>baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) >bar : Symbol(bar, Decl(parameterInitializerBeforeDestructuringEmit.ts, 5, 17)) } @@ -35,9 +35,9 @@ class C { "use strict"; "Some other prologue"; opts.baz(bar); ->opts.baz : Symbol(baz) +>opts.baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) >opts : Symbol(opts, Decl(parameterInitializerBeforeDestructuringEmit.ts, 12, 27)) ->baz : Symbol(baz) +>baz : Symbol(Foo.baz, Decl(parameterInitializerBeforeDestructuringEmit.ts, 1, 14)) >bar : Symbol(bar, Decl(parameterInitializerBeforeDestructuringEmit.ts, 12, 17)) } } diff --git a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types index 28f71d1362b..bbdf5580a60 100644 --- a/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types +++ b/tests/baselines/reference/parameterInitializerBeforeDestructuringEmit.types @@ -11,7 +11,7 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { >foobar : ({ bar, ...opts }?: Foo) => void >bar : any >{} : {} ->opts : Rest +>opts : { baz?: any; } >{} : {} "use strict"; @@ -23,7 +23,7 @@ function foobar({ bar = {}, ...opts }: Foo = {}) { opts.baz(bar); >opts.baz(bar) : any >opts.baz : any ->opts : Rest +>opts : { baz?: any; } >baz : any >bar : any } @@ -34,7 +34,7 @@ class C { constructor({ bar = {}, ...opts }: Foo = {}) { >bar : any >{} : {} ->opts : Rest +>opts : { baz?: any; } >{} : {} "use strict"; @@ -46,7 +46,7 @@ class C { opts.baz(bar); >opts.baz(bar) : any >opts.baz : any ->opts : Rest +>opts : { baz?: any; } >baz : any >bar : any } diff --git a/tests/baselines/reference/restInvalidArgumentType.types b/tests/baselines/reference/restInvalidArgumentType.types index e04395b2407..54af9099c31 100644 --- a/tests/baselines/reference/restInvalidArgumentType.types +++ b/tests/baselines/reference/restInvalidArgumentType.types @@ -71,7 +71,7 @@ function f(p1: T, p2: T[]) { >p1 : T var {...r2} = p2; // OK ->r2 : T[] +>r2 : { [n: number]: T; length: number; toString(): string; toLocaleString(): string; pop(): T; push(...items: T[]): number; concat(...items: ConcatArray[]): T[]; concat(...items: (T | ConcatArray)[]): T[]; join(separator?: string): string; reverse(): T[]; shift(): T; slice(start?: number, end?: number): T[]; sort(compareFn?: (a: T, b: T) => number): T[]; splice(start: number, deleteCount?: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; unshift(...items: T[]): number; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; } >p2 : T[] var {...r3} = t; // Error, generic type paramter diff --git a/tests/baselines/reference/unusedLocalsAndObjectSpread.types b/tests/baselines/reference/unusedLocalsAndObjectSpread.types index 233ea57ae6f..3fc4ae1e751 100644 --- a/tests/baselines/reference/unusedLocalsAndObjectSpread.types +++ b/tests/baselines/reference/unusedLocalsAndObjectSpread.types @@ -18,7 +18,7 @@ function one() { // 'a' is declared but never used const {a, ...bar} = foo; >a : number ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } >foo : { a: number; b: number; } console.log(bar); @@ -26,7 +26,7 @@ function one() { >console.log : (a: any) => void >console : { log(a: any): void; } >log : (a: any) => void ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } } function two() { @@ -44,7 +44,7 @@ function two() { const {a: _, ...bar} = foo; >a : any >_ : number ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } >foo : { a: number; b: number; } console.log(bar); @@ -52,7 +52,7 @@ function two() { >console.log : (a: any) => void >console : { log(a: any): void; } >log : (a: any) => void ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } } function three() { @@ -69,7 +69,7 @@ function three() { // 'a' is declared but never used const {a, ...bar} = foo; // bar should be unused >a : number ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } >foo : { a: number; b: number; } //console.log(bar); @@ -90,7 +90,7 @@ function four() { const {a: _, ...bar} = foo; // bar should be unused >a : any >_ : number ->bar : Rest<{ a: number; b: number; }, "a"> +>bar : { b: number; } >foo : { a: number; b: number; } //console.log(bar); From 9fd7d0a5f4cbe901c87ac04c32489db69c654f3e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 06:40:26 -0700 Subject: [PATCH 194/262] Remove Rest and use Pick> instead --- src/compiler/checker.ts | 30 ++++++++++++++++++++---------- src/lib/es5.d.ts | 5 ----- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b0bc866fded..e0f40cd2606 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -517,7 +517,8 @@ namespace ts { let deferredGlobalTemplateStringsArrayType: ObjectType; let deferredGlobalImportMetaType: ObjectType; let deferredGlobalExtractSymbol: Symbol; - let deferredGlobalRestSymbol: Symbol; + let deferredGlobalExcludeSymbol: Symbol; + let deferredGlobalPickSymbol: Symbol; const allPotentiallyUnusedIdentifiers = createMap(); // key is file name @@ -4602,10 +4603,16 @@ namespace ts { } const omitKeyType = getUnionType(map(properties, getLiteralTypeFromPropertyName)); if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { - const restTypeAlias = getGlobalRestSymbol(); - return !restTypeAlias ? errorType : - omitKeyType.flags & TypeFlags.Never ? source : - getTypeAliasInstantiation(restTypeAlias, [source, omitKeyType]); + if (omitKeyType.flags & TypeFlags.Never) { + return source; + } + const pickTypeAlias = getGlobalPickSymbol(); + const excludeTypeAlias = getGlobalExcludeSymbol(); + if (!pickTypeAlias || !excludeTypeAlias) { + return errorType; + } + const pickKeys = getTypeAliasInstantiation(excludeTypeAlias, [getIndexType(source), omitKeyType]); + return getTypeAliasInstantiation(pickTypeAlias, [source, pickKeys]); } const members = createSymbolTable(); for (const prop of getPropertiesOfType(source)) { @@ -8640,8 +8647,12 @@ namespace ts { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 } - function getGlobalRestSymbol(): Symbol { - return deferredGlobalRestSymbol || (deferredGlobalRestSymbol = getGlobalSymbol("Rest" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 + function getGlobalExcludeSymbol(): Symbol { + return deferredGlobalExcludeSymbol || (deferredGlobalExcludeSymbol = getGlobalSymbol("Exclude" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 + } + + function getGlobalPickSymbol(): Symbol { + return deferredGlobalPickSymbol || (deferredGlobalPickSymbol = getGlobalSymbol("Pick" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 } /** @@ -9227,9 +9238,8 @@ namespace ts { } function getLiteralTypeFromPropertyName(name: PropertyName) { - return isComputedPropertyName(name) ? checkComputedPropertyName(name) : - isIdentifier(name) ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) : - checkExpression(name); + return isIdentifier(name) ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) : + getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); } function getLiteralTypeFromProperty(prop: Symbol, include: TypeFlags) { diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 98b4e3c625f..c8e99f0d1db 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1438,11 +1438,6 @@ type Extract = T extends U ? T : never; */ type NonNullable = T extends null | undefined ? never : T; -/** - * From T, pick all properties except those in the union K - */ -type Rest = Pick>; - /** * Obtain the parameters of a function type in a tuple */ From 9daf69de4c676aac0eaba84a1c8a2234fac33e79 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 06:40:33 -0700 Subject: [PATCH 195/262] Accept new baselines --- .../reference/expressionTypeNodeShouldError.types | 12 ++++++------ .../reference/intersectionsOfLargeUnions.types | 6 +++--- .../reference/intersectionsOfLargeUnions2.types | 6 +++--- .../reference/modularizeLibrary_Dom.iterable.types | 4 ++-- .../reference/parserOverloadOnConstants1.types | 8 ++++---- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/baselines/reference/expressionTypeNodeShouldError.types b/tests/baselines/reference/expressionTypeNodeShouldError.types index 90707d4db50..45c12d7c8ff 100644 --- a/tests/baselines/reference/expressionTypeNodeShouldError.types +++ b/tests/baselines/reference/expressionTypeNodeShouldError.types @@ -31,9 +31,9 @@ class C { const nodes = document.getElementsByTagName("li"); >nodes : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType = "".typeof(nodes.item(0)); @@ -72,9 +72,9 @@ class C2 { const nodes2 = document.getElementsByTagName("li"); >nodes2 : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType2 = 4..typeof(nodes.item(0)); @@ -114,9 +114,9 @@ class C3 { const nodes3 = document.getElementsByTagName("li"); >nodes3 : HTMLCollectionOf >document.getElementsByTagName("li") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"li" : "li" type ItemType3 = true.typeof(nodes.item(0)); diff --git a/tests/baselines/reference/intersectionsOfLargeUnions.types b/tests/baselines/reference/intersectionsOfLargeUnions.types index 26f93ac79db..06d01c0c6b2 100644 --- a/tests/baselines/reference/intersectionsOfLargeUnions.types +++ b/tests/baselines/reference/intersectionsOfLargeUnions.types @@ -24,7 +24,7 @@ export function assertIsElement(node: Node | null): node is Element { } export function assertNodeTagName< ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U T extends keyof ElementTagNameMap, U extends ElementTagNameMap[T]>(node: Node | null, tagName: T): node is U { @@ -56,7 +56,7 @@ export function assertNodeTagName< } export function assertNodeProperty< ->assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void +>assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void T extends keyof ElementTagNameMap, P extends keyof ElementTagNameMap[T], @@ -69,7 +69,7 @@ export function assertNodeProperty< if (assertNodeTagName(node, tagName)) { >assertNodeTagName(node, tagName) : boolean ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U >node : Node | null >tagName : T diff --git a/tests/baselines/reference/intersectionsOfLargeUnions2.types b/tests/baselines/reference/intersectionsOfLargeUnions2.types index 277806ae314..82160fb235e 100644 --- a/tests/baselines/reference/intersectionsOfLargeUnions2.types +++ b/tests/baselines/reference/intersectionsOfLargeUnions2.types @@ -38,7 +38,7 @@ export function assertIsElement(node: Node | null): node is Element { } export function assertNodeTagName< ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U T extends keyof ElementTagNameMap, U extends ElementTagNameMap[T]>(node: Node | null, tagName: T): node is U { @@ -70,7 +70,7 @@ export function assertNodeTagName< } export function assertNodeProperty< ->assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void +>assertNodeProperty : (node: Node | null, tagName: T, prop: P, value: V) => void T extends keyof ElementTagNameMap, P extends keyof ElementTagNameMap[T], @@ -83,7 +83,7 @@ export function assertNodeProperty< if (assertNodeTagName(node, tagName)) { >assertNodeTagName(node, tagName) : boolean ->assertNodeTagName : (node: Node | null, tagName: T) => node is U +>assertNodeTagName : (node: Node | null, tagName: T) => node is U >node : Node | null >tagName : T diff --git a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types index 70c6a6cb5b9..e2ba3e7a300 100644 --- a/tests/baselines/reference/modularizeLibrary_Dom.iterable.types +++ b/tests/baselines/reference/modularizeLibrary_Dom.iterable.types @@ -2,9 +2,9 @@ for (const element of document.getElementsByTagName("a")) { >element : HTMLAnchorElement >document.getElementsByTagName("a") : HTMLCollectionOf ->document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>document.getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >document : Document ->getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } +>getElementsByTagName : { (qualifiedName: K): HTMLCollectionOf; (qualifiedName: K): HTMLCollectionOf; (qualifiedName: string): HTMLCollectionOf; } >"a" : "a" element.href; diff --git a/tests/baselines/reference/parserOverloadOnConstants1.types b/tests/baselines/reference/parserOverloadOnConstants1.types index 2a865af7ba7..6cac9a704a9 100644 --- a/tests/baselines/reference/parserOverloadOnConstants1.types +++ b/tests/baselines/reference/parserOverloadOnConstants1.types @@ -1,18 +1,18 @@ === tests/cases/conformance/parser/ecmascript5/parserOverloadOnConstants1.ts === interface Document { createElement(tagName: string): HTMLElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : string createElement(tagName: 'canvas'): HTMLCanvasElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "canvas" createElement(tagName: 'div'): HTMLDivElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "div" createElement(tagName: 'span'): HTMLSpanElement; ->createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } +>createElement : { (tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K]; (tagName: K, options?: ElementCreationOptions): HTMLElementDeprecatedTagNameMap[K]; (tagName: string, options?: ElementCreationOptions): HTMLElement; (tagName: string): HTMLElement; (tagName: "canvas"): HTMLCanvasElement; (tagName: "div"): HTMLDivElement; (tagName: "span"): HTMLSpanElement; } >tagName : "span" } From abebf15af8647526e3108662d306a49415d21269 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 07:53:25 -0700 Subject: [PATCH 196/262] Ensure '{ [key]: x } = obj' for generic key is the same as 'x = obj[key]' --- src/compiler/checker.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e0f40cd2606..465e4c0ecb6 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4667,12 +4667,8 @@ namespace ts { else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) const name = declaration.propertyName || declaration.name; - const exprType = isComputedPropertyName(name) - ? checkComputedPropertyName(name) - : isIdentifier(name) - ? getLiteralType(unescapeLeadingUnderscores(name.escapedText)) - : checkExpression(name); - const declaredType = checkIndexedAccessIndexType(getIndexedAccessType(getApparentType(parentType), exprType, name), name); + const exprType = getLiteralTypeFromPropertyName(name); + const declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } @@ -9528,7 +9524,7 @@ namespace ts { // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' // has always been resolved eagerly using the constraint type of 'this' at the given location. - if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression) && isGenericObjectType(objectType)) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== SyntaxKind.IndexedAccessType) && isGenericObjectType(objectType)) { if (objectType.flags & TypeFlags.AnyOrUnknown) { return objectType; } From bcc1d2a8cd41ca54591db5ef2f095cd01925e476 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 07:53:48 -0700 Subject: [PATCH 197/262] Accept new baselines --- .../definiteAssignmentOfDestructuredVariable.types | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types b/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types index fb40a9b492e..96d632736dd 100644 --- a/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types +++ b/tests/baselines/reference/definiteAssignmentOfDestructuredVariable.types @@ -18,20 +18,20 @@ class C { >method : () => void let { a, b } = this.foo; ->a : { [P in keyof T]: T[P]; }["a"] ->b : { [P in keyof T]: T[P]; }["b"] +>a : T["a"] +>b : T["b"] >this.foo : { [P in keyof T]: T[P]; } >this : this >foo : { [P in keyof T]: T[P]; } !(a && b); >!(a && b) : false ->(a && b) : { [P in keyof T]: T[P]; }["b"] ->a && b : { [P in keyof T]: T[P]; }["b"] ->a : { [P in keyof T]: T[P]; }["a"] ->b : { [P in keyof T]: T[P]; }["b"] +>(a && b) : T["b"] +>a && b : T["b"] +>a : T["a"] +>b : T["b"] a; ->a : { [P in keyof T]: T[P]; }["a"] +>a : T["a"] } } From 48c0aedf54eba2f048038bb4d804549c70e28396 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 08:20:06 -0700 Subject: [PATCH 198/262] Add tests --- .../types/rest/genericObjectRest.ts | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 tests/cases/conformance/types/rest/genericObjectRest.ts diff --git a/tests/cases/conformance/types/rest/genericObjectRest.ts b/tests/cases/conformance/types/rest/genericObjectRest.ts new file mode 100644 index 00000000000..18649db6415 --- /dev/null +++ b/tests/cases/conformance/types/rest/genericObjectRest.ts @@ -0,0 +1,30 @@ +// @strict: true +// @target: es2015 + +const a = 'a'; + +function f1(obj: T) { + let { ...r0 } = obj; + let { a: a1, ...r1 } = obj; + let { a: a2, b: b2, ...r2 } = obj; + let { 'a': a3, ...r3 } = obj; + let { ['a']: a4, ...r4 } = obj; + let { [a]: a5, ...r5 } = obj; +} + +const sa = Symbol(); +const sb = Symbol(); + +function f2(obj: T) { + let { [sa]: a1, [sb]: b1, ...r1 } = obj; +} + +function f3(obj: T, k1: K1, k2: K2) { + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +} + +type Item = { a: string, b: number, c: boolean }; + +function f4(obj: Item, k1: K1, k2: K2) { + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +} From 00c5071be6a78de74c63d9b00c107ca09e7ce849 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 2 Nov 2018 08:20:13 -0700 Subject: [PATCH 199/262] Accept new baselines --- .../baselines/reference/genericObjectRest.js | 61 +++++++++ .../reference/genericObjectRest.symbols | 126 ++++++++++++++++++ .../reference/genericObjectRest.types | 110 +++++++++++++++ 3 files changed, 297 insertions(+) create mode 100644 tests/baselines/reference/genericObjectRest.js create mode 100644 tests/baselines/reference/genericObjectRest.symbols create mode 100644 tests/baselines/reference/genericObjectRest.types diff --git a/tests/baselines/reference/genericObjectRest.js b/tests/baselines/reference/genericObjectRest.js new file mode 100644 index 00000000000..33de97a3d5f --- /dev/null +++ b/tests/baselines/reference/genericObjectRest.js @@ -0,0 +1,61 @@ +//// [genericObjectRest.ts] +const a = 'a'; + +function f1(obj: T) { + let { ...r0 } = obj; + let { a: a1, ...r1 } = obj; + let { a: a2, b: b2, ...r2 } = obj; + let { 'a': a3, ...r3 } = obj; + let { ['a']: a4, ...r4 } = obj; + let { [a]: a5, ...r5 } = obj; +} + +const sa = Symbol(); +const sb = Symbol(); + +function f2(obj: T) { + let { [sa]: a1, [sb]: b1, ...r1 } = obj; +} + +function f3(obj: T, k1: K1, k2: K2) { + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +} + +type Item = { a: string, b: number, c: boolean }; + +function f4(obj: Item, k1: K1, k2: K2) { + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +} + + +//// [genericObjectRest.js] +"use strict"; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +}; +const a = 'a'; +function f1(obj) { + let r0 = __rest(obj, []); + let { a: a1 } = obj, r1 = __rest(obj, ["a"]); + let { a: a2, b: b2 } = obj, r2 = __rest(obj, ["a", "b"]); + let { 'a': a3 } = obj, r3 = __rest(obj, ['a']); + let { ['a']: a4 } = obj, r4 = __rest(obj, ['a']); + let _a = a, a5 = obj[_a], r5 = __rest(obj, [typeof _a === "symbol" ? _a : _a + ""]); +} +const sa = Symbol(); +const sb = Symbol(); +function f2(obj) { + let _a = sa, a1 = obj[_a], _b = sb, b1 = obj[_b], r1 = __rest(obj, [typeof _a === "symbol" ? _a : _a + "", typeof _b === "symbol" ? _b : _b + ""]); +} +function f3(obj, k1, k2) { + let _a = k1, a1 = obj[_a], _b = k2, a2 = obj[_b], r1 = __rest(obj, [typeof _a === "symbol" ? _a : _a + "", typeof _b === "symbol" ? _b : _b + ""]); +} +function f4(obj, k1, k2) { + let _a = k1, a1 = obj[_a], _b = k2, a2 = obj[_b], r1 = __rest(obj, [typeof _a === "symbol" ? _a : _a + "", typeof _b === "symbol" ? _b : _b + ""]); +} diff --git a/tests/baselines/reference/genericObjectRest.symbols b/tests/baselines/reference/genericObjectRest.symbols new file mode 100644 index 00000000000..1bec7d4b1ed --- /dev/null +++ b/tests/baselines/reference/genericObjectRest.symbols @@ -0,0 +1,126 @@ +=== tests/cases/conformance/types/rest/genericObjectRest.ts === +const a = 'a'; +>a : Symbol(a, Decl(genericObjectRest.ts, 0, 5)) + +function f1(obj: T) { +>f1 : Symbol(f1, Decl(genericObjectRest.ts, 0, 14)) +>T : Symbol(T, Decl(genericObjectRest.ts, 2, 12)) +>a : Symbol(a, Decl(genericObjectRest.ts, 2, 23)) +>b : Symbol(b, Decl(genericObjectRest.ts, 2, 34)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) +>T : Symbol(T, Decl(genericObjectRest.ts, 2, 12)) + + let { ...r0 } = obj; +>r0 : Symbol(r0, Decl(genericObjectRest.ts, 3, 9)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) + + let { a: a1, ...r1 } = obj; +>a : Symbol(a, Decl(genericObjectRest.ts, 2, 23)) +>a1 : Symbol(a1, Decl(genericObjectRest.ts, 4, 9)) +>r1 : Symbol(r1, Decl(genericObjectRest.ts, 4, 16)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) + + let { a: a2, b: b2, ...r2 } = obj; +>a : Symbol(a, Decl(genericObjectRest.ts, 2, 23)) +>a2 : Symbol(a2, Decl(genericObjectRest.ts, 5, 9)) +>b : Symbol(b, Decl(genericObjectRest.ts, 2, 34)) +>b2 : Symbol(b2, Decl(genericObjectRest.ts, 5, 16)) +>r2 : Symbol(r2, Decl(genericObjectRest.ts, 5, 23)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) + + let { 'a': a3, ...r3 } = obj; +>a3 : Symbol(a3, Decl(genericObjectRest.ts, 6, 9)) +>r3 : Symbol(r3, Decl(genericObjectRest.ts, 6, 18)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) + + let { ['a']: a4, ...r4 } = obj; +>'a' : Symbol(a4, Decl(genericObjectRest.ts, 7, 9)) +>a4 : Symbol(a4, Decl(genericObjectRest.ts, 7, 9)) +>r4 : Symbol(r4, Decl(genericObjectRest.ts, 7, 20)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) + + let { [a]: a5, ...r5 } = obj; +>a : Symbol(a, Decl(genericObjectRest.ts, 0, 5)) +>a5 : Symbol(a5, Decl(genericObjectRest.ts, 8, 9)) +>r5 : Symbol(r5, Decl(genericObjectRest.ts, 8, 18)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 2, 48)) +} + +const sa = Symbol(); +>sa : Symbol(sa, Decl(genericObjectRest.ts, 11, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +const sb = Symbol(); +>sb : Symbol(sb, Decl(genericObjectRest.ts, 12, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +function f2(obj: T) { +>f2 : Symbol(f2, Decl(genericObjectRest.ts, 12, 20)) +>T : Symbol(T, Decl(genericObjectRest.ts, 14, 12)) +>[sa] : Symbol([sa], Decl(genericObjectRest.ts, 14, 23)) +>sa : Symbol(sa, Decl(genericObjectRest.ts, 11, 5)) +>[sb] : Symbol([sb], Decl(genericObjectRest.ts, 14, 37)) +>sb : Symbol(sb, Decl(genericObjectRest.ts, 12, 5)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 14, 54)) +>T : Symbol(T, Decl(genericObjectRest.ts, 14, 12)) + + let { [sa]: a1, [sb]: b1, ...r1 } = obj; +>sa : Symbol(sa, Decl(genericObjectRest.ts, 11, 5)) +>a1 : Symbol(a1, Decl(genericObjectRest.ts, 15, 9)) +>sb : Symbol(sb, Decl(genericObjectRest.ts, 12, 5)) +>b1 : Symbol(b1, Decl(genericObjectRest.ts, 15, 19)) +>r1 : Symbol(r1, Decl(genericObjectRest.ts, 15, 29)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 14, 54)) +} + +function f3(obj: T, k1: K1, k2: K2) { +>f3 : Symbol(f3, Decl(genericObjectRest.ts, 16, 1)) +>T : Symbol(T, Decl(genericObjectRest.ts, 18, 12)) +>K1 : Symbol(K1, Decl(genericObjectRest.ts, 18, 14)) +>T : Symbol(T, Decl(genericObjectRest.ts, 18, 12)) +>K2 : Symbol(K2, Decl(genericObjectRest.ts, 18, 34)) +>T : Symbol(T, Decl(genericObjectRest.ts, 18, 12)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 18, 55)) +>T : Symbol(T, Decl(genericObjectRest.ts, 18, 12)) +>k1 : Symbol(k1, Decl(genericObjectRest.ts, 18, 62)) +>K1 : Symbol(K1, Decl(genericObjectRest.ts, 18, 14)) +>k2 : Symbol(k2, Decl(genericObjectRest.ts, 18, 70)) +>K2 : Symbol(K2, Decl(genericObjectRest.ts, 18, 34)) + + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +>k1 : Symbol(k1, Decl(genericObjectRest.ts, 18, 62)) +>a1 : Symbol(a1, Decl(genericObjectRest.ts, 19, 9)) +>k2 : Symbol(k2, Decl(genericObjectRest.ts, 18, 70)) +>a2 : Symbol(a2, Decl(genericObjectRest.ts, 19, 19)) +>r1 : Symbol(r1, Decl(genericObjectRest.ts, 19, 29)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 18, 55)) +} + +type Item = { a: string, b: number, c: boolean }; +>Item : Symbol(Item, Decl(genericObjectRest.ts, 20, 1)) +>a : Symbol(a, Decl(genericObjectRest.ts, 22, 13)) +>b : Symbol(b, Decl(genericObjectRest.ts, 22, 24)) +>c : Symbol(c, Decl(genericObjectRest.ts, 22, 35)) + +function f4(obj: Item, k1: K1, k2: K2) { +>f4 : Symbol(f4, Decl(genericObjectRest.ts, 22, 49)) +>K1 : Symbol(K1, Decl(genericObjectRest.ts, 24, 12)) +>Item : Symbol(Item, Decl(genericObjectRest.ts, 20, 1)) +>K2 : Symbol(K2, Decl(genericObjectRest.ts, 24, 34)) +>Item : Symbol(Item, Decl(genericObjectRest.ts, 20, 1)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 24, 58)) +>Item : Symbol(Item, Decl(genericObjectRest.ts, 20, 1)) +>k1 : Symbol(k1, Decl(genericObjectRest.ts, 24, 68)) +>K1 : Symbol(K1, Decl(genericObjectRest.ts, 24, 12)) +>k2 : Symbol(k2, Decl(genericObjectRest.ts, 24, 76)) +>K2 : Symbol(K2, Decl(genericObjectRest.ts, 24, 34)) + + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +>k1 : Symbol(k1, Decl(genericObjectRest.ts, 24, 68)) +>a1 : Symbol(a1, Decl(genericObjectRest.ts, 25, 9)) +>k2 : Symbol(k2, Decl(genericObjectRest.ts, 24, 76)) +>a2 : Symbol(a2, Decl(genericObjectRest.ts, 25, 19)) +>r1 : Symbol(r1, Decl(genericObjectRest.ts, 25, 29)) +>obj : Symbol(obj, Decl(genericObjectRest.ts, 24, 58)) +} + diff --git a/tests/baselines/reference/genericObjectRest.types b/tests/baselines/reference/genericObjectRest.types new file mode 100644 index 00000000000..c2fcaad7cb8 --- /dev/null +++ b/tests/baselines/reference/genericObjectRest.types @@ -0,0 +1,110 @@ +=== tests/cases/conformance/types/rest/genericObjectRest.ts === +const a = 'a'; +>a : "a" +>'a' : "a" + +function f1(obj: T) { +>f1 : (obj: T) => void +>a : string +>b : number +>obj : T + + let { ...r0 } = obj; +>r0 : T +>obj : T + + let { a: a1, ...r1 } = obj; +>a : any +>a1 : string +>r1 : Pick> +>obj : T + + let { a: a2, b: b2, ...r2 } = obj; +>a : any +>a2 : string +>b : any +>b2 : number +>r2 : Pick> +>obj : T + + let { 'a': a3, ...r3 } = obj; +>a3 : string +>r3 : Pick> +>obj : T + + let { ['a']: a4, ...r4 } = obj; +>'a' : "a" +>a4 : string +>r4 : Pick> +>obj : T + + let { [a]: a5, ...r5 } = obj; +>a : "a" +>a5 : string +>r5 : Pick> +>obj : T +} + +const sa = Symbol(); +>sa : unique symbol +>Symbol() : unique symbol +>Symbol : SymbolConstructor + +const sb = Symbol(); +>sb : unique symbol +>Symbol() : unique symbol +>Symbol : SymbolConstructor + +function f2(obj: T) { +>f2 : (obj: T) => void +>[sa] : string +>sa : unique symbol +>[sb] : number +>sb : unique symbol +>obj : T + + let { [sa]: a1, [sb]: b1, ...r1 } = obj; +>sa : unique symbol +>a1 : string +>sb : unique symbol +>b1 : number +>r1 : Pick> +>obj : T +} + +function f3(obj: T, k1: K1, k2: K2) { +>f3 : (obj: T, k1: K1, k2: K2) => void +>obj : T +>k1 : K1 +>k2 : K2 + + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +>k1 : K1 +>a1 : T[K1] +>k2 : K2 +>a2 : T[K2] +>r1 : Pick> +>obj : T +} + +type Item = { a: string, b: number, c: boolean }; +>Item : Item +>a : string +>b : number +>c : boolean + +function f4(obj: Item, k1: K1, k2: K2) { +>f4 : (obj: Item, k1: K1, k2: K2) => void +>obj : Item +>k1 : K1 +>k2 : K2 + + let { [k1]: a1, [k2]: a2, ...r1 } = obj; +>k1 : K1 +>a1 : Item[K1] +>k2 : K2 +>a2 : Item[K2] +>r1 : Pick | Exclude<"b", K1 | K2> | Exclude<"c", K1 | K2>> +>obj : Item +} + From 8056e2b12f68e307c8f816e44042b1c5085dfeb4 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 2 Nov 2018 09:07:32 -0700 Subject: [PATCH 200/262] infer from usage's unification uses multiple passes (#28244) * infer from usage's unification uses multiple passes Previously, the unification step of infer-from-usage codefix would stop as soon an answer was found. Now it continues if the result is *incomplete*, with the idea that later passes may provide a better inference. Currently, an *incomplete* inference is 1. The type any. 2. The empty object type `{}` or a union or intersection that contains `{}`. In the checker, any takes priority over other types since it basically shuts down type checking. For type inference, however, any is one of the least useful inferences. `{}` is not a good inference for a similar reason; as a parameter inference, it doesn't tell the caller much about what is expected, and it doesn't allow the function author to use an object as expected. But currently it's inferred whenever there's an initialisation with the value `{}`. With this change, subsequent property assignments to the same parameter will replace the `{}` with a specific anonymous type. For example: ```js function C(config) { if (config === undefined) config = {}; this.x = config.x; this.y = config.y; this.z = config.z; } ``` * Unify all passes of inference from usage In the previous commit, I changed inference from usage to continue inference if a the result was *incomplete*. This commit now runs all 4 inference passes and combines them in a unification step. Currently the unification step is simple, it: 1. Gathers all inferences in a list. 2. Makes properties of anonymous types optional if there is an empty object in the inference list. 3. Removes *vacuous* inferences. 4. Combines the type in a union. An inference is *vacuous* if it: 1. Is any or void, when a non-any, non-void type is also inferred. 2. Is the empty object type, when an object type that is not empty is also inferred. 3. Is an anonymous type, when a non-nullable, non-any, non-void, non-anonymous type is also inferred. I think I might eventually want a concept of priorities, like the compiler's type parameter inference, but I don't have enough examples to be sure yet. Eventually, unification should have an additional step that examines the whole inference list to see if its contents are collectively meaningless. A good example is `null | undefined`, which is not useful. * Remove isNumberOrString * Unify anonymous types @andy-ms pointed out that my empty object code was a special case of merging all anonymous types from an inference and making properties optional that are not in all the anonymous type. So I did that instead. * Use getTypeOfSymbolAtLocation instead of Symbol.type! * Unify parameter call-site inferences too Because they still have a separate code path, they didn't use the new unification code. Also some cleanup from PR comments. * Add object type unification test Also remove dead code. * Only use fallback if no inferences were found Instead of relying on the unification code to remove the fallback. --- src/compiler/checker.ts | 1 + src/compiler/types.ts | 2 + src/services/codefixes/inferFromUsage.ts | 116 +++++++++++++----- .../codeFixInferFromUsageEmptyTypePriority.ts | 13 ++ .../codeFixInferFromUsageMemberJS.ts | 4 +- ...codeFixInferFromUsageUnifyAnonymousType.ts | 19 +++ 6 files changed, 122 insertions(+), 33 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageEmptyTypePriority.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7df0414b90b..eee26f894dc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -301,6 +301,7 @@ namespace ts { getESSymbolType: () => esSymbolType, getNeverType: () => neverType, isSymbolAccessible, + getObjectFlags, isArrayLikeType, isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 1e592ad5886..a39d098443c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3173,6 +3173,8 @@ namespace ts { /* @internal */ getTypeCount(): number; /* @internal */ isArrayLikeType(type: Type): boolean; + /* @internal */ getObjectFlags(type: Type): ObjectFlags; + /** * True if `contextualType` should not be considered for completions because * e.g. it specifies `kind: "a"` and obj has `kind: "b"`. diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 12a0aeff730..d8e0bd08ebc 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -369,7 +369,9 @@ namespace ts.codefix { interface UsageContext { isNumber?: boolean; isString?: boolean; - isNumberOrString?: boolean; + hasNonVacuousType?: boolean; + hasNonVacuousNonAnonymousType?: boolean; + candidateTypes?: Type[]; properties?: UnderscoreEscapedMap; callContexts?: CallContext[]; @@ -384,7 +386,7 @@ namespace ts.codefix { cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - return getTypeFromUsageContext(usageContext, checker) || checker.getAnyType(); + return unifyFromContext(inferFromContext(usageContext, checker), checker); } export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { @@ -411,6 +413,7 @@ namespace ts.codefix { for (const callContext of callContexts) { if (callContext.argumentTypes.length <= parameterIndex) { isOptional = isInJSFile(declaration); + types.push(checker.getUndefinedType()); continue; } @@ -423,14 +426,10 @@ namespace ts.codefix { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); } } - - let type = types.length && checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); - if ((!type || type.flags & TypeFlags.Any) && isIdentifier(parameter.name)) { + let type = unifyFromContext(types, checker); + if (type.flags & TypeFlags.Any && isIdentifier(parameter.name)) { type = inferTypeForVariableFromUsage(parameter.name, program, cancellationToken); } - if (!type) { - type = checker.getAnyType(); - } return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, @@ -504,7 +503,8 @@ namespace ts.codefix { break; case SyntaxKind.PlusToken: - usageContext.isNumberOrString = true; + usageContext.isNumber = true; + usageContext.isString = true; break; // case SyntaxKind.ExclamationToken: @@ -575,7 +575,8 @@ namespace ts.codefix { usageContext.isString = true; } else { - usageContext.isNumberOrString = true; + usageContext.isNumber = true; + usageContext.isString = true; } break; @@ -649,7 +650,8 @@ namespace ts.codefix { function inferTypeFromPropertyElementExpressionContext(parent: ElementAccessExpression, node: Expression, checker: TypeChecker, usageContext: UsageContext): void { if (node === parent.argumentExpression) { - usageContext.isNumberOrString = true; + usageContext.isNumber = true; + usageContext.isString = true; return; } else { @@ -665,29 +667,83 @@ namespace ts.codefix { } } - function getTypeFromUsageContext(usageContext: UsageContext, checker: TypeChecker): Type | undefined { - if (usageContext.isNumberOrString && !usageContext.isNumber && !usageContext.isString) { - return checker.getUnionType([checker.getNumberType(), checker.getStringType()]); + function unifyFromContext(inferences: ReadonlyArray, checker: TypeChecker, fallback = checker.getAnyType()): Type { + if (!inferences.length) return fallback; + const hasNonVacuousType = inferences.some(i => !(i.flags & (TypeFlags.Any | TypeFlags.Void))); + const hasNonVacuousNonAnonymousType = inferences.some( + i => !(i.flags & (TypeFlags.Nullable | TypeFlags.Any | TypeFlags.Void)) && !(checker.getObjectFlags(i) & ObjectFlags.Anonymous)); + const anons = inferences.filter(i => checker.getObjectFlags(i) & ObjectFlags.Anonymous) as AnonymousType[]; + const good = []; + if (!hasNonVacuousNonAnonymousType && anons.length) { + good.push(unifyAnonymousTypes(anons, checker)); } - else if (usageContext.isNumber) { - return checker.getNumberType(); + good.push(...inferences.filter(i => !(checker.getObjectFlags(i) & ObjectFlags.Anonymous) && !(hasNonVacuousType && i.flags & (TypeFlags.Any | TypeFlags.Void)))); + return checker.getWidenedType(checker.getUnionType(good)); + } + + function unifyAnonymousTypes(anons: AnonymousType[], checker: TypeChecker) { + if (anons.length === 1) { + return anons[0]; } - else if (usageContext.isString) { - return checker.getStringType(); + const calls = []; + const constructs = []; + const stringIndices = []; + const numberIndices = []; + let stringIndexReadonly = false; + let numberIndexReadonly = false; + const props = createMultiMap(); + for (const anon of anons) { + for (const p of checker.getPropertiesOfType(anon)) { + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push(...checker.getSignaturesOfType(anon, SignatureKind.Call)); + constructs.push(...checker.getSignaturesOfType(anon, SignatureKind.Construct)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } } - else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(t => checker.getBaseTypeOfLiteralType(t)), UnionReduction.Subtype)); + const members = mapEntries(props, (name, types) => { + const isOptional = types.length < anons.length ? SymbolFlags.Optional : 0; + const s = checker.createSymbol(SymbolFlags.Property | isOptional, name as __String); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType( + anons[0].symbol, + members as UnderscoreEscapedMap, + calls, + constructs, + stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, + numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + + function inferFromContext(usageContext: UsageContext, checker: TypeChecker) { + const types = []; + if (usageContext.isNumber) { + types.push(checker.getNumberType()); } - else if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) { + if (usageContext.isString) { + types.push(checker.getStringType()); + } + + types.push(...(usageContext.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t))); + + if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) { const paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!; // TODO: GH#18217 const types = paramType.getCallSignatures().map(c => c.getReturnType()); - return checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType()); + types.push(checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType())); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push" as __String))) { - return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!); + types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push" as __String)!.callContexts!, /*isRestParameter*/ false, checker)!)); } - else if (usageContext.numberIndexContext) { - return checker.createArrayType(recur(usageContext.numberIndexContext)); + + if (usageContext.numberIndexContext) { + return [checker.createArrayType(recur(usageContext.numberIndexContext))]; } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { const members = createUnderscoreEscapedMap(); @@ -719,14 +775,12 @@ namespace ts.codefix { stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 - } - else { - return undefined; + types.push(checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 } + return types; function recur(innerContext: UsageContext): Type { - return getTypeFromUsageContext(innerContext, checker) || checker.getAnyType(); + return unifyFromContext(inferFromContext(innerContext, checker), checker); } } @@ -759,7 +813,7 @@ namespace ts.codefix { symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); parameters.push(symbol); } - const returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + const returnType = unifyFromContext(inferFromContext(callContext.returnType, checker), checker, checker.getVoidType()); // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } diff --git a/tests/cases/fourslash/codeFixInferFromUsageEmptyTypePriority.ts b/tests/cases/fourslash/codeFixInferFromUsageEmptyTypePriority.ts new file mode 100644 index 00000000000..e9288303781 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageEmptyTypePriority.ts @@ -0,0 +1,13 @@ +/// +// @strict: true +// based on acorn, translated to TS + +////function TokenType([|label, conf |]) { +//// if ( conf === void 0 ) conf = {}; +//// +//// var l = label; +//// var keyword = conf.keyword; +//// var beforeExpr = !!conf.beforeExpr; +////}; + +verify.rangeAfterCodeFix("label: any, conf: { keyword?: any; beforeExpr?: any; } | undefined",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts index 2a97b3dca32..f53c89b6fcc 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMemberJS.ts @@ -27,10 +27,10 @@ verify.codeFixAll({ constructor() { /** * this is fine - * @type {undefined} + * @type {number[] | undefined} */ this.p = undefined; - /** @type {undefined} */ + /** @type {number[] | undefined} */ this.q = undefined } method() { diff --git a/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts b/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts new file mode 100644 index 00000000000..50a9fcd071e --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts @@ -0,0 +1,19 @@ +/// +// @strict: true +// based on acorn, translated to TS + +////function kw([|name, options |]) { +//// if ( options === void 0 ) options = {}; +//// +//// options.keyword = name; +//// return keywords$1[name] = new TokenType(name, options) +////} +////kw("1") +////kw("2", { startsExpr: true }) +////kw("3", { beforeExpr: false }) +////kw("4", { isLoop: false }) +////kw("5", { beforeExpr: true, startsExpr: true }) +////kw("6", { beforeExpr: true, prefix: true, startsExpr: true }) + + +verify.rangeAfterCodeFix("name: string, options: { startsExpr?: boolean; beforeExpr?: boolean; isLoop?: boolean; prefix?: boolean; } | undefined",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); From a682a525b803f99e39b3be5c6b1557746599e80b Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 2 Nov 2018 09:08:04 -0700 Subject: [PATCH 201/262] module.exports aliases have correct flags (#28303) * module.exports aliases have correct flags They are marked both as (1) alias and (2) assignment declaration. This fixes alias resolution in cases where multiple module.exports assignments exist, but differ in whether they are aliases or not: ```js function f() { } module.exports = f module.exports = 23 ``` Previously, this construct would fail to resolve the alias `f` because the `export=` symbol would be marked as Alias | Value but not Assignment. This change just adds Assignment so that the assignment declaration alias-following rules apply: you should always follow the alias, regardless of other flags. Also, isAliasSymbolDeclaration needed to be tightened up. Previously, I missed the condition that `module.exports =` aliases required an EntityNameDeclaration on right-hand-side, just like `export default` and `export =` aliases. * Address PR comments 1. Rename test to be more accurate. 2. Always mark module.exports assignments with SymbolFlags.Assignment. --- src/compiler/binder.ts | 2 +- src/compiler/utilities.ts | 3 ++- ...rtFixWithMultipleModuleExportAssignment.ts | 21 +++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/importFixWithMultipleModuleExportAssignment.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index c35a62b8448..6881dc60e98 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2418,7 +2418,7 @@ namespace ts { const flags = exportAssignmentIsAlias(node) ? SymbolFlags.Alias // An export= with an EntityNameExpression or a ClassExpression exports all meanings of that identifier or class : SymbolFlags.Property | SymbolFlags.ExportValue | SymbolFlags.ValueModule; - declareSymbol(file.symbol.exports!, file.symbol, node, flags, SymbolFlags.None); + declareSymbol(file.symbol.exports!, file.symbol, node, flags | SymbolFlags.Assignment, SymbolFlags.None); } function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 991e403f52e..d0564f7ef01 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2490,6 +2490,7 @@ namespace ts { // export { x as } from ... // export = // export default + // module.exports = export function isAliasSymbolDeclaration(node: Node): boolean { return node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration || @@ -2498,7 +2499,7 @@ namespace ts { node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || - isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports; + isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node); } export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean { diff --git a/tests/cases/fourslash/importFixWithMultipleModuleExportAssignment.ts b/tests/cases/fourslash/importFixWithMultipleModuleExportAssignment.ts new file mode 100644 index 00000000000..546a613947f --- /dev/null +++ b/tests/cases/fourslash/importFixWithMultipleModuleExportAssignment.ts @@ -0,0 +1,21 @@ +/// + +// @allowJs: true +// @checkJs: true + +// @Filename: /a.js +////function f() {} +////module.exports = f; +////module.exports = 42; + +// @Filename: /b.js +////export const foo = 0; + +// @Filename: /c.js +////foo + +goTo.file("/c.js"); +verify.importFixAtPosition([ +`import { foo } from "./b"; + +foo`]); From afbf89e3b3983fef4dfb5487556b374039e2744e Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 2 Nov 2018 10:07:21 -0700 Subject: [PATCH 202/262] Refactors can return ReadonlyArray (#28305) * Refactors can return ReadonlyArray * Remove unnecessary type assertions --- src/harness/fourslash.ts | 2 +- src/services/refactorProvider.ts | 2 +- .../refactors/addOrRemoveBracesToArrowFunction.ts | 4 ++-- src/services/refactors/convertExport.ts | 4 ++-- src/services/refactors/convertImport.ts | 4 ++-- src/services/refactors/extractSymbol.ts | 8 ++++---- .../refactors/generateGetAccessorAndSetAccessor.ts | 4 ++-- src/services/refactors/moveToNewFile.ts | 4 ++-- src/testRunner/unittests/extractTestHelpers.ts | 4 ++-- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 8f83f0bc3f0..aeb2920ce3d 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -5021,7 +5021,7 @@ namespace FourSlashInterface { export interface VerifyRefactorOptions { name: string; actionName: string; - refactors: ts.ApplicableRefactorInfo[]; + refactors: ReadonlyArray; } export interface VerifyCompletionActionOptions extends NewContentOptions { diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index adb3af3ea7a..e1ac6a58f8d 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -5,7 +5,7 @@ namespace ts { getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; /** Compute (quickly) which actions are available here */ - getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined; + getAvailableActions(context: RefactorContext): ReadonlyArray; } export interface RefactorContext extends textChanges.TextChangesContext { diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index 57e7dbd97a7..c5fccde13db 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -15,10 +15,10 @@ namespace ts.refactor.addOrRemoveBracesToArrowFunction { addBraces: boolean; } - function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - if (!info) return undefined; + if (!info) return emptyArray; return [{ name: refactorName, diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index ca31ef58100..60729d85487 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -4,9 +4,9 @@ namespace ts.refactor { const actionNameDefaultToNamed = "Convert default export to named export"; const actionNameNamedToDefault = "Convert named export to default export"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { + getAvailableActions(context): ReadonlyArray { const info = getInfo(context); - if (!info) return undefined; + if (!info) return emptyArray; const description = info.wasDefault ? Diagnostics.Convert_default_export_to_named_export.message : Diagnostics.Convert_named_export_to_default_export.message; const actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; return [{ name: refactorName, description, actions: [{ name: actionName, description }] }]; diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index c91c06cb1fa..862717e728a 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -4,9 +4,9 @@ namespace ts.refactor { const actionNameNamespaceToNamed = "Convert namespace import to named imports"; const actionNameNamedToNamespace = "Convert named imports to namespace import"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { + getAvailableActions(context): ReadonlyArray { const i = getImportToConvert(context); - if (!i) return undefined; + if (!i) return emptyArray; const description = i.kind === SyntaxKind.NamespaceImport ? Diagnostics.Convert_namespace_import_to_named_imports.message : Diagnostics.Convert_named_imports_to_namespace_import.message; const actionName = i.kind === SyntaxKind.NamespaceImport ? actionNameNamespaceToNamed : actionNameNamedToNamespace; return [{ name: refactorName, description, actions: [{ name: actionName, description }] }]; diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 96b5ba18070..df828c783de 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -7,18 +7,18 @@ namespace ts.refactor.extractSymbol { * Compute the associated code actions * Exported for tests. */ - export function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { + export function getAvailableActions(context: RefactorContext): ReadonlyArray { const rangeToExtract = getRangeToExtract(context.file, getRefactorContextSpan(context)); const targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { - return undefined; + return emptyArray; } const extractions = getPossibleExtractions(targetRange, context); if (extractions === undefined) { // No extractions possible - return undefined; + return emptyArray; } const functionActions: RefactorActionInfo[] = []; @@ -82,7 +82,7 @@ namespace ts.refactor.extractSymbol { }); } - return infos.length ? infos : undefined; + return infos.length ? infos : emptyArray; } /* Exported for tests */ diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index 96b8b1e8b06..70f16e3b7b2 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -20,8 +20,8 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { readonly renameAccessor: boolean; } - function getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined { - if (!getConvertibleFieldAtPosition(context)) return undefined; + function getAvailableActions(context: RefactorContext): ReadonlyArray { + if (!getConvertibleFieldAtPosition(context)) return emptyArray; return [{ name: actionName, diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 757b1ab71cf..87973226b3c 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -2,8 +2,8 @@ namespace ts.refactor { const refactorName = "Move to a new file"; registerRefactor(refactorName, { - getAvailableActions(context): ApplicableRefactorInfo[] | undefined { - if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return undefined; + getAvailableActions(context): ReadonlyArray { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) return emptyArray; const description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); return [{ name: refactorName, description, actions: [{ name: refactorName, description }] }]; }, diff --git a/src/testRunner/unittests/extractTestHelpers.ts b/src/testRunner/unittests/extractTestHelpers.ts index 6a74a637e92..cc3ba9f372e 100644 --- a/src/testRunner/unittests/extractTestHelpers.ts +++ b/src/testRunner/unittests/extractTestHelpers.ts @@ -107,7 +107,7 @@ namespace ts { }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); assert.equal(rangeToExtract.errors, undefined, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText); - const infos = refactor.extractSymbol.getAvailableActions(context)!; + const infos = refactor.extractSymbol.getAvailableActions(context); const actions = find(infos, info => info.description === description.message)!.actions; const data: string[] = []; @@ -169,7 +169,7 @@ namespace ts { }; const rangeToExtract = refactor.extractSymbol.getRangeToExtract(sourceFile, createTextSpanFromRange(selectionRange)); assert.isUndefined(rangeToExtract.errors, rangeToExtract.errors && "Range error: " + rangeToExtract.errors[0].messageText); - const infos = refactor.extractSymbol.getAvailableActions(context)!; + const infos = refactor.extractSymbol.getAvailableActions(context); assert.isUndefined(find(infos, info => info.description === description.message)); }); } From 4e59096ea557a0d9a0a92fc6bd3a6b1195c53679 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 2 Nov 2018 14:33:02 -0700 Subject: [PATCH 203/262] Exclude keywords from import completions (#28114) * Exclude keywords from import completions * Still allow contextual keywords * Add excludes tests --- src/compiler/utilities.ts | 4 ++ src/services/completions.ts | 10 +++-- .../fourslash/completionsImport_keywords.ts | 42 +++++++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) create mode 100644 tests/cases/fourslash/completionsImport_keywords.ts diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index d0564f7ef01..5d9a77c2a98 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2586,6 +2586,10 @@ namespace ts { return token !== undefined && isNonContextualKeyword(token); } + export function isIdentifierANonContextualKeyword({ originalKeywordKind }: Identifier): boolean { + return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); + } + export type TriviaKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia diff --git a/src/services/completions.ts b/src/services/completions.ts index 1573db9a249..c7d888b647e 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1167,14 +1167,16 @@ namespace ts.Completions { // 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 comes from an `export * from "foo"` re-export. Those don't create new symbols. - // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). + // 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 => isExportSpecifier(d) && !d.propertyName && !!d.parent.parent.moduleSpecifier)) { + || 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; } - const isDefaultExport = symbol.name === InternalSymbolName.Default; + const isDefaultExport = symbol.escapedName === InternalSymbolName.Default; if (isDefaultExport) { symbol = getLocalSymbolForExportDefault(symbol) || symbol; } diff --git a/tests/cases/fourslash/completionsImport_keywords.ts b/tests/cases/fourslash/completionsImport_keywords.ts new file mode 100644 index 00000000000..3ac4e0b320e --- /dev/null +++ b/tests/cases/fourslash/completionsImport_keywords.ts @@ -0,0 +1,42 @@ +/// + +// @Filename: /a.ts +////const _break = 0; +////export { _break as break }; +////const _implements = 0; +////export { _implements as implements }; +////const _unique = 0; +////export { _unique as unique }; + +// Note: `export const unique = 0;` is legal, +// but we want to test that we don't block an import completion of 'unique' just because it appears in an ExportSpecifier. + +// @Filename: /b.ts +////br/*break*/ +////im/*implements*/ +////un/*unique*/ + +const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; +verify.completions( + // no reserved words + { + marker: "break", + includes: { name: "break", text: "break", kind: "keyword" }, + excludes: { name: "break", source: "/a" }, + preferences, + }, + // no strict mode reserved words + { + marker: "implements", + includes: { name: "implements", text: "implements", kind: "keyword" }, + excludes: { name: "implements", source: "/a" }, + preferences, + }, + // yes contextual keywords + { + marker: "unique", + includes: { name: "unique", source: "/a", sourceDisplay: "./a", text: "(alias) const unique: 0\nexport unique", hasAction: true }, + excludes: { name: "unique", source: undefined }, + preferences, + }, +); From ce85ee511586f753da3cf3f816e4311271dedf30 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Fri, 2 Nov 2018 15:39:27 -0700 Subject: [PATCH 204/262] Move infer-from-usage earlier in codefix list (#28318) This makes it appear before the ts-ignore codefix, specifically. --- src/services/tsconfig.json | 2 +- .../fourslash/codeFixInferFromUsageCommentAfterParameter.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts | 2 +- .../fourslash/codeFixInferFromUsageMultipleParametersJS.ts | 2 +- .../fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts | 2 +- .../fourslash/codeFixInferFromUsagePartialParameterListJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts | 2 +- .../codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts | 2 +- .../fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts | 2 +- tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts | 2 +- 18 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 66b1977ddc5..690bad237ab 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -45,6 +45,7 @@ "refactorProvider.ts", "codefixes/addMissingInvocationForDecorator.ts", "codefixes/annotateWithTypeFromJSDoc.ts", + "codefixes/inferFromUsage.ts", "codefixes/convertFunctionToEs6Class.ts", "codefixes/convertToAsyncFunction.ts", "codefixes/convertToEs6Module.ts", @@ -66,7 +67,6 @@ "codefixes/fixAwaitInSyncFunction.ts", "codefixes/disableJsDiagnostics.ts", "codefixes/helpers.ts", - "codefixes/inferFromUsage.ts", "codefixes/fixInvalidImportSyntax.ts", "codefixes/fixStrictClassInitialization.ts", "codefixes/generateTypes.ts", diff --git a/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts b/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts index b46600d927f..bdefd2b5dea 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageCommentAfterParameter.ts @@ -13,7 +13,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {(arg0: any) => void} callback diff --git a/tests/cases/fourslash/codeFixInferFromUsageJS.ts b/tests/cases/fourslash/codeFixInferFromUsageJS.ts index 62c9d1bf90b..be36fec5825 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageJS.ts @@ -9,4 +9,4 @@ //// foo += 2; ////} -verify.rangeAfterCodeFix("/** @type {number} */\nvar foo;",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); +verify.rangeAfterCodeFix("/** @type {number} */\nvar foo;",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts index dc52286a906..c561510cfc7 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMember2JS.ts @@ -11,4 +11,4 @@ ////i.p = 0; -verify.rangeAfterCodeFix("p: number", undefined, undefined, 1); +verify.rangeAfterCodeFix("p: number", undefined, undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts index d57f3292375..d82700c1709 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageMultipleParametersJS.ts @@ -11,7 +11,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 6, + index: 4, newFileContent: `/** * @param {number} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts index d494d1dbb7b..22b8e62bc76 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageNumberIndexSignatureJS.ts @@ -10,7 +10,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {number[]} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts index 7003950b7ff..dbf29fe2f5d 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageOptionalParamJS.ts @@ -12,7 +12,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {number} [a] diff --git a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts index 034fe7d0411..9b4e4d8442b 100644 --- a/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsagePartialParameterListJS.ts @@ -15,7 +15,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {*} y diff --git a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts index 322d51a79ab..ed9d4b33b37 100644 --- a/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts @@ -18,7 +18,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {{ b: { c: any; }; }} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts index 609ab76b787..d5c1fd54bb5 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam2JS.ts @@ -15,7 +15,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {number} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts index 2c6da348852..dec7f8e7674 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParam3JS.ts @@ -12,7 +12,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `/** * @param {number} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts index 7e87bc3d256..4b7f046ca18 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageRestParamJS.ts @@ -15,7 +15,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 4, + index: 2, newFileContent: `/** * @param {number} a diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts index c9c0c719de4..54350bb493f 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterJS.ts @@ -13,7 +13,7 @@ verify.codeFix({ description: "Infer type of \'x\' from usage", - index: 2, + index: 0, newFileContent: `class C { /** diff --git a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts index 7620b969234..c5fc937a9b8 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSetterWithInaccessibleTypeJS.ts @@ -22,7 +22,7 @@ goTo.file("/b.js"); verify.codeFix({ - index: 2, + index: 0, description: "Infer type of 'x' from usage", newFileContent: `export class C { diff --git a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts index 42f5481f143..dec76892cb2 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageSingleLineClassJS.ts @@ -11,7 +11,7 @@ verify.codeFix({ description: "Infer parameter types from usage", - index: 2, + index: 0, newFileContent: `class C {/** * @param {number} x diff --git a/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts index 5182e80969e..c3305988dec 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageStringIndexSignatureJS.ts @@ -11,7 +11,7 @@ ////} verify.codeFix({ - index: 2, + index: 0, description: "Infer parameter types from usage", newFileContent: `/** diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts index 0e88a30b96b..27482acf377 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageVariable2JS.ts @@ -15,4 +15,4 @@ var x; function f() { x++; } -`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); +`, /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts index 8e96fd08916..bbd5409a25c 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageVariableJS.ts @@ -11,4 +11,4 @@ //// x++; ////} -verify.rangeAfterCodeFix("/** @type {number } */\nvar x;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 2); +verify.rangeAfterCodeFix("/** @type {number } */\nvar x;", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); From 92a48d8880b9bf6084a2d392e57e258a589e1bb9 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 2 Nov 2018 16:12:46 -0700 Subject: [PATCH 205/262] Improve error message when scriptInfo is missing in mapTextChangeToCodeEdit (#28258) * Improve error message when scriptInfo is missing in mapTextChangeToCodeEdit * Include both fileName and path, and use in more places * Move logErrorForScriptInfoNotFound to editorServices.ts * Update API --- src/server/editorServices.ts | 8 +++++++- src/server/session.ts | 25 +++++++++++++++---------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index b649527572e..2f3c6204937 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -867,7 +867,7 @@ namespace ts.server { private doEnsureDefaultProjectForFile(fileName: NormalizedPath): Project { this.ensureProjectStructuresUptoDate(); const scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : Errors.ThrowNoProject(); + return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), Errors.ThrowNoProject()); } getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string) { @@ -1966,6 +1966,12 @@ namespace ts.server { return configProject && configProject.getCompilerOptions().configFile; } + /* @internal */ + logErrorForScriptInfoNotFound(fileName: string): void { + const names = arrayFrom(this.filenameToScriptInfo.entries()).map(([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName })); + this.logger.msg(`Could not find file ${JSON.stringify(fileName)}.\nAll files are: ${JSON.stringify(names)}`, Msg.Err); + } + /** * Returns the projects that contain script info through SymLink * Note that this does not return projects in info.containingProjects diff --git a/src/server/session.ts b/src/server/session.ts index da4808c31f6..42d3994db09 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1157,7 +1157,9 @@ namespace ts.server { this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); if (!scriptInfo) { - return ignoreNoProjectError ? emptyArray : Errors.ThrowNoProject(); + if (ignoreNoProjectError) return emptyArray; + this.projectService.logErrorForScriptInfoNotFound(args.file); + return Errors.ThrowNoProject(); } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); @@ -1165,6 +1167,7 @@ namespace ts.server { // filter handles case when 'projects' is undefined projects = filter(projects, p => p.languageServiceEnabled && !p.isOrphan()); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { + this.projectService.logErrorForScriptInfoNotFound(args.file); return Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects!, symLinkedProjects } : projects!; // TODO: GH#18217 @@ -1908,8 +1911,17 @@ namespace ts.server { return textChanges.map(change => this.mapTextChangeToCodeEdit(change)); } - private mapTextChangeToCodeEdit(change: FileTextChanges): protocol.FileCodeEdits { - return mapTextChangesToCodeEdits(change, this.projectService.getScriptInfoOrConfig(change.fileName)); + private mapTextChangeToCodeEdit(textChanges: FileTextChanges): protocol.FileCodeEdits { + const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName); + if (!!textChanges.isNewFile === !!scriptInfo) { + if (!scriptInfo) { // and !isNewFile + this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName); + } + Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); + } + return scriptInfo + ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(textChange => convertTextChangeToCodeEdit(textChange, scriptInfo)) } + : convertNewFileTextChangeToCodeEdit(textChanges); } private convertTextChangeToCodeEdit(change: TextChange, scriptInfo: ScriptInfo): protocol.CodeEdit { @@ -2431,13 +2443,6 @@ namespace ts.server { return { file: fileName, start: scriptInfo.positionToLineOffset(textSpan.start), end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)) }; } - function mapTextChangesToCodeEdits(textChanges: FileTextChanges, scriptInfo: ScriptInfoOrConfig | undefined): protocol.FileCodeEdits { - Debug.assert(!!textChanges.isNewFile === !scriptInfo, "Expected isNewFile for (only) new files", () => JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo })); - return scriptInfo - ? { fileName: textChanges.fileName, textChanges: textChanges.textChanges.map(textChange => convertTextChangeToCodeEdit(textChange, scriptInfo)) } - : convertNewFileTextChangeToCodeEdit(textChanges); - } - function convertTextChangeToCodeEdit(change: TextChange, scriptInfo: ScriptInfoOrConfig): protocol.CodeEdit { return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText }; } From eba83f4ea76112fa66d036f09038e868cda760ba Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 2 Nov 2018 17:29:05 -0700 Subject: [PATCH 206/262] Add related span for mixin constructor error (#28319) * Add related span for mixin constructor error * Remove unneeded casts * Nicer style --- src/compiler/checker.ts | 13 ++++++- src/compiler/diagnosticMessages.json | 4 +++ .../baseConstraintOfDecorator.errors.txt | 25 ++++++++++++- .../reference/baseConstraintOfDecorator.js | 31 ++++++++++++++++ .../baseConstraintOfDecorator.symbols | 34 ++++++++++++++++++ .../reference/baseConstraintOfDecorator.types | 35 +++++++++++++++++++ .../compiler/baseConstraintOfDecorator.ts | 10 ++++++ 7 files changed, 150 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eee26f894dc..e17b38ff736 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5674,7 +5674,18 @@ namespace ts { return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & TypeFlags.Any) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + if (baseConstructorType.flags & TypeFlags.TypeParameter) { + const constraint = getConstraintFromTypeParameter(baseConstructorType); + let ctorReturn: Type = unknownType; + if (constraint) { + const ctorSig = getSignaturesOfType(constraint, SignatureKind.Construct); + if (ctorSig[0]) { + ctorReturn = getReturnTypeOfSignature(ctorSig[0]); + } + } + addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + } return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index e2dd0a1b7cd..6f22515dea7 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2493,6 +2493,10 @@ "category": "Error", "code": 2734 }, + "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?": { + "category": "Error", + "code": 2735 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", diff --git a/tests/baselines/reference/baseConstraintOfDecorator.errors.txt b/tests/baselines/reference/baseConstraintOfDecorator.errors.txt index efc0c59f9ee..3af8756fac2 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.errors.txt +++ b/tests/baselines/reference/baseConstraintOfDecorator.errors.txt @@ -1,13 +1,36 @@ tests/cases/compiler/baseConstraintOfDecorator.ts(2,5): error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. tests/cases/compiler/baseConstraintOfDecorator.ts(2,40): error TS2507: Type 'TFunction' is not a constructor function type. +tests/cases/compiler/baseConstraintOfDecorator.ts(12,5): error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. +tests/cases/compiler/baseConstraintOfDecorator.ts(12,40): error TS2507: Type 'TFunction' is not a constructor function type. -==== tests/cases/compiler/baseConstraintOfDecorator.ts (2 errors) ==== +==== tests/cases/compiler/baseConstraintOfDecorator.ts (4 errors) ==== export function classExtender(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { return class decoratorFunc extends superClass { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~ !!! error TS2507: Type 'TFunction' is not a constructor function type. +!!! related TS2735 tests/cases/compiler/baseConstraintOfDecorator.ts:1:31: Did you mean for 'TFunction' to be constrained to type 'new (...args: any[]) => unknown'? + constructor(...args: any[]) { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + super(...args); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + _instanceModifier(this, args); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + } + ~~~~~~~~~ + }; + ~~~~~~ +!!! error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. + } + + class MyClass { private x; } + export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { + return class decoratorFunc extends superClass { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~ +!!! error TS2507: Type 'TFunction' is not a constructor function type. +!!! related TS2735 tests/cases/compiler/baseConstraintOfDecorator.ts:11:32: Did you mean for 'TFunction' to be constrained to type 'new (...args: any[]) => MyClass'? constructor(...args: any[]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ super(...args); diff --git a/tests/baselines/reference/baseConstraintOfDecorator.js b/tests/baselines/reference/baseConstraintOfDecorator.js index a7f6b6e41cb..0c1f77e31e6 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.js +++ b/tests/baselines/reference/baseConstraintOfDecorator.js @@ -7,6 +7,16 @@ export function classExtender(superClass: TFunction, _instanceModifie } }; } + +class MyClass { private x; } +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { + return class decoratorFunc extends superClass { + constructor(...args: any[]) { + super(...args); + _instanceModifier(this, args); + } + }; +} //// [baseConstraintOfDecorator.js] @@ -41,3 +51,24 @@ function classExtender(superClass, _instanceModifier) { }(superClass)); } exports.classExtender = classExtender; +var MyClass = /** @class */ (function () { + function MyClass() { + } + return MyClass; +}()); +function classExtender2(superClass, _instanceModifier) { + return /** @class */ (function (_super) { + __extends(decoratorFunc, _super); + function decoratorFunc() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _this = _super.apply(this, args) || this; + _instanceModifier(_this, args); + return _this; + } + return decoratorFunc; + }(superClass)); +} +exports.classExtender2 = classExtender2; diff --git a/tests/baselines/reference/baseConstraintOfDecorator.symbols b/tests/baselines/reference/baseConstraintOfDecorator.symbols index 71d7773a7cf..9048d7ed568 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.symbols +++ b/tests/baselines/reference/baseConstraintOfDecorator.symbols @@ -27,3 +27,37 @@ export function classExtender(superClass: TFunction, _instanceModifie }; } +class MyClass { private x; } +>MyClass : Symbol(MyClass, Decl(baseConstraintOfDecorator.ts, 7, 1)) +>x : Symbol(MyClass.x, Decl(baseConstraintOfDecorator.ts, 9, 15)) + +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { +>classExtender2 : Symbol(classExtender2, Decl(baseConstraintOfDecorator.ts, 9, 28)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 10, 54)) +>MyClass : Symbol(MyClass, Decl(baseConstraintOfDecorator.ts, 7, 1)) +>superClass : Symbol(superClass, Decl(baseConstraintOfDecorator.ts, 10, 85)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) +>_instanceModifier : Symbol(_instanceModifier, Decl(baseConstraintOfDecorator.ts, 10, 107)) +>instance : Symbol(instance, Decl(baseConstraintOfDecorator.ts, 10, 128)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 10, 142)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) + + return class decoratorFunc extends superClass { +>decoratorFunc : Symbol(decoratorFunc, Decl(baseConstraintOfDecorator.ts, 11, 10)) +>superClass : Symbol(superClass, Decl(baseConstraintOfDecorator.ts, 10, 85)) + + constructor(...args: any[]) { +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + + super(...args); +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + + _instanceModifier(this, args); +>_instanceModifier : Symbol(_instanceModifier, Decl(baseConstraintOfDecorator.ts, 10, 107)) +>this : Symbol(decoratorFunc, Decl(baseConstraintOfDecorator.ts, 11, 10)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + } + }; +} + diff --git a/tests/baselines/reference/baseConstraintOfDecorator.types b/tests/baselines/reference/baseConstraintOfDecorator.types index edf9641a4ba..a5a277c5d2a 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.types +++ b/tests/baselines/reference/baseConstraintOfDecorator.types @@ -29,3 +29,38 @@ export function classExtender(superClass: TFunction, _instanceModifie }; } +class MyClass { private x; } +>MyClass : MyClass +>x : any + +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { +>classExtender2 : MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void) => TFunction +>args : string[] +>superClass : TFunction +>_instanceModifier : (instance: any, args: any[]) => void +>instance : any +>args : any[] + + return class decoratorFunc extends superClass { +>class decoratorFunc extends superClass { constructor(...args: any[]) { super(...args); _instanceModifier(this, args); } } : typeof decoratorFunc +>decoratorFunc : typeof decoratorFunc +>superClass : TFunction + + constructor(...args: any[]) { +>args : any[] + + super(...args); +>super(...args) : void +>super : any +>...args : any +>args : any[] + + _instanceModifier(this, args); +>_instanceModifier(this, args) : void +>_instanceModifier : (instance: any, args: any[]) => void +>this : this +>args : any[] + } + }; +} + diff --git a/tests/cases/compiler/baseConstraintOfDecorator.ts b/tests/cases/compiler/baseConstraintOfDecorator.ts index d8eb00f07da..9419974a04f 100644 --- a/tests/cases/compiler/baseConstraintOfDecorator.ts +++ b/tests/cases/compiler/baseConstraintOfDecorator.ts @@ -6,3 +6,13 @@ export function classExtender(superClass: TFunction, _instanceModifie } }; } + +class MyClass { private x; } +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { + return class decoratorFunc extends superClass { + constructor(...args: any[]) { + super(...args); + _instanceModifier(this, args); + } + }; +} From 4cb210ce2efcf37106fd5e3cec31fa77275e8b76 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 5 Nov 2018 11:29:16 -0800 Subject: [PATCH 207/262] Parameters infer from body and call sites (#28342) * Parameters infer from body usage and call sites * Function expressions infer from variable decl usages If the function expression is the initialiser of a variable declaration. * Update isApplicableFunctionForInference too * Update baseline --- src/services/codefixes/inferFromUsage.ts | 45 +++++++++++-------- .../fourslash/annotateWithTypeFromJSDoc8.ts | 1 + .../codeFixInferFromUsageCallBodyBoth.ts | 16 +++++++ ...codeFixInferFromUsageFunctionExpression.ts | 9 ++++ ...codeFixInferFromUsageUnifyAnonymousType.ts | 2 +- 5 files changed, 53 insertions(+), 20 deletions(-) create mode 100644 tests/cases/fourslash/codeFixInferFromUsageCallBodyBoth.ts create mode 100644 tests/cases/fourslash/codeFixInferFromUsageFunctionExpression.ts diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index d8e0bd08ebc..528674c1251 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -194,7 +194,8 @@ namespace ts.codefix { case SyntaxKind.Constructor: return true; case SyntaxKind.FunctionExpression: - return !!declaration.name; + const parent = declaration.parent; + return isVariableDeclaration(parent) && isIdentifier(parent.name) || !!declaration.name; } return false; } @@ -335,22 +336,31 @@ namespace ts.codefix { } function inferTypeForVariableFromUsage(token: Identifier, program: Program, cancellationToken: CancellationToken): Type { - return InferFromReference.inferTypeFromReferences(getReferences(token, program, cancellationToken), program.getTypeChecker(), cancellationToken); + const references = getReferences(token, program, cancellationToken); + const checker = program.getTypeChecker(); + const types = InferFromReference.inferTypesFromReferences(references, checker, cancellationToken); + return InferFromReference.unifyFromContext(types, checker); } function inferTypeForParametersFromUsage(containingFunction: FunctionLikeDeclaration, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + let searchToken; switch (containingFunction.kind) { case SyntaxKind.Constructor: + searchToken = findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile); + break; case SyntaxKind.FunctionExpression: + const parent = containingFunction.parent; + searchToken = isVariableDeclaration(parent) && isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - const isConstructor = containingFunction.kind === SyntaxKind.Constructor; - const searchToken = isConstructor ? - findChildOfKind>(containingFunction, SyntaxKind.ConstructorKeyword, sourceFile) : - containingFunction.name; - if (searchToken) { - return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); - } + searchToken = containingFunction.name; + break; + } + if (searchToken) { + return InferFromReference.inferTypeForParametersFromReferences(getReferences(searchToken, program, cancellationToken), containingFunction, program, cancellationToken); } } @@ -380,13 +390,13 @@ namespace ts.codefix { stringIndexContext?: UsageContext; } - export function inferTypeFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type { + export function inferTypesFromReferences(references: ReadonlyArray, checker: TypeChecker, cancellationToken: CancellationToken): Type[] { const usageContext: UsageContext = {}; for (const reference of references) { cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - return unifyFromContext(inferFromContext(usageContext, checker), checker); + return inferFromContext(usageContext, checker); } export function inferTypeForParametersFromReferences(references: ReadonlyArray, declaration: FunctionLikeDeclaration, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { @@ -394,7 +404,6 @@ namespace ts.codefix { if (references.length === 0) { return undefined; } - if (!declaration.parameters) { return undefined; } @@ -414,10 +423,8 @@ namespace ts.codefix { if (callContext.argumentTypes.length <= parameterIndex) { isOptional = isInJSFile(declaration); types.push(checker.getUndefinedType()); - continue; } - - if (isRest) { + else if (isRest) { for (let i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -426,10 +433,10 @@ namespace ts.codefix { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[parameterIndex])); } } - let type = unifyFromContext(types, checker); - if (type.flags & TypeFlags.Any && isIdentifier(parameter.name)) { - type = inferTypeForVariableFromUsage(parameter.name, program, cancellationToken); + if (isIdentifier(parameter.name)) { + types.push(...inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken)); } + const type = unifyFromContext(types, checker); return { type: isRest ? checker.createArrayType(type) : type, isOptional: isOptional && !isRest, @@ -667,7 +674,7 @@ namespace ts.codefix { } } - function unifyFromContext(inferences: ReadonlyArray, checker: TypeChecker, fallback = checker.getAnyType()): Type { + export function unifyFromContext(inferences: ReadonlyArray, checker: TypeChecker, fallback = checker.getAnyType()): Type { if (!inferences.length) return fallback; const hasNonVacuousType = inferences.some(i => !(i.flags & (TypeFlags.Any | TypeFlags.Void))); const hasNonVacuousNonAnonymousType = inferences.some( diff --git a/tests/cases/fourslash/annotateWithTypeFromJSDoc8.ts b/tests/cases/fourslash/annotateWithTypeFromJSDoc8.ts index 40ddf4fad0e..ca9450c1e6f 100644 --- a/tests/cases/fourslash/annotateWithTypeFromJSDoc8.ts +++ b/tests/cases/fourslash/annotateWithTypeFromJSDoc8.ts @@ -10,6 +10,7 @@ verify.codeFix({ description: "Annotate with type from JSDoc", + index: 0, newFileContent: `/** * @param {number} x diff --git a/tests/cases/fourslash/codeFixInferFromUsageCallBodyBoth.ts b/tests/cases/fourslash/codeFixInferFromUsageCallBodyBoth.ts new file mode 100644 index 00000000000..859d5ea2ce7 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageCallBodyBoth.ts @@ -0,0 +1,16 @@ +/// + +////class C { +//// +////} +////var c = new C() +////function f([|x, y |]) { +//// if (y) { +//// x = 1 +//// } +//// return x +////} +////f(new C()) + + +verify.rangeAfterCodeFix("x: number | C, y: undefined",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); diff --git a/tests/cases/fourslash/codeFixInferFromUsageFunctionExpression.ts b/tests/cases/fourslash/codeFixInferFromUsageFunctionExpression.ts new file mode 100644 index 00000000000..ab52ec82e2d --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageFunctionExpression.ts @@ -0,0 +1,9 @@ +/// + +////var f = function ([|x |]) { +//// return x +////} +////f(1) + +verify.rangeAfterCodeFix("x: number",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); + diff --git a/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts b/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts index 50a9fcd071e..e422eb7653f 100644 --- a/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts +++ b/tests/cases/fourslash/codeFixInferFromUsageUnifyAnonymousType.ts @@ -16,4 +16,4 @@ ////kw("6", { beforeExpr: true, prefix: true, startsExpr: true }) -verify.rangeAfterCodeFix("name: string, options: { startsExpr?: boolean; beforeExpr?: boolean; isLoop?: boolean; prefix?: boolean; } | undefined",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); +verify.rangeAfterCodeFix("name: string | number, options: { startsExpr?: boolean; beforeExpr?: boolean; isLoop?: boolean; prefix?: boolean; keyword?: any; } | undefined",/*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, 0); From 0c1bf316a2002a2c370cf258a36b8e462fd3218d Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 12:01:42 -0700 Subject: [PATCH 208/262] Declaration files for BigInt --- src/compiler/commandLineParser.ts | 3 +- src/lib/esnext.bigint.d.ts | 609 ++++++++++++++++++ src/lib/esnext.d.ts | 1 + src/lib/libs.json | 1 + .../unittests/commandLineParsing.ts | 6 +- .../convertCompilerOptionsFromJson.ts | 8 +- 6 files changed, 620 insertions(+), 8 deletions(-) create mode 100644 src/lib/esnext.bigint.d.ts diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 078a158f8f8..cbd6188ff66 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -44,7 +44,8 @@ namespace ts { ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], - ["esnext.intl", "lib.esnext.intl.d.ts"] + ["esnext.intl", "lib.esnext.intl.d.ts"], + ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; /** diff --git a/src/lib/esnext.bigint.d.ts b/src/lib/esnext.bigint.d.ts new file mode 100644 index 00000000000..667422bf890 --- /dev/null +++ b/src/lib/esnext.bigint.d.ts @@ -0,0 +1,609 @@ +interface BigInt { + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. + */ + toString(radix?: number): string; + + /** Returns a string representation appropriate to the host environment's current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): bigint; + + readonly [Symbol.toStringTag]: "BigInt"; +} + +interface BigIntConstructor { + (value?: any): bigint; + readonly prototype: BigInt; + + /** + * Interprets the low bits of a BigInt as a 2's-complement signed integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asIntN(bits: number, int: bigint): bigint; + /** + * Interprets the low bits of a BigInt as an unsigned integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ + asUintN(bits: number, int: bigint): bigint; +} + +declare const BigInt: BigIntConstructor; + +/** + * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated, an exception is raised. + */ +interface BigInt64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** The length in bytes of the array. */ + readonly byteLength: number; + + /** The offset in bytes of the array. */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: bigint, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; + + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: bigint, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: bigint, fromIndex?: number): number; + + /** The length of the array. */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): BigInt64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigInt64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigInt64Array"; + + [index: number]: bigint; +} + +interface BigInt64ArrayConstructor { + readonly prototype: BigInt64Array; + new(length?: number): BigInt64Array; + new(array: Iterable): BigInt64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: bigint[]): BigInt64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike): BigInt64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; +} + +declare const BigInt64Array: BigInt64ArrayConstructor; + +/** + * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the + * requested number of bytes could not be allocated, an exception is raised. + */ +interface BigUint64Array { + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** The ArrayBuffer instance referenced by the array. */ + readonly buffer: ArrayBufferLike; + + /** The length in bytes of the array. */ + readonly byteLength: number; + + /** The offset in bytes of the array. */ + readonly byteOffset: number; + + /** + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ + copyWithin(target: number, start: number, end?: number): this; + + /** Yields index, value pairs for every entry in the array. */ + entries(): IterableIterator<[number, bigint]>; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ + fill(value: bigint, start?: number, end?: number): this; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls + * the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; + + /** + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the first element in the array where predicate is true, and -1 + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; + + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + indexOf(searchElement: bigint, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** Yields each index in the array. */ + keys(): IterableIterator; + + /** + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ + lastIndexOf(searchElement: bigint, fromIndex?: number): number; + + /** The length of the array. */ + readonly length: number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the + * callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array. The return value of + * the callback function is the accumulated result, and is provided as an argument in the next + * call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the + * callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an + * argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + + /** Reverses the elements in the array. */ + reverse(): this; + + /** + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ + set(array: ArrayLike, offset?: number): void; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ + slice(start?: number, end?: number): BigUint64Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + + /** + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ + sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; + + /** + * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigUint64Array; + + /** Converts the array to a string by using the current locale. */ + toLocaleString(): string; + + /** Returns a string representation of the array. */ + toString(): string; + + /** Yields each value in the array. */ + values(): IterableIterator; + + [Symbol.iterator](): IterableIterator; + + readonly [Symbol.toStringTag]: "BigUint64Array"; + + [index: number]: bigint; +} + +interface BigUint64ArrayConstructor { + readonly prototype: BigUint64Array; + new(length?: number): BigUint64Array; + new(array: Iterable): BigUint64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + + /** The size in bytes of each element in the array. */ + readonly BYTES_PER_ELEMENT: number; + + /** + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ + of(...items: bigint[]): BigUint64Array; + + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike): BigUint64Array; + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; +} + +declare const BigUint64Array: BigUint64ArrayConstructor; + +interface DataView { + /** + * Gets the BigInt64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Gets the BigUint64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ + getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; + + /** + * Stores a BigInt64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; + + /** + * Stores a BigUint64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ + setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; +} \ No newline at end of file diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts index 970e1b32b3e..45d7e1d96c9 100644 --- a/src/lib/esnext.d.ts +++ b/src/lib/esnext.d.ts @@ -1,5 +1,6 @@ /// /// /// +/// /// /// diff --git a/src/lib/libs.json b/src/lib/libs.json index 1f2079e33a3..3077181af6e 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -34,6 +34,7 @@ "es2018.intl", "esnext.asynciterable", "esnext.array", + "esnext.bigint", "esnext.symbol", "esnext.intl", // Default libraries diff --git a/src/testRunner/unittests/commandLineParsing.ts b/src/testRunner/unittests/commandLineParsing.ts index 7ac9504f1f8..7e2090eb3bd 100644 --- a/src/testRunner/unittests/commandLineParsing.ts +++ b/src/testRunner/unittests/commandLineParsing.ts @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, diff --git a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts index 4f6f479e2bd..7b8af54f930 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts @@ -295,7 +295,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -326,7 +326,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -357,7 +357,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] @@ -388,7 +388,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] From ece27eb1774fbe53920b65a880262cac986550b8 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 12:48:07 -0700 Subject: [PATCH 209/262] Utilities for PseudoBigInt --- src/compiler/types.ts | 6 ++ src/compiler/utilities.ts | 84 +++++++++++++++++++ src/testRunner/tsconfig.json | 1 + src/testRunner/unittests/parsePseudoBigInt.ts | 71 ++++++++++++++++ .../reference/api/tsserverlibrary.d.ts | 5 ++ tests/baselines/reference/api/typescript.d.ts | 5 ++ 6 files changed, 172 insertions(+) create mode 100644 src/testRunner/unittests/parsePseudoBigInt.ts diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a39d098443c..4a25a9f9eef 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5761,4 +5761,10 @@ namespace ts { readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; } + + /** Represents a bigint literal value without requiring bigint support */ + export interface PseudoBigInt { + negative: boolean; + base10Value: string; + } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5d9a77c2a98..34d80992153 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -8427,4 +8427,88 @@ namespace ts { return got; } } + + // TODO: remove once tslint allows tsconfig.json to include lib "esnext.bigint" + /* @internal */ + declare const BigInt: ((value: string) => number) | undefined; + + /** + * Converts a bigint literal string, e.g. `0x1234n`, + * to its decimal string representation, e.g. `4660`. + */ + export function parsePseudoBigInt(stringValue: string): string { + // Use native BigInt if available + if (typeof BigInt !== "undefined") { + return "" + BigInt(stringValue.slice(0, -1)); // omit trailing "n" + } + + let log2Base: number; + switch (stringValue.charCodeAt(1)) { // "x" in "0x123" + case CharacterCodes.b: + case CharacterCodes.B: // 0b or 0B + log2Base = 1; + break; + case CharacterCodes.o: + case CharacterCodes.O: // 0o or 0O + log2Base = 3; + break; + case CharacterCodes.x: + case CharacterCodes.X: // 0x or 0X + log2Base = 4; + break; + default: // already in decimal; omit trailing "n" + const nIndex = stringValue.length - 1; + // Skip leading 0s + let nonZeroStart = 0; + while (stringValue.charCodeAt(nonZeroStart) === CharacterCodes._0) { + nonZeroStart++; + } + return stringValue.slice(nonZeroStart, nIndex) || "0"; + } + + // Omit leading "0b", "0o", or "0x", and trailing "n" + const startIndex = 2, endIndex = stringValue.length - 1; + const bitsNeeded = (endIndex - startIndex) * log2Base; + // Stores the value specified by the string as a LE array of 16-bit integers + // using Uint16 instead of Uint32 so combining steps can use bitwise operators + const segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0)); + // Add the digits, one at a time + for (let i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) { + const segment = bitOffset >>> 4; + const digitChar = stringValue.charCodeAt(i); + // Find character range: 0-9 < A-F < a-f + const digit = digitChar <= CharacterCodes._9 + ? digitChar - CharacterCodes._0 + : 10 + digitChar - + (digitChar <= CharacterCodes.F ? CharacterCodes.A : CharacterCodes.a); + const shiftedDigit = digit << (bitOffset & 15); + segments[segment] |= shiftedDigit; + const residual = shiftedDigit >>> 16; + if (residual) segments[segment + 1] |= residual; // overflows segment + } + // Repeatedly divide segments by 10 and add remainder to base10Value + let base10Value = ""; + let firstNonzeroSegment = segments.length - 1; + let segmentsRemaining = true; + while (segmentsRemaining) { + let mod10 = 0; + segmentsRemaining = false; + for (let segment = firstNonzeroSegment; segment >= 0; segment--) { + const newSegment = mod10 << 16 | segments[segment]; + const segmentValue = (newSegment / 10) | 0; + segments[segment] = segmentValue; + mod10 = newSegment - segmentValue * 10; + if (segmentValue && !segmentsRemaining) { + firstNonzeroSegment = segment; + segmentsRemaining = true; + } + } + base10Value = mod10 + base10Value; + } + return base10Value; + } + + export function pseudoBigIntToString({negative, base10Value}: PseudoBigInt): string { + return (negative && base10Value !== "0" ? "-" : "") + base10Value; + } } diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index af25aba408d..32772ed311b 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -65,6 +65,7 @@ "unittests/matchFiles.ts", "unittests/moduleResolution.ts", "unittests/organizeImports.ts", + "unittests/parsePseudoBigInt.ts", "unittests/paths.ts", "unittests/printer.ts", "unittests/programMissingFiles.ts", diff --git a/src/testRunner/unittests/parsePseudoBigInt.ts b/src/testRunner/unittests/parsePseudoBigInt.ts new file mode 100644 index 00000000000..0ffbee6345e --- /dev/null +++ b/src/testRunner/unittests/parsePseudoBigInt.ts @@ -0,0 +1,71 @@ +namespace ts { + describe("BigInt literal base conversions", () => { + describe("parsePseudoBigInt", () => { + const testNumbers: number[] = []; + for (let i = 0; i < 1e3; i++) testNumbers.push(i); + for (let bits = 0; bits <= 52; bits++) { + testNumbers.push(2 ** bits, 2 ** bits - 1); + } + it("can strip base-10 strings", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + assert.equal( + parsePseudoBigInt("0".repeat(leadingZeros) + testNumber + "n"), + String(testNumber) + ); + } + } + }); + it("can parse binary literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const binary = "0".repeat(leadingZeros) + testNumber.toString(2) + "n"; + for (const prefix of ["0b", "0B"]) { + assert.equal(parsePseudoBigInt(prefix + binary), String(testNumber)); + } + } + } + }); + it("can parse octal literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const octal = "0".repeat(leadingZeros) + testNumber.toString(8) + "n"; + for (const prefix of ["0o", "0O"]) { + assert.equal(parsePseudoBigInt(prefix + octal), String(testNumber)); + } + } + } + }); + it("can parse hex literals", () => { + for (const testNumber of testNumbers) { + for (let leadingZeros = 0; leadingZeros < 10; leadingZeros++) { + const hex = "0".repeat(leadingZeros) + testNumber.toString(16) + "n"; + for (const prefix of ["0x", "0X"]) { + for (const hexCase of [hex.toLowerCase(), hex.toUpperCase()]) { + assert.equal(parsePseudoBigInt(prefix + hexCase), String(testNumber)); + } + } + } + } + }); + it("can parse large literals", () => { + assert.equal( + parsePseudoBigInt("123456789012345678901234567890n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0b1100011101110100100001111111101101100001101110011111000001110111001001110001111110000101011010010n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0o143564417755415637016711617605322n"), + "123456789012345678901234567890" + ); + assert.equal( + parsePseudoBigInt("0x18ee90ff6c373e0ee4e3f0ad2n"), + "123456789012345678901234567890" + ); + }); + }); + }); +} \ No newline at end of file diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index b5ef0cac750..9f447a12c35 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -3013,6 +3013,11 @@ declare namespace ts { readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 8f047351750..d2ec3ab1d12 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -3013,6 +3013,11 @@ declare namespace ts { readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; } + /** Represents a bigint literal value without requiring bigint support */ + interface PseudoBigInt { + negative: boolean; + base10Value: string; + } } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; From 3e10dedbce75ec93a5c6a5241ef1db254ac3f758 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 13:28:51 -0700 Subject: [PATCH 210/262] Add diagnostic messages for bigints --- src/compiler/checker.ts | 8 +- src/compiler/diagnosticMessages.json | 18 +- src/testRunner/unittests/tscWatchMode.ts | 2 +- .../YieldStarExpression1_es6.errors.txt | 4 +- .../arithmeticOnInvalidTypes.errors.txt | 24 +- .../arithmeticOnInvalidTypes2.errors.txt | 24 +- ...eticOperatorWithInvalidOperands.errors.txt | 2216 ++++++++--------- ...WithNullValueAndInvalidOperands.errors.txt | 480 ++-- ...hmeticOperatorWithTypeParameter.errors.txt | 720 +++--- ...ndefinedValueAndInvalidOperands.errors.txt | 480 ++-- ...wiseCompoundAssignmentOperators.errors.txt | 20 +- ...icAssignmentWithInvalidOperands.errors.txt | 240 +- .../compoundAssignmentLHSIsValue.errors.txt | 64 +- ...onAssignmentLHSCannotBeAssigned.errors.txt | 240 +- ...onentiationAssignmentLHSIsValue.errors.txt | 64 +- ...torWithIncompleteTypeAnnotation.errors.txt | 4 +- ...thAnyOtherTypeInvalidOperations.errors.txt | 56 +- .../decrementOperatorWithEnumType.errors.txt | 4 +- ...WithNumberTypeInvalidOperations.errors.txt | 32 +- ...ratorWithUnsupportedBooleanType.errors.txt | 116 +- ...eratorWithUnsupportedStringType.errors.txt | 156 +- .../duplicateLocalVariable1.errors.txt | 4 +- .../duplicateLocalVariable2.errors.txt | 4 +- ...nTemplateStringWithSyntaxError1.errors.txt | 60 +- ...nTemplateStringWithSyntaxError2.errors.txt | 60 +- ...nTemplateStringWithSyntaxError3.errors.txt | 60 +- ...onentiationOperatorSyntaxError2.errors.txt | 112 +- ...tionOperatorWithInvalidOperands.errors.txt | 224 +- ...idSimpleUnaryExpressionOperands.errors.txt | 112 +- ...WithNullValueAndInvalidOperands.errors.txt | 48 +- ...eratorWithTemplateStringInvalid.errors.txt | 48 +- ...torWithTemplateStringInvalidES6.errors.txt | 48 +- ...iationOperatorWithTypeParameter.errors.txt | 72 +- ...ndefinedValueAndInvalidOperands.errors.txt | 48 +- tests/baselines/reference/expr.errors.txt | 216 +- .../for-inStatementsArrayErrors.errors.txt | 4 +- .../incrementOnTypeParameter.errors.txt | 8 +- ...thAnyOtherTypeInvalidOperations.errors.txt | 60 +- ...orWithEnumTypeInvalidOperations.errors.txt | 8 +- ...WithNumberTypeInvalidOperations.errors.txt | 32 +- ...ratorWithUnsupportedBooleanType.errors.txt | 116 +- ...eratorWithUnsupportedStringType.errors.txt | 156 +- .../reference/interfaceNaming1.errors.txt | 4 +- .../reference/jsdocInTypeScript.errors.txt | 4 +- .../objectLitIndexerContextualType.errors.txt | 24 +- ...ularExpressionMixedWithComments.errors.txt | 16 +- .../parserUnaryExpression2.errors.txt | 4 +- .../parserUnaryExpression3.errors.txt | 4 +- .../parserUnaryExpression4.errors.txt | 4 +- .../reference/shebangError.errors.txt | 4 +- ...eralTypesWithVariousOperators02.errors.txt | 16 +- .../reference/symbolType10.errors.txt | 32 +- .../reference/symbolType12.errors.txt | 120 +- .../reference/symbolType3.errors.txt | 8 +- .../reference/symbolType4.errors.txt | 8 +- .../reference/symbolType5.errors.txt | 32 +- .../reference/symbolType6.errors.txt | 16 +- .../reference/symbolType7.errors.txt | 36 +- ...tringBinaryOperationsES6Invalid.errors.txt | 384 +-- ...teStringBinaryOperationsInvalid.errors.txt | 384 +-- .../templateStringInDivision.errors.txt | 4 +- .../templateStringInModulo.errors.txt | 4 +- .../templateStringInModuloES6.errors.txt | 4 +- .../templateStringInMultiplication.errors.txt | 4 +- ...mplateStringInMultiplicationES6.errors.txt | 4 +- .../tsxAttributeInvalidNames.errors.txt | 8 +- .../reference/typeGuardsDefeat.errors.txt | 16 +- 67 files changed, 3814 insertions(+), 3802 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e17b38ff736..e50239e622f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -21454,7 +21454,7 @@ namespace ts { case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); @@ -21472,7 +21472,7 @@ namespace ts { const ok = checkArithmeticOperandType( node.operand, checkNonNullType(operandType, node.operand), - Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); @@ -21872,8 +21872,8 @@ namespace ts { } else { // otherwise just check each operand separately and report errors as normal - const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); + const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); if (leftOk && rightOk) { checkAssignmentOperator(numberType); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 6f22515dea7..a1cab6bfaff 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1011,6 +1011,10 @@ "category": "Message", "code": 1350 }, + "Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning.": { + "category": "Error", + "code": 1351 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1236,7 +1240,7 @@ "category": "Error", "code": 2355 }, - "An arithmetic operand must be of type 'any', 'number' or an enum type.": { + "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2356 }, @@ -1260,11 +1264,11 @@ "category": "Error", "code": 2361 }, - "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2362 }, - "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.": { + "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.": { "category": "Error", "code": 2363 }, @@ -2497,6 +2501,10 @@ "category": "Error", "code": 2735 }, + "Operator '{0}' cannot be applied to type '{1}'.": { + "category": "Error", + "code": 2736 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -3905,6 +3913,10 @@ "category": "Error", "code": 6370 }, + "Enables experimental support for ESNext BigInt expressions.": { + "category": "Message", + "code": 6371 + }, "The expected type comes from property '{0}' which is declared here on type '{1}'": { "category": "Message", diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index 3523db7544f..810a70054d1 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1298,7 +1298,7 @@ export default test;`; ]); changeParameterType("y", "string", [ getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf("5"), 1, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1, "5", "string"), - getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type) + getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type) ]); function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray) { diff --git a/tests/baselines/reference/YieldStarExpression1_es6.errors.txt b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt index 9ba5e44f9aa..265013d6bad 100644 --- a/tests/baselines/reference/YieldStarExpression1_es6.errors.txt +++ b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,1): error TS2304: Cannot find name 'yield'. -tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): e ~~~~~ !!! error TS2304: Cannot find name 'yield'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt b/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt index 2c042af6f86..ac526ccc5a9 100644 --- a/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt +++ b/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/arithmeticOnInvalidTypes.ts(3,9): error TS2365: Operator '+' cannot be applied to types 'Number' and 'Number'. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/arithmeticOnInvalidTypes.ts (7 errors) ==== @@ -15,16 +15,16 @@ tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right- !!! error TS2365: Operator '+' cannot be applied to types 'Number' and 'Number'. var z2 = x - y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z3 = x * y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z4 = x / y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt b/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt index d5b74e5abc7..f4dd0cd7852 100644 --- a/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt +++ b/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/arithmeticOnInvalidTypes2.ts(2,14): error TS2365: Operator '+' cannot be applied to types 'T' and 'T'. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/arithmeticOnInvalidTypes2.ts (7 errors) ==== @@ -14,18 +14,18 @@ tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right !!! error TS2365: Operator '+' cannot be applied to types 'T' and 'T'. var z2 = a - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z3 = a * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z4 = a / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. return a; }; \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt index 0d376912b8d..cfcd2cded79 100644 --- a/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt @@ -1,560 +1,560 @@ -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(15,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(17,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(18,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(19,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(29,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(31,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(32,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(33,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(57,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(59,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(60,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(61,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(72,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(74,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(75,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(76,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(78,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(80,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(86,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(88,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(89,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(90,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(92,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(94,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(101,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(114,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(116,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(117,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(118,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(121,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(129,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(131,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(132,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(133,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(135,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(137,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(143,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(145,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(146,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(147,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(156,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(163,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(165,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(171,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(173,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(174,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(175,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(178,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(180,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(181,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(182,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(186,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(188,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(189,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(190,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(192,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(194,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(200,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(202,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(203,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(204,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(206,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(208,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(213,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(215,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(220,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(222,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(228,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(230,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(231,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(232,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(235,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(237,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(238,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(239,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(243,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(245,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(246,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(247,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(249,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(251,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(257,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(259,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(260,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(261,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(263,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(265,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(270,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(272,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(277,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(279,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(285,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(287,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(288,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(289,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(292,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(294,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(295,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(296,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(300,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(302,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(303,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(304,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(306,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(308,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(314,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(316,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(317,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(318,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(320,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(322,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(327,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(329,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(334,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(336,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(342,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(344,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(345,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(346,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(349,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(351,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(352,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(353,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(357,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(359,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(360,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(361,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(363,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(365,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(371,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(373,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(374,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(375,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(377,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(379,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(384,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(386,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(391,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(393,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(399,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(401,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(402,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(403,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(406,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(408,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(409,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(410,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(414,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(416,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(417,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(418,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(420,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(15,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(17,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(18,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(19,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(29,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(31,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(32,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(33,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(57,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(59,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(60,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(61,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(72,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(74,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(75,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(76,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(78,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(80,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(86,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(88,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(89,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(90,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(92,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(94,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(101,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(114,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(116,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(117,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(118,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(121,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(129,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(131,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(132,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(133,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(135,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(137,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(143,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(145,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(146,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(147,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(156,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(163,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(165,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(171,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(173,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(174,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(175,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(178,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(180,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(181,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(182,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(186,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(188,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(189,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(190,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(192,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(194,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(200,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(202,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(203,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(204,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(206,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(208,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(213,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(215,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(220,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(222,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(228,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(230,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(231,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(232,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(235,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(237,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(238,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(239,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(243,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(245,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(246,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(247,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(249,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(251,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(257,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(259,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(260,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(261,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(263,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(265,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(270,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(272,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(277,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(279,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(285,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(287,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(288,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(289,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(292,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(294,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(295,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(296,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(300,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(302,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(303,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(304,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(306,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(308,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(314,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(316,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(317,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(318,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(320,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(322,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(327,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(329,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(334,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(336,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(342,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(344,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(345,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(346,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(349,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(351,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(352,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(353,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(357,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(359,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(360,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(361,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(363,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(365,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(371,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(373,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(374,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(375,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(377,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(379,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(384,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(386,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(391,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(393,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(399,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(401,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(402,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(403,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(406,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(408,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(409,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(410,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(414,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(416,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(417,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(418,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(420,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(421,12): error TS2447: The '&' operator is not allowed for boolean types. Consider using '&&' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(422,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(428,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(430,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(431,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(432,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(434,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(436,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(441,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(443,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(448,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(450,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(456,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(458,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(459,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(460,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(463,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(465,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(466,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(467,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(471,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(473,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(474,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(475,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(477,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(422,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(428,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(430,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(431,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(432,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(434,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(436,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(441,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(443,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(448,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(450,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(456,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(458,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(459,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(460,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(463,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(465,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(466,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(467,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(471,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(473,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(474,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(475,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(477,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(478,12): error TS2447: The '^' operator is not allowed for boolean types. Consider using '!==' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(479,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(485,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(487,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(488,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(489,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(491,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(493,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(498,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(500,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(505,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(507,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(513,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(515,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(516,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(517,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(520,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(522,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(523,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(524,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(528,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(530,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(531,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(532,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(534,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(479,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(485,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(487,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(488,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(489,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(491,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(493,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(498,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(500,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(505,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(507,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(513,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(515,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(516,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(517,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(520,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(522,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(523,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(524,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(528,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(530,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(531,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(532,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(534,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(535,13): error TS2447: The '|' operator is not allowed for boolean types. Consider using '||' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(536,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(542,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(544,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(545,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(546,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(548,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(550,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(555,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(557,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(562,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(564,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(570,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(572,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(573,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(574,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(577,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(579,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(580,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(581,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(536,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(542,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(544,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(545,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(546,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(548,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(550,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(555,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(557,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(562,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(564,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(570,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(572,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(573,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(574,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(577,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(579,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(580,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(581,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts (557 errors) ==== @@ -574,1682 +574,1682 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti var r1a1 = a * a; //ok var r1a2 = a * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = a * c; //ok var r1a4 = a * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a5 = a * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a6 = a * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b2 = b * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b3 = b * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b4 = b * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b5 = b * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b6 = b * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c * a; //ok var r1c2 = c * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = c * c; //ok var r1c4 = c * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c5 = c * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c6 = c * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d2 = d * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d3 = d * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d4 = d * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d5 = d * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d6 = d * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e2 = e * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e3 = e * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e4 = e * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e5 = e * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e6 = e * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = f * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f2 = f * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f3 = f * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f4 = f * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f5 = f * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f6 = f * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g1 = E.a * a; //ok var r1g2 = E.a * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g3 = E.a * c; //ok var r1g4 = E.a * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g5 = E.a * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g6 = E.a * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h1 = a * E.b; //ok var r1h2 = b * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h3 = c * E.b; //ok var r1h4 = d * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h5 = e * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h6 = f * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator / var r2a1 = a / a; //ok var r2a2 = a / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = a / c; //ok var r2a4 = a / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a5 = a / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a6 = a / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = b / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b2 = b / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b3 = b / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b4 = b / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b5 = b / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b6 = b / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c1 = c / a; //ok var r2c2 = c / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = c / c; //ok var r2c4 = c / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c5 = c / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c6 = c / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = d / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d2 = d / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d3 = d / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d4 = d / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d5 = d / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d6 = d / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e1 = e / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e2 = e / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e3 = e / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e4 = e / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e5 = e / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e6 = e / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f1 = f / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f2 = f / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f3 = f / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f4 = f / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f5 = f / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f6 = f / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g1 = E.a / a; //ok var r2g2 = E.a / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g3 = E.a / c; //ok var r2g4 = E.a / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g5 = E.a / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g6 = E.a / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h1 = a / E.b; //ok var r2h2 = b / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h3 = c / E.b; //ok var r2h4 = d / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h5 = e / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h6 = f / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator % var r3a1 = a % a; //ok var r3a2 = a % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = a % c; //ok var r3a4 = a % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a5 = a % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a6 = a % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = b % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b2 = b % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b3 = b % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b4 = b % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b5 = b % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b6 = b % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c1 = c % a; //ok var r3c2 = c % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = c % c; //ok var r3c4 = c % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c5 = c % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c6 = c % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = d % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d2 = d % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d3 = d % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d4 = d % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d5 = d % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d6 = d % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e1 = e % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e2 = e % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e3 = e % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e4 = e % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e5 = e % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e6 = e % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f1 = f % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f2 = f % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f3 = f % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f4 = f % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f5 = f % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f6 = f % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g1 = E.a % a; //ok var r3g2 = E.a % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g3 = E.a % c; //ok var r3g4 = E.a % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g5 = E.a % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g6 = E.a % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h1 = a % E.b; //ok var r3h2 = b % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h3 = c % E.b; //ok var r3h4 = d % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h5 = e % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h6 = f % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator - var r4a1 = a - a; //ok var r4a2 = a - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = a - c; //ok var r4a4 = a - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a5 = a - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a6 = a - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = b - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b2 = b - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b3 = b - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b4 = b - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b5 = b - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b6 = b - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c1 = c - a; //ok var r4c2 = c - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = c - c; //ok var r4c4 = c - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c5 = c - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c6 = c - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = d - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d2 = d - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d3 = d - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d4 = d - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d5 = d - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d6 = d - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e1 = e - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e2 = e - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e3 = e - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e4 = e - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e5 = e - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e6 = e - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f1 = f - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f2 = f - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f3 = f - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f4 = f - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f5 = f - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f6 = f - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g1 = E.a - a; //ok var r4g2 = E.a - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g3 = E.a - c; //ok var r4g4 = E.a - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g5 = E.a - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g6 = E.a - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h1 = a - E.b; //ok var r4h2 = b - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h3 = c - E.b; //ok var r4h4 = d - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h5 = e - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h6 = f - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator << var r5a1 = a << a; //ok var r5a2 = a << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = a << c; //ok var r5a4 = a << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a5 = a << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a6 = a << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = b << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b2 = b << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b3 = b << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b4 = b << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b5 = b << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b6 = b << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c1 = c << a; //ok var r5c2 = c << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = c << c; //ok var r5c4 = c << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c5 = c << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c6 = c << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = d << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d2 = d << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d3 = d << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d4 = d << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d5 = d << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d6 = d << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e1 = e << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e2 = e << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e3 = e << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e4 = e << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e5 = e << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e6 = e << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f1 = f << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f2 = f << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f3 = f << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f4 = f << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f5 = f << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f6 = f << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g1 = E.a << a; //ok var r5g2 = E.a << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g3 = E.a << c; //ok var r5g4 = E.a << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g5 = E.a << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g6 = E.a << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h1 = a << E.b; //ok var r5h2 = b << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h3 = c << E.b; //ok var r5h4 = d << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h5 = e << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h6 = f << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator >> var r6a1 = a >> a; //ok var r6a2 = a >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = a >> c; //ok var r6a4 = a >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a5 = a >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a6 = a >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = b >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b2 = b >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b3 = b >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b4 = b >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b5 = b >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b6 = b >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c1 = c >> a; //ok var r6c2 = c >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = c >> c; //ok var r6c4 = c >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c5 = c >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c6 = c >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = d >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d2 = d >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d3 = d >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d4 = d >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d5 = d >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d6 = d >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e1 = e >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e2 = e >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e3 = e >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e4 = e >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e5 = e >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e6 = e >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f1 = f >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f2 = f >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f3 = f >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f4 = f >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f5 = f >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f6 = f >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g1 = E.a >> a; //ok var r6g2 = E.a >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g3 = E.a >> c; //ok var r6g4 = E.a >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g5 = E.a >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g6 = E.a >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h1 = a >> E.b; //ok var r6h2 = b >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h3 = c >> E.b; //ok var r6h4 = d >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h5 = e >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h6 = f >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator >>> var r7a1 = a >>> a; //ok var r7a2 = a >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = a >>> c; //ok var r7a4 = a >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a5 = a >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a6 = a >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = b >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b2 = b >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b3 = b >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b4 = b >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b5 = b >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b6 = b >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c1 = c >>> a; //ok var r7c2 = c >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = c >>> c; //ok var r7c4 = c >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c5 = c >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c6 = c >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = d >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d2 = d >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d3 = d >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d4 = d >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d5 = d >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d6 = d >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e1 = e >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e2 = e >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e3 = e >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e4 = e >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e5 = e >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e6 = e >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f1 = f >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f2 = f >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f3 = f >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f4 = f >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f5 = f >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f6 = f >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g1 = E.a >>> a; //ok var r7g2 = E.a >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g3 = E.a >>> c; //ok var r7g4 = E.a >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g5 = E.a >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g6 = E.a >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h1 = a >>> E.b; //ok var r7h2 = b >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h3 = c >>> E.b; //ok var r7h4 = d >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h5 = e >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h6 = f >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator & var r8a1 = a & a; //ok var r8a2 = a & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = a & c; //ok var r8a4 = a & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a5 = a & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a6 = a & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = b & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b2 = b & b; ~~~~~ !!! error TS2447: The '&' operator is not allowed for boolean types. Consider using '&&' instead. var r8b3 = b & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b4 = b & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b5 = b & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b6 = b & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c1 = c & a; //ok var r8c2 = c & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = c & c; //ok var r8c4 = c & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c5 = c & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c6 = c & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = d & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d2 = d & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d3 = d & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d4 = d & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d5 = d & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d6 = d & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e1 = e & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e2 = e & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e3 = e & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e4 = e & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e5 = e & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e6 = e & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f1 = f & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f2 = f & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f3 = f & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f4 = f & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f5 = f & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f6 = f & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g1 = E.a & a; //ok var r8g2 = E.a & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g3 = E.a & c; //ok var r8g4 = E.a & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g5 = E.a & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g6 = E.a & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h1 = a & E.b; //ok var r8h2 = b & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h3 = c & E.b; //ok var r8h4 = d & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h5 = e & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h6 = f & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator ^ var r9a1 = a ^ a; //ok var r9a2 = a ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = a ^ c; //ok var r9a4 = a ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a5 = a ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a6 = a ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = b ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b2 = b ^ b; ~~~~~ !!! error TS2447: The '^' operator is not allowed for boolean types. Consider using '!==' instead. var r9b3 = b ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b4 = b ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b5 = b ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b6 = b ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c1 = c ^ a; //ok var r9c2 = c ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = c ^ c; //ok var r9c4 = c ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c5 = c ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c6 = c ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = d ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d2 = d ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d3 = d ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d4 = d ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d5 = d ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d6 = d ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e1 = e ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e2 = e ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e3 = e ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e4 = e ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e5 = e ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e6 = e ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f1 = f ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f2 = f ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f3 = f ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f4 = f ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f5 = f ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f6 = f ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g1 = E.a ^ a; //ok var r9g2 = E.a ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g3 = E.a ^ c; //ok var r9g4 = E.a ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g5 = E.a ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g6 = E.a ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h1 = a ^ E.b; //ok var r9h2 = b ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h3 = c ^ E.b; //ok var r9h4 = d ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h5 = e ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h6 = f ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator | var r10a1 = a | a; //ok var r10a2 = a | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = a | c; //ok var r10a4 = a | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a5 = a | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a6 = a | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = b | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b2 = b | b; ~~~~~ !!! error TS2447: The '|' operator is not allowed for boolean types. Consider using '||' instead. var r10b3 = b | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b4 = b | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b5 = b | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b6 = b | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c1 = c | a; //ok var r10c2 = c | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = c | c; //ok var r10c4 = c | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c5 = c | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c6 = c | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = d | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d2 = d | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d3 = d | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d4 = d | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d5 = d | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d6 = d | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e1 = e | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e2 = e | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e3 = e | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e4 = e | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e5 = e | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e6 = e | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f1 = f | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f2 = f | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f3 = f | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f4 = f | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f5 = f | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f6 = f | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g1 = E.a | a; //ok var r10g2 = E.a | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g3 = E.a | c; //ok var r10g4 = E.a | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g5 = E.a | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g6 = E.a | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h1 = a | E.b; //ok var r10h2 = b | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h3 = c | E.b; //ok var r10h4 = d | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h5 = e | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h6 = f | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt index 16a0264a805..e352fbf9060 100644 --- a/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt @@ -1,242 +1,242 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,21): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,19): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,18): error TS2531: Object is possibly 'null'. @@ -253,31 +253,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = null * b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = null * c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b2 = b * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b3 = c * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -285,31 +285,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = null * ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = null * {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true * null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d2 = '' * null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d3 = {} * null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -318,31 +318,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = null / b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = null / c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = a / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2b2 = b / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2b3 = c / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -350,31 +350,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = null / ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = null / {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = true / null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2d2 = '' / null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2d3 = {} / null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -383,31 +383,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a2 = null % b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = null % c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = a % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3b2 = b % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3b3 = c % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -415,31 +415,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c2 = null % ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = null % {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = true % null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3d2 = '' % null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3d3 = {} % null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -448,31 +448,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a2 = null - b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = null - c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = a - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4b2 = b - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4b3 = c - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -480,31 +480,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c2 = null - ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = null - {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = true - null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4d2 = '' - null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4d3 = {} - null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -513,31 +513,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a2 = null << b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = null << c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = a << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5b2 = b << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5b3 = c << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -545,31 +545,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c2 = null << ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = null << {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = true << null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5d2 = '' << null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5d3 = {} << null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -578,31 +578,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a2 = null >> b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = null >> c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = a >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6b2 = b >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6b3 = c >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -610,31 +610,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c2 = null >> ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = null >> {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = true >> null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6d2 = '' >> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6d3 = {} >> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -643,31 +643,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a2 = null >>> b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = null >>> c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = a >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7b2 = b >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7b3 = c >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -675,31 +675,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c2 = null >>> ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = null >>> {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = true >>> null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7d2 = '' >>> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7d3 = {} >>> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -708,31 +708,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a2 = null & b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = null & c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = a & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8b2 = b & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8b3 = c & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -740,31 +740,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c2 = null & ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = null & {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = true & null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8d2 = '' & null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8d3 = {} & null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -773,31 +773,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a2 = null ^ b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = null ^ c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = a ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9b2 = b ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9b3 = c ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -805,31 +805,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c2 = null ^ ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = null ^ {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = true ^ null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9d2 = '' ^ null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9d3 = {} ^ null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -838,31 +838,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a2 = null | b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = null | c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = a | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10b2 = b | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10b3 = c | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -870,30 +870,30 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c2 = null | ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = null | {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = true | null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10d2 = '' | null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10d3 = {} | null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt b/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt index a1de1f0c795..fc939a5216e 100644 --- a/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt @@ -1,183 +1,183 @@ -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(12,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(14,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(15,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(16,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(20,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(21,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(22,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(23,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(24,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(25,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(26,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(27,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(28,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(29,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(53,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(54,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(55,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(56,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(57,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(58,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(59,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(60,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(61,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(62,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(64,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(65,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(66,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(67,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(68,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(69,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(70,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(71,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(72,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(73,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(12,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(14,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(15,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(16,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(20,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(21,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(22,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(23,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(24,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(25,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(26,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(27,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(28,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(29,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(53,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(54,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(55,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(56,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(57,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(58,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(59,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(60,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(61,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(62,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(64,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(65,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(66,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(67,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(68,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(69,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(70,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(71,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(72,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(73,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts (180 errors) ==== @@ -191,482 +191,482 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti var r1a1 = a * t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = a / t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = a % t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a4 = a - t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a5 = a << t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a6 = a >> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a7 = a >>> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a8 = a & t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a9 = a ^ t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a10 = a | t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a1 = t * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = t / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = t % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a4 = t - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a5 = t << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a6 = t >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a7 = t >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a8 = t & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a9 = t ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a10 = t | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b2 = b / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b3 = b % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b4 = b - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b5 = b << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b6 = b >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b7 = b >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b8 = b & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b9 = b ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b10 = b | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = t * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b2 = t / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b3 = t % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b4 = t - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b5 = t << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b6 = t >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b7 = t >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b8 = t & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b9 = t ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b10 = t | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c * t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = c / t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = c % t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c4 = c - t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c5 = c << t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c6 = c >> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c7 = c >>> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c8 = c & t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c9 = c ^ t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c10 = c | t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c1 = t * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = t / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = t % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c4 = t - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c5 = t << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c6 = t >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c7 = t >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c8 = t & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c9 = t ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c10 = t | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d2 = d / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d3 = d % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d4 = d - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d5 = d << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d6 = d >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d7 = d >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d8 = d & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d9 = d ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d10 = d | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = t * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d2 = t / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d3 = t % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d4 = t - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d5 = t << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d6 = t >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d7 = t >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d8 = t & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d9 = t ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d10 = t | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e2 = e / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e3 = e % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e4 = e - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e5 = e << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e6 = e >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e7 = e >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e8 = e & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e9 = e ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e10 = e | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e1 = t * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e2 = t / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e3 = t % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e4 = t - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e5 = t << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e6 = t >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e7 = t >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e8 = t & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e9 = t ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e10 = t | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = t * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f2 = t / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f3 = t % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f4 = t - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f5 = t << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f6 = t >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f7 = t >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f8 = t & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f9 = t ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f10 = t | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt index 8a9d014f2c2..0482a511077 100644 --- a/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt @@ -1,242 +1,242 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,21): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,19): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,18): error TS2532: Object is possibly 'undefined'. @@ -253,31 +253,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = undefined * b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = undefined * c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b2 = b * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b3 = c * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -285,31 +285,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = undefined * ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = undefined * {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true * undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d2 = '' * undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d3 = {} * undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -318,31 +318,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = undefined / b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = undefined / c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = a / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2b2 = b / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2b3 = c / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -350,31 +350,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = undefined / ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = undefined / {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = true / undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2d2 = '' / undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2d3 = {} / undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -383,31 +383,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a2 = undefined % b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = undefined % c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = a % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3b2 = b % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3b3 = c % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -415,31 +415,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c2 = undefined % ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = undefined % {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = true % undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3d2 = '' % undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3d3 = {} % undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -448,31 +448,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a2 = undefined - b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = undefined - c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = a - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4b2 = b - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4b3 = c - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -480,31 +480,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c2 = undefined - ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = undefined - {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = true - undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4d2 = '' - undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4d3 = {} - undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -513,31 +513,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a2 = undefined << b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = undefined << c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = a << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5b2 = b << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5b3 = c << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -545,31 +545,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c2 = undefined << ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = undefined << {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = true << undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5d2 = '' << undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5d3 = {} << undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -578,31 +578,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a2 = undefined >> b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = undefined >> c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = a >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6b2 = b >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6b3 = c >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -610,31 +610,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c2 = undefined >> ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = undefined >> {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = true >> undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6d2 = '' >> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6d3 = {} >> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -643,31 +643,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a2 = undefined >>> b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = undefined >>> c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = a >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7b2 = b >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7b3 = c >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -675,31 +675,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c2 = undefined >>> ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = undefined >>> {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = true >>> undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7d2 = '' >>> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7d3 = {} >>> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -708,31 +708,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a2 = undefined & b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = undefined & c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = a & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8b2 = b & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8b3 = c & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -740,31 +740,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c2 = undefined & ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = undefined & {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = true & undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8d2 = '' & undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8d3 = {} & undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -773,31 +773,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a2 = undefined ^ b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = undefined ^ c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = a ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9b2 = b ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9b3 = c ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -805,31 +805,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c2 = undefined ^ ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = undefined ^ {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = true ^ undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9d2 = '' ^ undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9d3 = {} ^ undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -838,31 +838,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a2 = undefined | b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = undefined | c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = a | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10b2 = b | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10b3 = c | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -870,30 +870,30 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c2 = undefined | ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = undefined | {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = true | undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10d2 = '' | undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10d3 = {} | undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. \ No newline at end of file diff --git a/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt b/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt index ae7a8fdce0a..221ac478cd6 100644 --- a/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt +++ b/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt @@ -1,11 +1,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(3,1): error TS2447: The '^=' operator is not allowed for boolean types. Consider using '!==' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(9,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(9,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(14,1): error TS2447: The '&=' operator is not allowed for boolean types. Consider using '&&' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(20,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(20,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(24,1): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts (8 errors) ==== @@ -19,11 +19,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: b = 1; a ^= b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a = true; b ^= a; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. b = 1; var c = false; @@ -36,11 +36,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: d = 2; c &= d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. c = false; d &= c; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = true; var f = 0; @@ -52,7 +52,7 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: f = 0; e |= f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e = true; f |= f; diff --git a/tests/baselines/reference/compoundArithmeticAssignmentWithInvalidOperands.errors.txt b/tests/baselines/reference/compoundArithmeticAssignmentWithInvalidOperands.errors.txt index 7429445b422..dcf16a9b7cb 100644 --- a/tests/baselines/reference/compoundArithmeticAssignmentWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/compoundArithmeticAssignmentWithInvalidOperands.errors.txt @@ -1,71 +1,71 @@ -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(8,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(9,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(9,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(8,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(9,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(9,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(14,7): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(15,7): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(19,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(20,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(22,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(24,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(19,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(20,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(22,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(24,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(25,7): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(26,7): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(30,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(31,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(32,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(33,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(33,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(34,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(35,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(35,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(30,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(31,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(32,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(33,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(33,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(34,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(35,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(35,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(36,7): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(37,7): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(41,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(41,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(42,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(42,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(43,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(44,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(44,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(45,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(46,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(47,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(41,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(41,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(42,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(42,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(43,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(44,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(44,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(45,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(46,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(47,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(47,7): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(48,7): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(51,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(52,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(53,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(54,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(57,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(58,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(59,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(60,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(51,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(52,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(53,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(54,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(57,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(58,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(59,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts(60,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts (68 errors) ==== @@ -77,191 +77,191 @@ tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignm var x1: boolean; x1 *= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 *= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x1 *= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x2: string; x2 *= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 *= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x2 *= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x3: {}; x3 *= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 *= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x3 *= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x4: void; x4 *= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 *= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x4 *= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x5: number; x5 *= b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 *= true; ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 *= '' ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 *= {}; ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var x6: E; x6 *= b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 *= true; ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 *= '' ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 *= {}; ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt index 7b9eb40dee0..8a133148007 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(8,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(11,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(11,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(12,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(15,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(15,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(16,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(21,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(22,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -19,19 +19,19 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(44,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(44,1): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(45,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(47,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(49,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(50,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(51,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(52,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(52,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(53,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(54,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(54,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(55,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(58,9): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(59,9): error TS1128: Declaration or statement expected. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(62,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(62,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(63,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(69,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(70,15): error TS1034: 'super' must be followed by an argument list or member access. @@ -43,7 +43,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(86,21): error TS1128: Declaration or statement expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(87,11): error TS1005: ';' expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(88,11): error TS1005: ';' expected. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(91,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(91,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(92,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(95,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(96,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -58,21 +58,21 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(105,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(105,1): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(106,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(107,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(107,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(108,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(109,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(110,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(111,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(111,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(112,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(113,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(113,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(114,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(115,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(115,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(116,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(117,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(117,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(118,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(119,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(119,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(120,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(121,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(121,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(122,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -85,7 +85,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa constructor() { this *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. this += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -93,7 +93,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa foo() { this *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. this += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -101,7 +101,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa static sfoo() { this *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. this += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -166,13 +166,13 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. true *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. true += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. false *= value; ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. false += value; ~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -184,13 +184,13 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. '' *= value; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. '' += value; ~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. /d+/ *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. /d+/ += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -206,7 +206,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa // array literals ['', ''] *= value; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ['', ''] += value; ~~~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -259,7 +259,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa // function calls foo() *= value; ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. foo() += value; ~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -305,7 +305,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (true) *= value; ~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (true) += value; ~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -317,37 +317,37 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ('') *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ('') += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (/d+/) *= value; ~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (/d+/) += value; ~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ({}) *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ({}) += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ([]) *= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ([]) += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (function baz1() { }) *= value; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (function baz2() { }) += value; ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. (foo()) *= value; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (foo()) += value; ~~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSCannotBeAssigned.errors.txt b/tests/baselines/reference/compoundExponentiationAssignmentLHSCannotBeAssigned.errors.txt index 6d48d968638..3c7e39fe54d 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSCannotBeAssigned.errors.txt +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSCannotBeAssigned.errors.txt @@ -1,71 +1,71 @@ -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(8,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(9,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(9,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(11,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(13,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(8,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(9,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(9,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(11,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(13,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(14,8): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(15,8): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(19,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(20,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(22,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(24,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(19,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(20,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(22,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(24,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(25,8): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(26,8): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(30,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(31,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(32,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(33,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(33,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(34,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(35,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(35,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(30,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(31,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(32,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(33,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(33,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(34,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(35,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(35,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(36,8): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(37,8): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(41,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(41,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(42,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(42,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(43,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(44,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(44,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(45,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(46,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(47,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(41,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(41,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(42,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(42,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(43,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(44,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(44,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(45,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(46,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(47,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(47,8): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(48,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(48,8): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(51,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(52,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(53,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(54,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(57,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(58,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(59,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(60,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(51,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(52,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(53,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(54,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(57,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(58,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(59,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts(60,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSCannotBeAssigned.ts (68 errors) ==== @@ -77,191 +77,191 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm var x1: boolean; x1 **= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x1 **= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x1 **= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x2: string; x2 **= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x2 **= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x2 **= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x3: {}; x3 **= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x3 **= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x3 **= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x4: void; x4 **= a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= b; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= true; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= 0; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= '' ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= E.a; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= {}; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x4 **= null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. x4 **= undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var x5: number; x5 **= b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 **= true; ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 **= '' ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x5 **= {}; ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var x6: E; x6 **= b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 **= true; ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 **= '' ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. x6 **= {}; ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt index 3f806e2c1fd..e3c9918aa4b 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(10,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(10,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(18,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(21,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(25,1): error TS2539: Cannot assign to 'M' because it is not a variable. @@ -9,19 +9,19 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(32,1): error TS2539: Cannot assign to 'foo' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(35,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(35,1): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(36,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(37,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(38,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(39,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(39,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(40,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(43,10): error TS1128: Declaration or statement expected. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(46,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(52,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(56,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(60,15): error TS1034: 'super' must be followed by an argument list or member access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(65,21): error TS1128: Declaration or statement expected. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(66,11): error TS1005: ';' expected. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(69,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(69,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(72,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(73,2): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(74,2): error TS2539: Cannot assign to 'C' because it is not a variable. @@ -29,14 +29,14 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(76,2): error TS2539: Cannot assign to 'foo' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(77,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(77,1): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(78,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(78,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(79,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(80,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(81,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(82,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(83,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(84,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(85,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(80,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(81,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(82,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(83,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(84,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(85,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts (39 errors) ==== @@ -48,17 +48,17 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm constructor() { this **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } foo() { this **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } static sfoo() { this **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } } @@ -99,19 +99,19 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm !!! error TS2531: Object is possibly 'null'. true **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. false **= value; ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 0 **= value; ~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. '' **= value; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. /d+/ **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // object literals { a: 0 } **= value; @@ -121,7 +121,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm // array literals ['', ''] **= value; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // super class Derived extends C { @@ -156,7 +156,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm // function calls foo() **= value; ~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // parentheses, the containted expression is value (this) **= value; @@ -181,25 +181,25 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm !!! error TS2531: Object is possibly 'null'. (true) **= value; ~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (0) **= value; ~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. ('') **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (/d+/) **= value; ~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ({}) **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ([]) **= value; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (function baz1() { }) **= value; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (foo()) **= value; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index d683899f41d..2fbd47409dd 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,28): error TS1005: ':' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,29): error TS1005: ',' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,18): error TS1128: Declaration or statement expected. @@ -132,7 +132,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS !!! error TS1005: ',' expected. } ~~~~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. case = bfs.STATEMENTS(4); ~~~~ diff --git a/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt b/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt index ff54b4d52c6..9fb7b43b0d8 100644 --- a/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt @@ -1,20 +1,20 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2539: Cannot assign to 'A' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2539: Cannot assign to 'A' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -24,8 +24,8 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,27): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -34,10 +34,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,25): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(63,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(63,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(67,7): error TS1005: ';' expected. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(67,9): error TS1109: Expression expected. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithAnyOtherTypeInvalidOperations.ts(68,7): error TS1005: ';' expected. @@ -78,7 +78,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // any type var var ResultIsNumber1 = --ANY2; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = --A; ~ !!! error TS2539: Cannot assign to 'A' because it is not a variable. @@ -87,14 +87,14 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber4 = --obj; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = --obj1; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = ANY2--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = A--; ~ !!! error TS2539: Cannot assign to 'A' because it is not a variable. @@ -103,15 +103,15 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber9 = obj--; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = obj1--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // any type literal var ResultIsNumber11 = --{}; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = --null; ~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -128,7 +128,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2531: Object is possibly 'null'. var ResultIsNumber15 = {}--; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = undefined--; ~~~~~~~~~ !!! error TS2539: Cannot assign to 'undefined' because it is not a variable. @@ -157,10 +157,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber22 = --obj1.x; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber23 = --obj1.y; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber24 = foo()--; ~~~~~ @@ -185,19 +185,19 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber29 = obj1.x--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber30 = obj1.y--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators --ANY2; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ANY2--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --ANY1--; ~~ diff --git a/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt b/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt index 284e15c5193..cd92089e814 100644 --- a/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithEnumType.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(6,31): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(7,29): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(10,9): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,1): error TS2542: Index signature in type 'typeof ENUM1' only permits reading. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithEnumType.ts(12,7): error TS2304: Cannot find name 'A'. @@ -26,7 +26,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp ENUM1[A]--; ~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~ !!! error TS2542: Index signature in type 'typeof ENUM1' only permits reading. ~ diff --git a/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt b/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt index 8cf459cb790..eb1748ea031 100644 --- a/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithNumberTypeInvalidOperations.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -13,10 +13,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -40,10 +40,10 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp //number type var var ResultIsNumber1 = --NUMBER1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = NUMBER1--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // number type literal var ResultIsNumber3 = --1; @@ -51,20 +51,20 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber4 = --{ x: 1, y: 2}; ~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = --{ x: 1, y: (n: number) => { return n; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = 1--; ~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber7 = { x: 1, y: 2 }--; ~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = { x: 1, y: (n: number) => { return n; } }--; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // number type expressions var ResultIsNumber9 = --foo(); @@ -93,7 +93,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. --NUMBER1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --foo(); ~~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -103,7 +103,7 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. NUMBER1--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()--; ~~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/decrementOperatorWithUnsupportedBooleanType.errors.txt b/tests/baselines/reference/decrementOperatorWithUnsupportedBooleanType.errors.txt index cef6decd4ad..724af6dc8c4 100644 --- a/tests/baselines/reference/decrementOperatorWithUnsupportedBooleanType.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithUnsupportedBooleanType.errors.txt @@ -1,32 +1,32 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(17,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(22,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(26,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(31,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(32,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(33,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(36,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(37,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(38,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(39,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(42,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(43,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(44,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(45,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(46,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(47,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(49,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(50,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(51,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(52,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(53,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(54,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(54,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(17,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(22,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(26,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(31,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(32,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(33,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(36,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(37,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(38,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(39,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(42,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(43,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(44,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(45,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(46,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(47,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(49,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(50,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(51,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(52,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(53,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(54,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts(54,11): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedBooleanType.ts (29 errors) ==== @@ -48,97 +48,97 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // boolean type var var ResultIsNumber1 = --BOOLEAN; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = BOOLEAN--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // boolean type literal var ResultIsNumber3 = --true; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber4 = --{ x: true, y: false }; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = --{ x: true, y: (n: boolean) => { return n; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = true--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = { x: true, y: false }--; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = { x: true, y: (n: boolean) => { return n; } }--; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // boolean type expressions var ResultIsNumber9 = --objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = --M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber11 = --foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = --A.foo(); ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber13 = foo()--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber14 = A.foo()--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber15 = objA.a--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = M.n--; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators --true; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --BOOLEAN; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --objA.a, M.n; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. true--; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. BOOLEAN--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. M.n--; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a--, M.n--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/decrementOperatorWithUnsupportedStringType.errors.txt b/tests/baselines/reference/decrementOperatorWithUnsupportedStringType.errors.txt index 7169155158c..3879a0d14f1 100644 --- a/tests/baselines/reference/decrementOperatorWithUnsupportedStringType.errors.txt +++ b/tests/baselines/reference/decrementOperatorWithUnsupportedStringType.errors.txt @@ -1,42 +1,42 @@ -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(19,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(21,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(22,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(29,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(31,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(35,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(36,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(44,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(45,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(46,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(49,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(50,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(51,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(52,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(53,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(54,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(55,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(56,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(58,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(59,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(60,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(61,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(62,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(63,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(64,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(65,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(19,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(21,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(22,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(29,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(31,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(35,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(36,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(44,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(45,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(46,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(49,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(50,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(51,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(52,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(53,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(54,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(55,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(56,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(58,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(59,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(60,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(61,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(62,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(63,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(64,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts(65,11): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOperatorWithUnsupportedStringType.ts (39 errors) ==== @@ -59,127 +59,127 @@ tests/cases/conformance/expressions/unaryOperators/decrementOperator/decrementOp // string type var var ResultIsNumber1 = --STRING; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = --STRING1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber3 = STRING--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber4 = STRING1--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // string type literal var ResultIsNumber5 = --""; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = --{ x: "", y: "" }; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = --{ x: "", y: (s: string) => { return s; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = ""--; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber9 = { x: "", y: "" }--; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = { x: "", y: (s: string) => { return s; } }--; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // string type expressions var ResultIsNumber11 = --objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = --M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber13 = --STRING1[0]; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber14 = --foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber15 = --A.foo(); ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = --(STRING + STRING); ~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber17 = objA.a--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber18 = M.n--; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber19 = STRING1[0]--; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber20 = foo()--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber21 = A.foo()--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber22 = (STRING + STRING)--; ~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators --""; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --STRING; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --STRING1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --STRING1[0]; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --objA.a, M.n; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ""--; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING1--; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING1[0]--; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()--; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. M.n--; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a--, M.n--; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/duplicateLocalVariable1.errors.txt b/tests/baselines/reference/duplicateLocalVariable1.errors.txt index 0486cd1af60..6f521565862 100644 --- a/tests/baselines/reference/duplicateLocalVariable1.errors.txt +++ b/tests/baselines/reference/duplicateLocalVariable1.errors.txt @@ -3,7 +3,7 @@ tests/cases/compiler/duplicateLocalVariable1.ts(1,11): error TS1146: Declaration tests/cases/compiler/duplicateLocalVariable1.ts(1,13): error TS2304: Cannot find name 'commonjs'. tests/cases/compiler/duplicateLocalVariable1.ts(186,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. tests/cases/compiler/duplicateLocalVariable1.ts(186,29): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. -tests/cases/compiler/duplicateLocalVariable1.ts(186,37): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/duplicateLocalVariable1.ts(186,37): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/duplicateLocalVariable1.ts (6 errors) ==== @@ -204,7 +204,7 @@ tests/cases/compiler/duplicateLocalVariable1.ts(186,37): error TS2356: An arithm ~~~~~~ !!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. bytes.push(fb.readByte()); } var expected = [0xEF, 0xBB, 0xBF, 0x54, 0xC3, 0xA8, 0xE1, 0xB4, 0xA3, 0xE2, 0x80, 0xA0, 0x0D, 0x0A]; diff --git a/tests/baselines/reference/duplicateLocalVariable2.errors.txt b/tests/baselines/reference/duplicateLocalVariable2.errors.txt index 5e89cc422cc..0258e7e8460 100644 --- a/tests/baselines/reference/duplicateLocalVariable2.errors.txt +++ b/tests/baselines/reference/duplicateLocalVariable2.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/duplicateLocalVariable2.ts(27,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. tests/cases/compiler/duplicateLocalVariable2.ts(27,29): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. -tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/duplicateLocalVariable2.ts (3 errors) ==== @@ -36,7 +36,7 @@ tests/cases/compiler/duplicateLocalVariable2.ts(27,37): error TS2356: An arithme ~~~~~~ !!! error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. bytes.push(fb.readByte()); } var expected = [0xEF]; diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.errors.txt b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.errors.txt index 86410b1b491..07196d68190 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(7,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(7,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(7,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(8,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(9,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(10,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(11,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(11,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(11,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(12,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(12,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(12,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(14,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(14,21): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -13,17 +13,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(15,23): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(16,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(16,23): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(17,25): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,28): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,28): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(18,28): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,36): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,36): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(19,36): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(21,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(21,34): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -31,17 +31,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(22,36): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(23,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(23,36): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,38): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,38): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(24,38): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,41): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,41): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(25,41): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,49): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,49): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError1.ts(26,49): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -54,7 +54,7 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl // TempateHead & TemplateTail are empty `${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${-t1 ** t2 - t1}`; @@ -68,12 +68,12 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -94,29 +94,29 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 }${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${1 + typeof t1 ** t2 ** t1}${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -137,28 +137,28 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 } hello world ${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${1 + typeof t1 ** t2 ** t1} hello world ${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.errors.txt b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.errors.txt index 7d3651498c5..47f1768ba2a 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.errors.txt @@ -1,11 +1,11 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(7,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(8,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(9,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(10,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(10,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(10,10): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(11,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(11,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(11,10): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(12,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(12,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(12,14): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(14,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(14,27): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -13,17 +13,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(15,29): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(16,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(16,29): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,10): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,31): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,31): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(17,31): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,10): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,34): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,34): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(18,34): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,14): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,42): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,42): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(19,42): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(21,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(21,40): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -31,17 +31,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(22,42): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(23,10): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(23,42): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,10): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,44): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,44): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(24,44): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,10): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,47): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,47): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(25,47): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,14): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,55): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,55): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError2.ts(26,55): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -63,17 +63,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -94,29 +94,29 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${!t1 ** t2 ** --t1 }${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${1 + typeof t1 ** t2 ** t1}${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -137,29 +137,29 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${!t1 ** t2 ** --t1 } hello world ${!t1 ** t2 ** --t1 }`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `hello ${1 + typeof t1 ** t2 ** t1} hello world ${1 + typeof t1 ** t2 ** t1}`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.errors.txt b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.errors.txt index 0c6fab96f90..11d6c543b48 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.errors.txt @@ -1,11 +1,11 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(7,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(8,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(9,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(10,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(10,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(10,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(11,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(11,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(11,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(12,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(12,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(12,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(14,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(14,21): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -13,17 +13,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(15,23): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(16,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(16,23): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(17,25): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,28): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,28): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(18,28): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,36): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,36): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(19,36): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(21,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(21,34): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -31,17 +31,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(22,36): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(23,4): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(23,36): error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,4): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,38): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,38): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(24,38): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,4): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,4): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,41): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,41): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(25,41): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,8): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,8): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,49): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,49): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTemplateStringWithSyntaxError3.ts(26,49): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -63,17 +63,17 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 } world`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1} world`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${1 + typeof t1 ** t2 ** t1} world`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -94,29 +94,29 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 }${!t1 ** t2 ** --t1 } world`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1} world`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${1 + typeof t1 ** t2 ** t1}${1 + typeof t1 ** t2 ** t1} world`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -137,28 +137,28 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorInTempl !!! error TS17006: An unary expression with the '-' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${!t1 ** t2 ** --t1 } hello world ${!t1 ** t2 ** --t1 } !!`; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1} !!`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. `${1 + typeof t1 ** t2 ** t1} hello world ${1 + typeof t1 ** t2 ** t1} !!`; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorSyntaxError2.errors.txt b/tests/baselines/reference/exponentiationOperatorSyntaxError2.errors.txt index f144879002e..5070f0ad9d2 100644 --- a/tests/baselines/reference/exponentiationOperatorSyntaxError2.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorSyntaxError2.errors.txt @@ -1,46 +1,46 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(4,1): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(4,8): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(5,1): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(5,8): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(6,1): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(6,8): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(7,1): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(7,8): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(10,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(10,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(10,6): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(10,13): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(11,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(11,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(11,6): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(11,13): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(12,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(12,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(12,6): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(12,13): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(13,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(13,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(13,6): error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(13,13): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(15,1): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(16,1): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(17,1): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(18,1): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(19,1): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(21,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(21,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(21,6): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(22,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(22,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(22,6): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(23,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(23,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(23,6): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(24,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(24,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(24,6): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(25,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(25,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(25,6): error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(27,1): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(27,1): error TS17006: An unary expression with the 'void' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -72,25 +72,25 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxE tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(47,6): error TS17006: An unary expression with the '~' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(48,6): error TS17006: An unary expression with the '~' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(49,6): error TS17006: An unary expression with the '~' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(51,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(51,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(51,1): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(52,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(52,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(52,1): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(53,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(53,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(53,1): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(54,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(54,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(54,1): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(55,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(55,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(55,1): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(57,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(57,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(57,6): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(58,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(58,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(58,6): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(59,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(59,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(59,6): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(60,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(60,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(60,6): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(61,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(61,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(61,6): error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(63,1): error TS17007: A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxError2.ts(64,1): error TS17007: A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -105,28 +105,28 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxE delete --temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. delete ++temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. delete temp-- ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. delete temp++ ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ @@ -135,28 +135,28 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxE 1 ** delete --temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** delete ++temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** delete temp-- ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** delete temp++ ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'delete' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. ~~~~~~ @@ -164,53 +164,53 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxE typeof --temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. typeof temp-- ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. typeof 3 ** 4; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. typeof temp++ ** 4; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. typeof temp-- ** 4; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** typeof --temp ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** typeof temp-- ** 3; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** typeof 3 ** 4; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** typeof temp++ ** 4; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** typeof temp-- ** 4; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~~~~~ !!! error TS17006: An unary expression with the 'typeof' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. @@ -300,53 +300,53 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorSyntaxE ! --temp ** 3; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. !temp-- ** 3; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. !3 ** 4; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. !temp++ ** 4; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. !temp-- ** 4; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** ! --temp ** 3; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** !temp-- ** 3; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** !3 ** 4; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** !temp++ ** 4; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. 1 ** !temp-- ** 4; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ !!! error TS17006: An unary expression with the '!' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses. diff --git a/tests/baselines/reference/exponentiationOperatorWithInvalidOperands.errors.txt b/tests/baselines/reference/exponentiationOperatorWithInvalidOperands.errors.txt index b62cd9601e4..da9141bc7ff 100644 --- a/tests/baselines/reference/exponentiationOperatorWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithInvalidOperands.errors.txt @@ -1,59 +1,59 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(15,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(17,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(18,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(19,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(22,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(24,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(25,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(26,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(29,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(31,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(32,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(33,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(36,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(38,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(39,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(40,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(43,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(45,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(46,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(47,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(50,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(52,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(53,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(54,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(57,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(59,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(15,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(17,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(18,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(19,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(22,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(24,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(25,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(26,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(29,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(31,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(32,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(33,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(36,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(38,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(39,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(40,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(43,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(45,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(46,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(47,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(50,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(52,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(53,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(54,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(57,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(59,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidOperands.ts (56 errors) ==== @@ -73,167 +73,167 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInv var r1a1 = a ** a; //ok var r1a2 = a ** b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = a ** c; //ok var r1a4 = a ** d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a5 = a ** e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a6 = a ** f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b ** a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b2 = b ** b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b3 = b ** c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b4 = b ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b5 = b ** e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b6 = b ** f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c ** a; //ok var r1c2 = c ** b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = c ** c; //ok var r1c4 = c ** d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c5 = c ** e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c6 = c ** f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d ** a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d2 = d ** b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d3 = d ** c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d4 = d ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d5 = d ** e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d6 = d ** f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e ** a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e2 = e ** b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e3 = e ** c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e4 = e ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e5 = e ** e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e6 = e ** f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = f ** a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f2 = f ** b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f3 = f ** c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f4 = f ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f5 = f ** e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f6 = f ** f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g1 = E.a ** a; //ok var r1g2 = E.a ** b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g3 = E.a ** c; //ok var r1g4 = E.a ** d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g5 = E.a ** e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g6 = E.a ** f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h1 = a ** E.b; //ok var r1h2 = b ** E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h3 = c ** E.b; //ok var r1h4 = d ** E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h5 = e ** E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h6 = f ** E.b ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.errors.txt b/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.errors.txt index 77f20df2597..67cad463c4f 100644 --- a/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.errors.txt @@ -1,38 +1,38 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(22,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(23,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(24,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(25,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(26,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(10,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(12,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(22,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(23,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(24,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(25,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(26,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(28,9): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(29,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(29,9): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(30,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(30,9): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(31,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(31,9): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(33,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(33,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(33,14): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(34,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(34,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(34,14): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(35,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(35,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(35,14): error TS2703: The operand of a delete operator must be a property reference. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(36,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(36,6): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.ts(36,14): error TS2703: The operand of a delete operator must be a property reference. @@ -42,106 +42,106 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithInv // Error: incorrect type on left-hand side (! --temp) ** 3; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp--) ** 3; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!3) ** 4; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp++) ** 4; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp--) ** 4; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (! --temp) ** 3 ** 1; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp--) ** 3 ** 1; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!3) ** 4 ** 1; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp++) ** 4 ** 1; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (!temp--) ** 4 ** 1; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (typeof --temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (typeof temp--) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (typeof 3) ** 4; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (typeof temp++) ** 4; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (typeof temp--) ** 4; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 1 ** (typeof --temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 1 ** (typeof temp--) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 1 ** (typeof 3) ** 4; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 1 ** (typeof temp++) ** 4; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 1 ** (typeof temp--) ** 4; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (delete --temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. (delete ++temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. (delete temp--) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. (delete temp++) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** (delete --temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** (delete ++temp) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** (delete temp--) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. 1 ** (delete temp++) ** 3; ~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~ !!! error TS2703: The operand of a delete operator must be a property reference. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithNullValueAndInvalidOperands.errors.txt b/tests/baselines/reference/exponentiationOperatorWithNullValueAndInvalidOperands.errors.txt index 2d0b76f28cc..c96576f7ecc 100644 --- a/tests/baselines/reference/exponentiationOperatorWithNullValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithNullValueAndInvalidOperands.errors.txt @@ -1,26 +1,26 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(9,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(10,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(11,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(13,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(14,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(15,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(17,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(18,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(18,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(18,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(19,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(19,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(19,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(21,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(22,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNullValueAndInvalidOperands.ts(23,18): error TS2531: Object is possibly 'null'. @@ -37,31 +37,31 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNul ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = null ** b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = null ** c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a ** null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b2 = b ** null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b3 = c ** null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -69,30 +69,30 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithNul ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = null ** ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = null ** {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true ** null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d2 = '' ** null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d3 = {} ** null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalid.errors.txt b/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalid.errors.txt index 5c659f24508..c5a0fbb1919 100644 --- a/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalid.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalid.errors.txt @@ -1,56 +1,56 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(1,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(2,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(3,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(12,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(14,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(1,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(2,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(3,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(12,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts(14,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalid.ts (12 errors) ==== var a = 1 ** `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b = 1 ** `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c = 1 ** `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d = 1 ** `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = `${ 3 }` ** 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f = `2${ 3 }` ** 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g = `${ 3 }4` ** 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h = `2${ 3 }4` ** 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var k = 10; k **= `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. k **= `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. k **= `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. k **= `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalidES6.errors.txt b/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalidES6.errors.txt index ed26fd48c75..0d5aac28aa4 100644 --- a/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalidES6.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithTemplateStringInvalidES6.errors.txt @@ -1,56 +1,56 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(1,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(2,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(3,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(12,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(1,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(2,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(3,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(11,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(12,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(13,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(14,1): error TS2304: Cannot find name 'kj'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(14,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts(14,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTemplateStringInvalidES6.ts (13 errors) ==== var a = 1 ** `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b = 1 ** `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c = 1 ** `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d = 1 ** `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = `${ 3 }` ** 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f = `2${ 3 }` ** 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g = `${ 3 }4` ** 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h = `2${ 3 }4` ** 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var k = 10; k **= `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. k **= `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. k **= `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. kj **= `2${ 3 }4`; ~~ !!! error TS2304: Cannot find name 'kj'. ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithTypeParameter.errors.txt b/tests/baselines/reference/exponentiationOperatorWithTypeParameter.errors.txt index 46fd0832468..4357a9ea34e 100644 --- a/tests/baselines/reference/exponentiationOperatorWithTypeParameter.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithTypeParameter.errors.txt @@ -1,21 +1,21 @@ -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(9,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(10,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(11,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(11,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(12,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(12,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(14,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(15,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(15,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(16,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(16,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(17,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(17,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(18,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(19,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(19,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(9,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(10,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(11,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(11,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(12,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(12,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(14,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(15,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(15,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(16,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(16,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(17,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(17,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(18,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(19,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts(19,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTypeParameter.ts (18 errors) ==== @@ -29,49 +29,49 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithTyp var r1a1 = a ** t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a1 = t ** a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b ** t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = t ** b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c ** t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c1 = t ** c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d ** t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = t ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e ** t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e1 = t ** d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = t ** t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } \ No newline at end of file diff --git a/tests/baselines/reference/exponentiationOperatorWithUndefinedValueAndInvalidOperands.errors.txt b/tests/baselines/reference/exponentiationOperatorWithUndefinedValueAndInvalidOperands.errors.txt index ce14298d02d..a0fa243e568 100644 --- a/tests/baselines/reference/exponentiationOperatorWithUndefinedValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/exponentiationOperatorWithUndefinedValueAndInvalidOperands.errors.txt @@ -1,26 +1,26 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(9,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(9,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(9,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(10,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(10,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(10,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(11,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(11,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(11,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(13,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(14,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(15,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(17,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(17,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(17,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(18,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(18,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(18,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(19,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(19,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(19,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(21,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(22,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUndefinedValueAndInvalidOperands.ts(23,18): error TS2532: Object is possibly 'undefined'. @@ -37,31 +37,31 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUnd ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = undefined ** b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = undefined ** c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a ** undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b2 = b ** undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b3 = c ** undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -69,30 +69,30 @@ tests/cases/conformance/es7/exponentiationOperator/exponentiationOperatorWithUnd ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = undefined ** ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = undefined ** {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true ** undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d2 = '' ** undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d3 = {} ** undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. \ No newline at end of file diff --git a/tests/baselines/reference/expr.errors.txt b/tests/baselines/reference/expr.errors.txt index 05e9ad9c3b4..5acfd691d58 100644 --- a/tests/baselines/reference/expr.errors.txt +++ b/tests/baselines/reference/expr.errors.txt @@ -13,60 +13,60 @@ tests/cases/compiler/expr.ts(165,5): error TS2365: Operator '+' cannot be applie tests/cases/compiler/expr.ts(166,5): error TS2365: Operator '+' cannot be applied to types 'I' and 'E'. tests/cases/compiler/expr.ts(170,5): error TS2365: Operator '+' cannot be applied to types 'E' and 'false'. tests/cases/compiler/expr.ts(172,5): error TS2365: Operator '+' cannot be applied to types 'E' and 'I'. -tests/cases/compiler/expr.ts(176,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(177,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(178,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(182,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(183,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(184,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(184,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(185,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(185,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(186,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(186,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(187,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(190,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(191,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(192,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(196,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(197,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(197,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(198,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(198,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(199,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(200,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(200,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(201,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(204,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(205,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(207,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(211,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(212,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(213,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(217,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(218,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(219,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(219,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(220,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(220,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(221,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(221,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(222,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(225,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(226,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(227,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(231,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(232,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(232,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(233,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(233,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(234,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(235,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(235,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(236,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(239,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(240,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/expr.ts(242,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/expr.ts(176,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(177,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(178,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(182,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(183,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(184,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(184,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(185,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(185,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(186,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(186,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(187,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(190,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(191,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(192,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(196,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(197,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(197,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(198,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(198,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(199,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(200,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(200,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(201,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(204,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(205,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(207,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(211,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(212,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(213,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(217,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(218,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(219,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(219,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(220,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(220,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(221,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(221,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(222,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(225,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(226,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(227,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(231,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(232,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(232,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(233,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(233,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(234,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(235,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(235,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(236,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(239,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(240,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/expr.ts(242,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/expr.ts (69 errors) ==== @@ -277,179 +277,179 @@ tests/cases/compiler/expr.ts(242,7): error TS2363: The right-hand side of an ari n^a; n^s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n^b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n^i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n^n; n^e; s^a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s^n; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s^b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s^i; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s^s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s^e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a^n; a^s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a^b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a^i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a^a; a^e; i^n; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i^s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i^b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i^a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i^i; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i^e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e^n; e^s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e^b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e^a; e^i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e^e; n-a; n-s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n-b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n-i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. n-n; n-e; s-a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s-n; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s-b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s-i; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s-s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s-e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a-n; a-s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a-b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a-i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a-a; a-e; i-n; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i-s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i-b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i-a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i-i; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. i-e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e-n; e-s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e-b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e-a; e-i; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e-e; } \ No newline at end of file diff --git a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt index efe6e098589..568412b563b 100644 --- a/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt +++ b/tests/baselines/reference/for-inStatementsArrayErrors.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(4,16): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. -tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(5,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(5,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(6,9): error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(8,16): error TS2339: Property 'unknownProperty' does not exist on type 'string'. tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors.ts(12,10): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'string'. @@ -15,7 +15,7 @@ tests/cases/conformance/statements/for-inStatements/for-inStatementsArrayErrors. !!! error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. let a2 = a[x - 1]; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. if (x === 1) { ~~~~~~~ !!! error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap. diff --git a/tests/baselines/reference/incrementOnTypeParameter.errors.txt b/tests/baselines/reference/incrementOnTypeParameter.errors.txt index 10cfb13aee5..71694710238 100644 --- a/tests/baselines/reference/incrementOnTypeParameter.errors.txt +++ b/tests/baselines/reference/incrementOnTypeParameter.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/incrementOnTypeParameter.ts(4,9): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/compiler/incrementOnTypeParameter.ts(5,39): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/compiler/incrementOnTypeParameter.ts(4,9): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/incrementOnTypeParameter.ts(5,39): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/incrementOnTypeParameter.ts (2 errors) ==== @@ -8,10 +8,10 @@ tests/cases/compiler/incrementOnTypeParameter.ts(5,39): error TS2356: An arithme foo() { this.a++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. for (var i: T, j = 0; j < 10; i++) { ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. } } } diff --git a/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt index 690f3391933..5d59f55a55a 100644 --- a/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithAnyOtherTypeInvalidOperations.errors.txt @@ -1,20 +1,20 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(25,25): error TS2539: Cannot assign to 'A' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(26,25): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(28,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(31,23): error TS2539: Cannot assign to 'A' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(32,23): error TS2539: Cannot assign to 'M' because it is not a variable. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(33,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(34,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(38,26): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(39,26): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(41,24): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(43,24): error TS2539: Cannot assign to 'undefined' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(46,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(47,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -24,8 +24,8 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(49,27): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(50,27): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(51,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(52,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(54,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(55,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(56,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -34,13 +34,13 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(57,25): error TS2365: Operator '+' cannot be applied to types 'null' and 'null'. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(58,25): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(63,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(59,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(60,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(63,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(67,7): error TS1005: ';' expected. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(67,9): error TS1109: Expression expected. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(68,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(68,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(68,7): error TS1005: ';' expected. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(68,9): error TS1109: Expression expected. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithAnyOtherTypeInvalidOperations.ts(69,10): error TS1005: ';' expected. @@ -73,7 +73,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // any type var var ResultIsNumber1 = ++ANY2; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = ++A; ~ !!! error TS2539: Cannot assign to 'A' because it is not a variable. @@ -82,14 +82,14 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber4 = ++obj; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = ++obj1; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = ANY2++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = A++; ~ !!! error TS2539: Cannot assign to 'A' because it is not a variable. @@ -98,15 +98,15 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2539: Cannot assign to 'M' because it is not a variable. var ResultIsNumber9 = obj++; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = obj1++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // any type literal var ResultIsNumber11 = ++{}; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = ++null; ~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -123,7 +123,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2531: Object is possibly 'null'. var ResultIsNumber15 = {}++; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = undefined++; ~~~~~~~~~ !!! error TS2539: Cannot assign to 'undefined' because it is not a variable. @@ -152,10 +152,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber22 = ++obj1.x; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber23 = ++obj1.y; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber24 = foo()++; ~~~~~ @@ -180,19 +180,19 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'undefined'. var ResultIsNumber29 = obj1.x++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber30 = obj1.y++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators ++ANY2; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ANY2++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++ANY1++; ~~ @@ -201,7 +201,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS1109: Expression expected. ++ANY2++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~ !!! error TS1005: ';' expected. ~ diff --git a/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt index ac021746157..bf4dcdf2fd6 100644 --- a/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithEnumTypeInvalidOperations.errors.txt @@ -2,8 +2,8 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(8,25): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(10,23): error TS2539: Cannot assign to 'ENUM' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(11,23): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(14,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(15,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(14,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(15,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(18,3): error TS2539: Cannot assign to 'ENUM' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(19,3): error TS2539: Cannot assign to 'ENUM1' because it is not a variable. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithEnumTypeInvalidOperations.ts(21,1): error TS2539: Cannot assign to 'ENUM' because it is not a variable. @@ -34,10 +34,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // enum type expressions var ResultIsNumber5 = ++(ENUM[1] + ENUM[2]); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = (ENUM[1] + ENUM[2])++; ~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operator ++ENUM; diff --git a/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt b/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt index 093a41aa355..ed1854a9f34 100644 --- a/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithNumberTypeInvalidOperations.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(22,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(26,23): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(31,25): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(32,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(33,26): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -13,10 +13,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(36,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(37,24): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(40,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(41,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(42,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(44,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(45,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithNumberTypeInvalidOperations.ts(46,1): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -40,10 +40,10 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp //number type var var ResultIsNumber1 = ++NUMBER1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = NUMBER1++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // number type literal var ResultIsNumber3 = ++1; @@ -51,20 +51,20 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber4 = ++{ x: 1, y: 2}; ~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = ++{ x: 1, y: (n: number) => { return n; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = 1++; ~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. var ResultIsNumber7 = { x: 1, y: 2 }++; ~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = { x: 1, y: (n: number) => { return n; } }++; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // number type expressions var ResultIsNumber9 = ++foo(); @@ -93,7 +93,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. ++NUMBER1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++foo(); ~~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. @@ -103,7 +103,7 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. NUMBER1++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()++; ~~~~~ !!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file diff --git a/tests/baselines/reference/incrementOperatorWithUnsupportedBooleanType.errors.txt b/tests/baselines/reference/incrementOperatorWithUnsupportedBooleanType.errors.txt index 42c00a2bf28..0bd170e45a6 100644 --- a/tests/baselines/reference/incrementOperatorWithUnsupportedBooleanType.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithUnsupportedBooleanType.errors.txt @@ -1,32 +1,32 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(17,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(22,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(26,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(31,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(32,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(33,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(36,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(37,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(38,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(39,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(42,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(43,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(44,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(45,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(46,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(47,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(49,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(50,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(51,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(52,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(53,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(54,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(54,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(17,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(19,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(22,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(23,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(24,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(26,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(27,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(28,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(31,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(32,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(33,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(36,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(37,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(38,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(39,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(42,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(43,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(44,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(45,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(46,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(47,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(49,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(50,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(51,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(52,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(53,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(54,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts(54,11): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedBooleanType.ts (29 errors) ==== @@ -48,97 +48,97 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // boolean type var var ResultIsNumber1 = ++BOOLEAN; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = BOOLEAN++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // boolean type literal var ResultIsNumber3 = ++true; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber4 = ++{ x: true, y: false }; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber5 = ++{ x: true, y: (n: boolean) => { return n; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = true++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = { x: true, y: false }++; ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = { x: true, y: (n: boolean) => { return n; } }++; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // boolean type expressions var ResultIsNumber9 = ++objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = ++M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber11 = ++foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = ++A.foo(); ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber13 = foo()++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber14 = A.foo()++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber15 = objA.a++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = M.n++; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators ++true; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++BOOLEAN; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++objA.a, M.n; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. true++; ~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. BOOLEAN++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. M.n++; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a++, M.n++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/incrementOperatorWithUnsupportedStringType.errors.txt b/tests/baselines/reference/incrementOperatorWithUnsupportedStringType.errors.txt index 7947bcb34b8..d21e2f3b8ea 100644 --- a/tests/baselines/reference/incrementOperatorWithUnsupportedStringType.errors.txt +++ b/tests/baselines/reference/incrementOperatorWithUnsupportedStringType.errors.txt @@ -1,42 +1,42 @@ -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(19,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(21,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(22,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(29,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(31,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(35,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(36,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(44,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(45,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(46,24): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(49,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(50,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(51,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(52,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(53,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(54,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(55,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(56,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(58,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(59,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(60,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(61,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(62,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(63,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(64,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(65,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(18,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(19,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(21,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(22,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(25,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(26,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(27,25): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(29,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(30,23): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(31,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(34,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(35,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(36,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(37,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(38,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(39,26): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(41,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(42,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(43,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(44,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(45,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(46,24): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(49,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(50,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(51,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(52,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(53,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(54,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(55,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(56,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(58,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(59,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(60,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(61,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(62,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(63,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(64,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(65,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts(65,11): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOperatorWithUnsupportedStringType.ts (39 errors) ==== @@ -59,127 +59,127 @@ tests/cases/conformance/expressions/unaryOperators/incrementOperator/incrementOp // string type var var ResultIsNumber1 = ++STRING; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber2 = ++STRING1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber3 = STRING++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber4 = STRING1++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // string type literal var ResultIsNumber5 = ++""; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber6 = ++{ x: "", y: "" }; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber7 = ++{ x: "", y: (s: string) => { return s; } }; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber8 = ""++; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber9 = { x: "", y: "" }++; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber10 = { x: "", y: (s: string) => { return s; } }++; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // string type expressions var ResultIsNumber11 = ++objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber12 = ++M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber13 = ++STRING1[0]; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber14 = ++foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber15 = ++A.foo(); ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber16 = ++(STRING + STRING); ~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber17 = objA.a++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber18 = M.n++; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber19 = STRING1[0]++; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber20 = foo()++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber21 = A.foo()++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. var ResultIsNumber22 = (STRING + STRING)++; ~~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. // miss assignment operators ++""; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++STRING; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++STRING1; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++STRING1[0]; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++foo(); ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++objA.a; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++M.n; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ++objA.a, M.n; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ""++; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING1++; ~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. STRING1[0]++; ~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. foo()++; ~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. M.n++; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. objA.a++, M.n++; ~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/interfaceNaming1.errors.txt b/tests/baselines/reference/interfaceNaming1.errors.txt index 5efeea8c5e9..f328e14fb1a 100644 --- a/tests/baselines/reference/interfaceNaming1.errors.txt +++ b/tests/baselines/reference/interfaceNaming1.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/interfaceNaming1.ts(1,1): error TS2693: 'interface' only refers to a type, but is being used as a value here. tests/cases/compiler/interfaceNaming1.ts(1,11): error TS1005: ';' expected. tests/cases/compiler/interfaceNaming1.ts(3,1): error TS2693: 'interface' only refers to a type, but is being used as a value here. -tests/cases/compiler/interfaceNaming1.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/interfaceNaming1.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/interfaceNaming1.ts (4 errors) ==== @@ -15,5 +15,5 @@ tests/cases/compiler/interfaceNaming1.ts(3,13): error TS2363: The right-hand sid ~~~~~~~~~ !!! error TS2693: 'interface' only refers to a type, but is being used as a value here. ~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.errors.txt b/tests/baselines/reference/jsdocInTypeScript.errors.txt index 24f80e1c889..38f3f136b9e 100644 --- a/tests/baselines/reference/jsdocInTypeScript.errors.txt +++ b/tests/baselines/reference/jsdocInTypeScript.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/jsdocInTypeScript.ts(16,23): error TS2304: Cannot find name 'MyType'. -tests/cases/compiler/jsdocInTypeScript.ts(23,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/jsdocInTypeScript.ts(23,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/jsdocInTypeScript.ts(25,3): error TS2345: Argument of type '1' is not assignable to parameter of type 'boolean'. tests/cases/compiler/jsdocInTypeScript.ts(25,15): error TS2339: Property 'length' does not exist on type 'number'. tests/cases/compiler/jsdocInTypeScript.ts(30,3): error TS2339: Property 'x' does not exist on type '{}'. @@ -33,7 +33,7 @@ tests/cases/compiler/jsdocInTypeScript.ts(42,12): error TS2503: Cannot find name */ function f(x: boolean) { return x * 2; } // Should error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // Should fail, because it takes a boolean and returns a number f(1); f(true).length; ~ diff --git a/tests/baselines/reference/objectLitIndexerContextualType.errors.txt b/tests/baselines/reference/objectLitIndexerContextualType.errors.txt index 5012dc11728..3c766dedcc6 100644 --- a/tests/baselines/reference/objectLitIndexerContextualType.errors.txt +++ b/tests/baselines/reference/objectLitIndexerContextualType.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/objectLitIndexerContextualType.ts(12,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/objectLitIndexerContextualType.ts(12,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/objectLitIndexerContextualType.ts(15,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/objectLitIndexerContextualType.ts(15,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(12,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(12,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(15,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(15,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/objectLitIndexerContextualType.ts(18,5): error TS2322: Type '{ s: (t: any) => number; }' is not assignable to type 'J'. Object literal may only specify known properties, and 's' does not exist in type 'J'. -tests/cases/compiler/objectLitIndexerContextualType.ts(21,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/objectLitIndexerContextualType.ts(21,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(21,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/objectLitIndexerContextualType.ts(21,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/objectLitIndexerContextualType.ts (7 errors) ==== @@ -22,16 +22,16 @@ tests/cases/compiler/objectLitIndexerContextualType.ts(21,17): error TS2363: The x = { s: t => t * t, // Should error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. }; x = { 0: t => t * t, // Should error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. }; y = { s: t => t * t, // Should error @@ -42,8 +42,8 @@ tests/cases/compiler/objectLitIndexerContextualType.ts(21,17): error TS2363: The y = { 0: t => t * t, // Should error ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. }; \ No newline at end of file diff --git a/tests/baselines/reference/parseRegularExpressionMixedWithComments.errors.txt b/tests/baselines/reference/parseRegularExpressionMixedWithComments.errors.txt index b4e08a6af46..83faf9086e0 100644 --- a/tests/baselines/reference/parseRegularExpressionMixedWithComments.errors.txt +++ b/tests/baselines/reference/parseRegularExpressionMixedWithComments.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(5,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(5,23): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(6,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(6,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(5,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(5,23): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(6,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts(6,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpressionMixedWithComments.ts (4 errors) ==== @@ -11,11 +11,11 @@ tests/cases/conformance/parser/ecmascript5/RegularExpressions/parseRegularExpres 1; var regex4 = /**// /**/asdf /; ~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var regex5 = /**// asdf/**/ /; ~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnaryExpression2.errors.txt b/tests/baselines/reference/parserUnaryExpression2.errors.txt index 4f9c67a16f3..58a87887f11 100644 --- a/tests/baselines/reference/parserUnaryExpression2.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression2.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression2.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression2.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression2.ts (1 errors) ==== ++function(e) { } ~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnaryExpression3.errors.txt b/tests/baselines/reference/parserUnaryExpression3.errors.txt index 5d6dc350247..b23362922e1 100644 --- a/tests/baselines/reference/parserUnaryExpression3.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression3.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression3.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression3.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression3.ts (1 errors) ==== ++[0]; ~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnaryExpression4.errors.txt b/tests/baselines/reference/parserUnaryExpression4.errors.txt index 70b2a3cfc17..d80e4575cd7 100644 --- a/tests/baselines/reference/parserUnaryExpression4.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression4.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression4.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression4.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression4.ts (1 errors) ==== ++{}; ~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/shebangError.errors.txt b/tests/baselines/reference/shebangError.errors.txt index e8197d8bc5f..cba74ceaed7 100644 --- a/tests/baselines/reference/shebangError.errors.txt +++ b/tests/baselines/reference/shebangError.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/shebangError.ts(2,1): error TS1127: Invalid character. -tests/cases/compiler/shebangError.ts(2,2): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/shebangError.ts(2,2): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/shebangError.ts(2,12): error TS2304: Cannot find name 'env'. tests/cases/compiler/shebangError.ts(2,16): error TS1005: ';' expected. tests/cases/compiler/shebangError.ts(2,16): error TS2304: Cannot find name 'node'. @@ -11,7 +11,7 @@ tests/cases/compiler/shebangError.ts(2,16): error TS2304: Cannot find name 'node !!! error TS1127: Invalid character. ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~ !!! error TS2304: Cannot find name 'env'. ~~~~ diff --git a/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt b/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt index 58add5bd3c7..e159a026cf1 100644 --- a/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt +++ b/tests/baselines/reference/stringLiteralTypesWithVariousOperators02.errors.txt @@ -3,10 +3,10 @@ tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperato tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(8,9): error TS2365: Operator '+' cannot be applied to types 'number | "ABC" | "XYZ"' and 'number | "ABC" | "XYZ"'. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(9,9): error TS2365: Operator '+' cannot be applied to types 'number | "ABC" | "XYZ"' and 'true'. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(10,9): error TS2365: Operator '+' cannot be applied to types 'false' and 'number | "ABC" | "XYZ"'. -tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(11,9): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(12,11): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(14,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(11,9): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(12,11): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(14,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(16,9): error TS2367: This condition will always return 'false' since the types '"ABC"' and '"XYZ"' have no overlap. tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperators02.ts(17,9): error TS2367: This condition will always return 'true' since the types '"ABC"' and '"XYZ"' have no overlap. @@ -34,16 +34,16 @@ tests/cases/conformance/types/stringLiteral/stringLiteralTypesWithVariousOperato !!! error TS2365: Operator '+' cannot be applied to types 'false' and 'number | "ABC" | "XYZ"'. let f = abcOrXyzOrNumber++; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. let g = --abcOrXyzOrNumber; ~~~~~~~~~~~~~~~~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. let h = abcOrXyzOrNumber ^ 10; ~~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. let i = abcOrXyzOrNumber | 10; ~~~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. let j = abc < xyz; let k = abc === xyz; ~~~~~~~~~~~ diff --git a/tests/baselines/reference/symbolType10.errors.txt b/tests/baselines/reference/symbolType10.errors.txt index 852f863bae8..44b05a21a5c 100644 --- a/tests/baselines/reference/symbolType10.errors.txt +++ b/tests/baselines/reference/symbolType10.errors.txt @@ -1,34 +1,34 @@ -tests/cases/conformance/es6/Symbols/symbolType10.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(2,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(3,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType10.ts(7,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(2,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(3,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType10.ts(7,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/Symbols/symbolType10.ts (8 errors) ==== var s = Symbol.for("bitwise"); s & s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s | s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s ^ s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s & 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 0 | s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/symbolType12.errors.txt b/tests/baselines/reference/symbolType12.errors.txt index b6034c62eec..1e82b7adb41 100644 --- a/tests/baselines/reference/symbolType12.errors.txt +++ b/tests/baselines/reference/symbolType12.errors.txt @@ -1,37 +1,37 @@ -tests/cases/conformance/es6/Symbols/symbolType12.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(3,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(5,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(7,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(3,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(5,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(7,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(8,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es6/Symbols/symbolType12.ts(9,1): error TS2365: Operator '+=' cannot be applied to types 'symbol' and 'symbol'. tests/cases/conformance/es6/Symbols/symbolType12.ts(10,1): error TS2365: Operator '+=' cannot be applied to types 'symbol' and '0'. tests/cases/conformance/es6/Symbols/symbolType12.ts(11,1): error TS2469: The '+=' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType12.ts(12,8): error TS2469: The '+=' operator cannot be applied to type 'symbol'. -tests/cases/conformance/es6/Symbols/symbolType12.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(13,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(15,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(17,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(19,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(21,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(23,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(25,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType12.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(13,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(13,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(14,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(15,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(15,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(16,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(17,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(17,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(19,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(19,8): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(20,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(21,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(22,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(23,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(23,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(24,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(25,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType12.ts(26,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es6/Symbols/symbolType12.ts(28,8): error TS2469: The '+=' operator cannot be applied to type 'symbol'. @@ -40,28 +40,28 @@ tests/cases/conformance/es6/Symbols/symbolType12.ts(28,8): error TS2469: The '+= var str = ""; s *= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s *= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s /= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s /= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s %= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s %= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s += s; ~~~~~~ !!! error TS2365: Operator '+=' cannot be applied to types 'symbol' and 'symbol'. @@ -76,60 +76,60 @@ tests/cases/conformance/es6/Symbols/symbolType12.ts(28,8): error TS2469: The '+= !!! error TS2469: The '+=' operator cannot be applied to type 'symbol'. s -= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s -= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s <<= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s <<= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>>= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>>= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s &= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s &= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s ^= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s ^= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s |= s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s |= 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. str += (s || str); ~~~~~~~~~~ diff --git a/tests/baselines/reference/symbolType3.errors.txt b/tests/baselines/reference/symbolType3.errors.txt index bd9754f7121..dec7b109798 100644 --- a/tests/baselines/reference/symbolType3.errors.txt +++ b/tests/baselines/reference/symbolType3.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/es6/Symbols/symbolType3.ts(2,8): error TS2704: The operand of a delete operator cannot be a read-only property. -tests/cases/conformance/es6/Symbols/symbolType3.ts(5,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType3.ts(6,3): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType3.ts(5,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType3.ts(6,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es6/Symbols/symbolType3.ts(7,3): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType3.ts(8,3): error TS2469: The '-' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType3.ts(9,3): error TS2469: The '~' operator cannot be applied to type 'symbol'. @@ -16,10 +16,10 @@ tests/cases/conformance/es6/Symbols/symbolType3.ts(12,2): error TS2469: The '+' typeof Symbol.toStringTag; ++s; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. --s; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. + Symbol(); ~~~~~~~~ !!! error TS2469: The '+' operator cannot be applied to type 'symbol'. diff --git a/tests/baselines/reference/symbolType4.errors.txt b/tests/baselines/reference/symbolType4.errors.txt index 210fe94b8d7..c2f80a29d0e 100644 --- a/tests/baselines/reference/symbolType4.errors.txt +++ b/tests/baselines/reference/symbolType4.errors.txt @@ -1,12 +1,12 @@ -tests/cases/conformance/es6/Symbols/symbolType4.ts(2,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType4.ts(3,1): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType4.ts(2,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType4.ts(3,1): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/Symbols/symbolType4.ts (2 errors) ==== var s = Symbol.for("postfix"); s++; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. s--; ~ -!!! error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/symbolType5.errors.txt b/tests/baselines/reference/symbolType5.errors.txt index af70aad0f26..49e2c87cca4 100644 --- a/tests/baselines/reference/symbolType5.errors.txt +++ b/tests/baselines/reference/symbolType5.errors.txt @@ -1,34 +1,34 @@ -tests/cases/conformance/es6/Symbols/symbolType5.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(2,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(3,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType5.ts(7,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(2,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(3,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType5.ts(7,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/Symbols/symbolType5.ts (8 errors) ==== var s = Symbol.for("multiply"); s * s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s / s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s % s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s * 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 0 / s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/symbolType6.errors.txt b/tests/baselines/reference/symbolType6.errors.txt index 42940ac1961..a49a4d9d6a3 100644 --- a/tests/baselines/reference/symbolType6.errors.txt +++ b/tests/baselines/reference/symbolType6.errors.txt @@ -1,14 +1,14 @@ tests/cases/conformance/es6/Symbols/symbolType6.ts(3,1): error TS2365: Operator '+' cannot be applied to types 'symbol' and 'symbol'. -tests/cases/conformance/es6/Symbols/symbolType6.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType6.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType6.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType6.ts(4,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es6/Symbols/symbolType6.ts(5,1): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType6.ts(6,1): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType6.ts(7,1): error TS2365: Operator '+' cannot be applied to types 'symbol' and '0'. tests/cases/conformance/es6/Symbols/symbolType6.ts(8,6): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType6.ts(9,5): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType6.ts(10,1): error TS2365: Operator '+' cannot be applied to types '0' and 'symbol'. -tests/cases/conformance/es6/Symbols/symbolType6.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType6.ts(12,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType6.ts(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType6.ts(12,5): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es6/Symbols/symbolType6.ts(14,1): error TS2469: The '+' operator cannot be applied to type 'symbol'. tests/cases/conformance/es6/Symbols/symbolType6.ts(15,6): error TS2469: The '+' operator cannot be applied to type 'symbol'. @@ -21,9 +21,9 @@ tests/cases/conformance/es6/Symbols/symbolType6.ts(15,6): error TS2469: The '+' !!! error TS2365: Operator '+' cannot be applied to types 'symbol' and 'symbol'. s - s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s + ""; ~ !!! error TS2469: The '+' operator cannot be applied to type 'symbol'. @@ -44,10 +44,10 @@ tests/cases/conformance/es6/Symbols/symbolType6.ts(15,6): error TS2469: The '+' !!! error TS2365: Operator '+' cannot be applied to types '0' and 'symbol'. s - 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. 0 - s; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (s || "") + ""; ~~~~~~~~~ diff --git a/tests/baselines/reference/symbolType7.errors.txt b/tests/baselines/reference/symbolType7.errors.txt index 80ecd2486ff..08877eb0594 100644 --- a/tests/baselines/reference/symbolType7.errors.txt +++ b/tests/baselines/reference/symbolType7.errors.txt @@ -1,37 +1,37 @@ -tests/cases/conformance/es6/Symbols/symbolType7.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(2,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(4,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(6,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/Symbols/symbolType7.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(2,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(2,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(3,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(4,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(4,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(5,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(6,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(6,7): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/Symbols/symbolType7.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/Symbols/symbolType7.ts (9 errors) ==== var s = Symbol.for("shift"); s << s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s << 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >> s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >> 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>> s; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. s >>> 0; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt index 261eb6bd558..394f6e87523 100644 --- a/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt +++ b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt @@ -1,399 +1,399 @@ -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts (96 errors) ==== var a = 1 - `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b = 1 - `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c = 1 - `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d = 1 - `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = `${ 3 }` - 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f = `2${ 3 }` - 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g = `${ 3 }4` - 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h = `2${ 3 }4` - 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a2 = 1 * `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b2 = 1 * `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c2 = 1 * `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d2 = 1 * `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e2 = `${ 3 }` * 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f2 = `2${ 3 }` * 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g2 = `${ 3 }4` * 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h2 = `2${ 3 }4` * 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a3 = 1 & `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b3 = 1 & `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c3 = 1 & `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d3 = 1 & `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e3 = `${ 3 }` & 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f3 = `2${ 3 }` & 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g3 = `${ 3 }4` & 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h3 = `2${ 3 }4` & 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a4 = 1 - `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b4 = 1 - `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c4 = 1 - `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d4 = 1 - `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e4 = `${ 3 - 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f4 = `2${ 3 - 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g4 = `${ 3 - 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h4 = `2${ 3 - 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a5 = 1 - `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b5 = 1 - `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c5 = 1 - `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d5 = 1 - `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e5 = `${ 3 * 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f5 = `2${ 3 * 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g5 = `${ 3 * 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h5 = `2${ 3 * 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a6 = 1 - `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b6 = 1 - `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c6 = 1 - `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d6 = 1 - `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e6 = `${ 3 & 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f6 = `2${ 3 & 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g6 = `${ 3 & 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h6 = `2${ 3 & 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a7 = 1 * `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b7 = 1 * `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c7 = 1 * `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d7 = 1 * `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e7 = `${ 3 - 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f7 = `2${ 3 - 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g7 = `${ 3 - 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h7 = `2${ 3 - 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a8 = 1 * `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b8 = 1 * `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c8 = 1 * `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d8 = 1 * `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e8 = `${ 3 * 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f8 = `2${ 3 * 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g8 = `${ 3 * 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h8 = `2${ 3 * 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a9 = 1 * `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b9 = 1 * `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c9 = 1 * `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d9 = 1 * `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e9 = `${ 3 & 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f9 = `2${ 3 & 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g9 = `${ 3 & 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h9 = `2${ 3 & 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var aa = 1 & `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ba = 1 & `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ca = 1 & `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var da = 1 & `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ea = `${ 3 - 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fa = `2${ 3 - 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ga = `${ 3 - 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ha = `2${ 3 - 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ab = 1 & `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var bb = 1 & `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var cb = 1 & `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var db = 1 & `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var eb = `${ 3 * 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fb = `2${ 3 * 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var gb = `${ 3 * 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var hb = `2${ 3 * 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ac = 1 & `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var bc = 1 & `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var cc = 1 & `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var dc = 1 & `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ec = `${ 3 & 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fc = `2${ 3 & 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var gc = `${ 3 & 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var hc = `2${ 3 & 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt b/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt index 8a6a9719a57..502040d0626 100644 --- a/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt +++ b/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt @@ -1,399 +1,399 @@ -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts (96 errors) ==== var a = 1 - `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b = 1 - `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c = 1 - `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d = 1 - `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = `${ 3 }` - 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f = `2${ 3 }` - 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g = `${ 3 }4` - 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h = `2${ 3 }4` - 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a2 = 1 * `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b2 = 1 * `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c2 = 1 * `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d2 = 1 * `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e2 = `${ 3 }` * 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f2 = `2${ 3 }` * 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g2 = `${ 3 }4` * 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h2 = `2${ 3 }4` * 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a3 = 1 & `${ 3 }`; ~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b3 = 1 & `2${ 3 }`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c3 = 1 & `${ 3 }4`; ~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d3 = 1 & `2${ 3 }4`; ~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e3 = `${ 3 }` & 5; ~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f3 = `2${ 3 }` & 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g3 = `${ 3 }4` & 5; ~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h3 = `2${ 3 }4` & 5; ~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a4 = 1 - `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b4 = 1 - `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c4 = 1 - `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d4 = 1 - `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e4 = `${ 3 - 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f4 = `2${ 3 - 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g4 = `${ 3 - 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h4 = `2${ 3 - 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a5 = 1 - `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b5 = 1 - `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c5 = 1 - `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d5 = 1 - `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e5 = `${ 3 * 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f5 = `2${ 3 * 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g5 = `${ 3 * 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h5 = `2${ 3 * 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a6 = 1 - `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b6 = 1 - `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c6 = 1 - `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d6 = 1 - `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e6 = `${ 3 & 4 }` - 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f6 = `2${ 3 & 4 }` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g6 = `${ 3 & 4 }5` - 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h6 = `2${ 3 & 4 }5` - 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a7 = 1 * `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b7 = 1 * `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c7 = 1 * `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d7 = 1 * `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e7 = `${ 3 - 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f7 = `2${ 3 - 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g7 = `${ 3 - 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h7 = `2${ 3 - 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a8 = 1 * `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b8 = 1 * `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c8 = 1 * `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d8 = 1 * `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e8 = `${ 3 * 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f8 = `2${ 3 * 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g8 = `${ 3 * 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h8 = `2${ 3 * 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var a9 = 1 * `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var b9 = 1 * `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var c9 = 1 * `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var d9 = 1 * `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e9 = `${ 3 & 4 }` * 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var f9 = `2${ 3 & 4 }` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var g9 = `${ 3 & 4 }5` * 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var h9 = `2${ 3 & 4 }5` * 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var aa = 1 & `${ 3 - 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ba = 1 & `2${ 3 - 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ca = 1 & `${ 3 - 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var da = 1 & `2${ 3 - 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ea = `${ 3 - 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fa = `2${ 3 - 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ga = `${ 3 - 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ha = `2${ 3 - 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ab = 1 & `${ 3 * 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var bb = 1 & `2${ 3 * 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var cb = 1 & `${ 3 * 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var db = 1 & `2${ 3 * 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var eb = `${ 3 * 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fb = `2${ 3 * 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var gb = `${ 3 * 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var hb = `2${ 3 * 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ac = 1 & `${ 3 & 4 }`; ~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var bc = 1 & `2${ 3 & 4 }`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var cc = 1 & `${ 3 & 4 }5`; ~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var dc = 1 & `2${ 3 & 4 }5`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var ec = `${ 3 & 4 }` & 6; ~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var fc = `2${ 3 & 4 }` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var gc = `${ 3 & 4 }5` & 6; ~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var hc = `2${ 3 & 4 }5` & 6; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInDivision.errors.txt b/tests/baselines/reference/templateStringInDivision.errors.txt index 32cc4830399..9a6674b7b80 100644 --- a/tests/baselines/reference/templateStringInDivision.errors.txt +++ b/tests/baselines/reference/templateStringInDivision.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/templates/templateStringInDivision.ts(1,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringInDivision.ts(1,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringInDivision.ts (1 errors) ==== var x = `abc${ 1 }def` / 1; ~~~~~~~~~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInModulo.errors.txt b/tests/baselines/reference/templateStringInModulo.errors.txt index f9f0b0257d6..c7861a4ef89 100644 --- a/tests/baselines/reference/templateStringInModulo.errors.txt +++ b/tests/baselines/reference/templateStringInModulo.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/templates/templateStringInModulo.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringInModulo.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringInModulo.ts (1 errors) ==== var x = 1 % `abc${ 1 }def`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInModuloES6.errors.txt b/tests/baselines/reference/templateStringInModuloES6.errors.txt index db410876b91..bb700c79c4c 100644 --- a/tests/baselines/reference/templateStringInModuloES6.errors.txt +++ b/tests/baselines/reference/templateStringInModuloES6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/templates/templateStringInModuloES6.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringInModuloES6.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringInModuloES6.ts (1 errors) ==== var x = 1 % `abc${ 1 }def`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInMultiplication.errors.txt b/tests/baselines/reference/templateStringInMultiplication.errors.txt index 11a4ea9985e..cc602fb611b 100644 --- a/tests/baselines/reference/templateStringInMultiplication.errors.txt +++ b/tests/baselines/reference/templateStringInMultiplication.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/templates/templateStringInMultiplication.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringInMultiplication.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringInMultiplication.ts (1 errors) ==== var x = 1 * `abc${ 1 }def`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInMultiplicationES6.errors.txt b/tests/baselines/reference/templateStringInMultiplicationES6.errors.txt index ee27091778f..3bd9c5bb557 100644 --- a/tests/baselines/reference/templateStringInMultiplicationES6.errors.txt +++ b/tests/baselines/reference/templateStringInMultiplicationES6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/templates/templateStringInMultiplicationES6.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringInMultiplicationES6.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/templates/templateStringInMultiplicationES6.ts (1 errors) ==== var x = 1 * `abc${ 1 }def`; ~~~~~~~~~~~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt index 0607a01a11c..e83b588ef76 100644 --- a/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt +++ b/tests/baselines/reference/tsxAttributeInvalidNames.errors.txt @@ -1,11 +1,11 @@ tests/cases/conformance/jsx/file.tsx(10,8): error TS1003: Identifier expected. tests/cases/conformance/jsx/file.tsx(10,10): error TS1005: ';' expected. tests/cases/conformance/jsx/file.tsx(10,10): error TS2304: Cannot find name 'data'. -tests/cases/conformance/jsx/file.tsx(10,15): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/jsx/file.tsx(10,15): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/jsx/file.tsx(10,18): error TS1005: ':' expected. tests/cases/conformance/jsx/file.tsx(10,21): error TS1109: Expression expected. tests/cases/conformance/jsx/file.tsx(10,22): error TS1109: Expression expected. -tests/cases/conformance/jsx/file.tsx(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/jsx/file.tsx(11,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/jsx/file.tsx(11,8): error TS1003: Identifier expected. tests/cases/conformance/jsx/file.tsx(11,9): error TS2304: Cannot find name 'data'. tests/cases/conformance/jsx/file.tsx(11,13): error TS1005: ';' expected. @@ -30,7 +30,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular ~~~~ !!! error TS2304: Cannot find name 'data'. ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ !!! error TS1005: ':' expected. ~ @@ -39,7 +39,7 @@ tests/cases/conformance/jsx/file.tsx(11,20): error TS1161: Unterminated regular !!! error TS1109: Expression expected. ; ~~~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ !!! error TS1003: Identifier expected. ~~~~ diff --git a/tests/baselines/reference/typeGuardsDefeat.errors.txt b/tests/baselines/reference/typeGuardsDefeat.errors.txt index d4006711d45..f5f6f611ee4 100644 --- a/tests/baselines/reference/typeGuardsDefeat.errors.txt +++ b/tests/baselines/reference/typeGuardsDefeat.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(21,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(21,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,23): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(21,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(21,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,23): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts (4 errors) ==== @@ -27,9 +27,9 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,27): error var f = function () { return x * x; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. }; } x = "hello"; @@ -42,9 +42,9 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsDefeat.ts(32,27): error else { var f = () => x * x; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } x = "hello"; f(); From ac2a118f075f9382cc84c6fee94fdee24835d058 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 14:02:44 -0700 Subject: [PATCH 211/262] Add bigint type --- src/compiler/checker.ts | 245 ++++++++++++++++++++++++-------- src/compiler/factory.ts | 11 +- src/compiler/transformers/ts.ts | 3 + src/compiler/types.ts | 82 ++++++----- src/compiler/utilities.ts | 2 + src/services/completions.ts | 9 +- 6 files changed, 254 insertions(+), 98 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e50239e622f..5e03f1b3987 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -403,6 +403,7 @@ namespace ts { const nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsWideningType, "null"); const stringType = createIntrinsicType(TypeFlags.String, "string"); const numberType = createIntrinsicType(TypeFlags.Number, "number"); + const bigintType = createIntrinsicType(TypeFlags.BigInt, "bigint"); const falseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; const regularFalseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; @@ -427,6 +428,7 @@ namespace ts { const nonPrimitiveType = createIntrinsicType(TypeFlags.NonPrimitive, "object"); const stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); const keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; + const numberOrBigIntType = getUnionType([numberType, bigintType]); const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -518,6 +520,7 @@ namespace ts { let deferredGlobalTemplateStringsArrayType: ObjectType; let deferredGlobalImportMetaType: ObjectType; let deferredGlobalExtractSymbol: Symbol; + let deferredGlobalBigIntType: ObjectType; const allPotentiallyUnusedIdentifiers = createMap(); // key is file name @@ -528,6 +531,7 @@ namespace ts { const emptyStringType = getLiteralType(""); const zeroType = getLiteralType(0); + const zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" }); const resolutionTargets: TypeSystemEntity[] = []; const resolutionResults: boolean[] = []; @@ -556,31 +560,33 @@ namespace ts { None = 0, TypeofEQString = 1 << 0, // typeof x === "string" TypeofEQNumber = 1 << 1, // typeof x === "number" - TypeofEQBoolean = 1 << 2, // typeof x === "boolean" - TypeofEQSymbol = 1 << 3, // typeof x === "symbol" - TypeofEQObject = 1 << 4, // typeof x === "object" - TypeofEQFunction = 1 << 5, // typeof x === "function" - TypeofEQHostObject = 1 << 6, // typeof x === "xxx" - TypeofNEString = 1 << 7, // typeof x !== "string" - TypeofNENumber = 1 << 8, // typeof x !== "number" - TypeofNEBoolean = 1 << 9, // typeof x !== "boolean" - TypeofNESymbol = 1 << 10, // typeof x !== "symbol" - TypeofNEObject = 1 << 11, // typeof x !== "object" - TypeofNEFunction = 1 << 12, // typeof x !== "function" - TypeofNEHostObject = 1 << 13, // typeof x !== "xxx" - EQUndefined = 1 << 14, // x === undefined - EQNull = 1 << 15, // x === null - EQUndefinedOrNull = 1 << 16, // x === undefined / x === null - NEUndefined = 1 << 17, // x !== undefined - NENull = 1 << 18, // x !== null - NEUndefinedOrNull = 1 << 19, // x != undefined / x != null - Truthy = 1 << 20, // x - Falsy = 1 << 21, // !x - All = (1 << 22) - 1, + TypeofEQBigInt = 1 << 2, // typeof x === "bigint" + TypeofEQBoolean = 1 << 3, // typeof x === "boolean" + TypeofEQSymbol = 1 << 4, // typeof x === "symbol" + TypeofEQObject = 1 << 5, // typeof x === "object" + TypeofEQFunction = 1 << 6, // typeof x === "function" + TypeofEQHostObject = 1 << 7, // typeof x === "xxx" + TypeofNEString = 1 << 8, // typeof x !== "string" + TypeofNENumber = 1 << 9, // typeof x !== "number" + TypeofNEBigInt = 1 << 10, // typeof x !== "bigint" + TypeofNEBoolean = 1 << 11, // typeof x !== "boolean" + TypeofNESymbol = 1 << 12, // typeof x !== "symbol" + TypeofNEObject = 1 << 13, // typeof x !== "object" + TypeofNEFunction = 1 << 14, // typeof x !== "function" + TypeofNEHostObject = 1 << 15, // typeof x !== "xxx" + EQUndefined = 1 << 16, // x === undefined + EQNull = 1 << 17, // x === null + EQUndefinedOrNull = 1 << 18, // x === undefined / x === null + NEUndefined = 1 << 19, // x !== undefined + NENull = 1 << 20, // x !== null + NEUndefinedOrNull = 1 << 21, // x != undefined / x != null + Truthy = 1 << 22, // x + Falsy = 1 << 23, // !x + All = (1 << 24) - 1, // The following members encode facts about particular kinds of types for use in the getTypeFacts function. // The presence of a particular fact means that the given test is true for some (and possibly all) values // of that kind of type. - BaseStringStrictFacts = TypeofEQString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseStringStrictFacts = TypeofEQString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseStringFacts = BaseStringStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, StringStrictFacts = BaseStringStrictFacts | Truthy | Falsy, StringFacts = BaseStringFacts | Truthy, @@ -588,15 +594,23 @@ namespace ts { EmptyStringFacts = BaseStringFacts, NonEmptyStringStrictFacts = BaseStringStrictFacts | Truthy, NonEmptyStringFacts = BaseStringFacts | Truthy, - BaseNumberStrictFacts = TypeofEQNumber | TypeofNEString | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseNumberStrictFacts = TypeofEQNumber | TypeofNEString | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseNumberFacts = BaseNumberStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, NumberStrictFacts = BaseNumberStrictFacts | Truthy | Falsy, NumberFacts = BaseNumberFacts | Truthy, - ZeroStrictFacts = BaseNumberStrictFacts | Falsy, - ZeroFacts = BaseNumberFacts, - NonZeroStrictFacts = BaseNumberStrictFacts | Truthy, - NonZeroFacts = BaseNumberFacts | Truthy, - BaseBooleanStrictFacts = TypeofEQBoolean | TypeofNEString | TypeofNENumber | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + ZeroNumberStrictFacts = BaseNumberStrictFacts | Falsy, + ZeroNumberFacts = BaseNumberFacts, + NonZeroNumberStrictFacts = BaseNumberStrictFacts | Truthy, + NonZeroNumberFacts = BaseNumberFacts | Truthy, + BaseBigIntStrictFacts = TypeofEQBigInt | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, + BaseBigIntFacts = BaseBigIntStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, + BigIntStrictFacts = BaseBigIntStrictFacts | Truthy | Falsy, + BigIntFacts = BaseBigIntFacts | Truthy, + ZeroBigIntStrictFacts = BaseBigIntStrictFacts | Falsy, + ZeroBigIntFacts = BaseBigIntFacts, + NonZeroBigIntStrictFacts = BaseBigIntStrictFacts | Truthy, + NonZeroBigIntFacts = BaseBigIntFacts | Truthy, + BaseBooleanStrictFacts = TypeofEQBoolean | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull, BaseBooleanFacts = BaseBooleanStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, BooleanStrictFacts = BaseBooleanStrictFacts | Truthy | Falsy, BooleanFacts = BaseBooleanFacts | Truthy, @@ -604,14 +618,14 @@ namespace ts { FalseFacts = BaseBooleanFacts, TrueStrictFacts = BaseBooleanStrictFacts | Truthy, TrueFacts = BaseBooleanFacts | Truthy, - SymbolStrictFacts = TypeofEQSymbol | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + SymbolStrictFacts = TypeofEQSymbol | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, SymbolFacts = SymbolStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - ObjectStrictFacts = TypeofEQObject | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + ObjectStrictFacts = TypeofEQObject | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | NEUndefined | NENull | NEUndefinedOrNull | Truthy, ObjectFacts = ObjectStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - FunctionStrictFacts = TypeofEQFunction | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, + FunctionStrictFacts = TypeofEQFunction | TypeofEQHostObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | NEUndefined | NENull | NEUndefinedOrNull | Truthy, FunctionFacts = FunctionStrictFacts | EQUndefined | EQNull | EQUndefinedOrNull | Falsy, - UndefinedFacts = TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | EQUndefined | EQUndefinedOrNull | NENull | Falsy, - NullFacts = TypeofEQObject | TypeofNEString | TypeofNENumber | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | TypeofNEHostObject | EQNull | EQUndefinedOrNull | NEUndefined | Falsy, + UndefinedFacts = TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEObject | TypeofNEFunction | TypeofNEHostObject | EQUndefined | EQUndefinedOrNull | NENull | Falsy, + NullFacts = TypeofEQObject | TypeofNEString | TypeofNENumber | TypeofNEBigInt | TypeofNEBoolean | TypeofNESymbol | TypeofNEFunction | TypeofNEHostObject | EQNull | EQUndefinedOrNull | NEUndefined | Falsy, EmptyObjectStrictFacts = All & ~(EQUndefined | EQNull | EQUndefinedOrNull), EmptyObjectFacts = All, } @@ -619,6 +633,7 @@ namespace ts { const typeofEQFacts = createMapFromTemplate({ string: TypeFacts.TypeofEQString, number: TypeFacts.TypeofEQNumber, + bigint: TypeFacts.TypeofEQBigInt, boolean: TypeFacts.TypeofEQBoolean, symbol: TypeFacts.TypeofEQSymbol, undefined: TypeFacts.EQUndefined, @@ -628,6 +643,7 @@ namespace ts { const typeofNEFacts = createMapFromTemplate({ string: TypeFacts.TypeofNEString, number: TypeFacts.TypeofNENumber, + bigint: TypeFacts.TypeofNEBigInt, boolean: TypeFacts.TypeofNEBoolean, symbol: TypeFacts.TypeofNESymbol, undefined: TypeFacts.NEUndefined, @@ -637,6 +653,7 @@ namespace ts { const typeofTypesByName = createMapFromTemplate({ string: stringType, number: numberType, + bigint: bigintType, boolean: booleanType, symbol: esSymbolType, undefined: undefinedType @@ -3217,6 +3234,10 @@ namespace ts { context.approximateLength += 6; return createKeywordTypeNode(SyntaxKind.NumberKeyword); } + if (type.flags & TypeFlags.BigInt) { + context.approximateLength += 6; + return createKeywordTypeNode(SyntaxKind.BigIntKeyword); + } if (type.flags & TypeFlags.Boolean) { context.approximateLength += 7; return createKeywordTypeNode(SyntaxKind.BooleanKeyword); @@ -3243,6 +3264,10 @@ namespace ts { context.approximateLength += (("" + (type).value).length); return createLiteralTypeNode((createLiteral((type).value))); } + if (type.flags & TypeFlags.BigIntLiteral) { + context.approximateLength += (pseudoBigIntToString((type).value).length) + 1; + return createLiteralTypeNode((createLiteral((type).value))); + } if (type.flags & TypeFlags.BooleanLiteral) { context.approximateLength += (type).intrinsicName.length; return (type).intrinsicName === "true" ? createTrue() : createFalse(); @@ -6066,6 +6091,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.ObjectKeyword: @@ -7313,6 +7339,7 @@ namespace ts { t.flags & TypeFlags.Intersection ? getApparentTypeOfIntersectionType(t) : t.flags & TypeFlags.StringLike ? globalStringType : t.flags & TypeFlags.NumberLike ? globalNumberType : + t.flags & TypeFlags.BigIntLike ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= ScriptTarget.ESNext) : t.flags & TypeFlags.BooleanLike ? globalBooleanType : t.flags & TypeFlags.ESSymbolLike ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= ScriptTarget.ES2015) : t.flags & TypeFlags.NonPrimitive ? emptyObjectType : @@ -8650,6 +8677,10 @@ namespace ts { return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract" as __String, SymbolFlags.TypeAlias, Diagnostics.Cannot_find_global_type_0)!); // TODO: GH#18217 } + function getGlobalBigIntType(reportErrors: boolean) { + return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; + } + /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -8830,6 +8861,7 @@ namespace ts { combined & TypeFlags.NonPrimitive && combined & (TypeFlags.DisjointDomains & ~TypeFlags.NonPrimitive) || combined & TypeFlags.StringLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.StringLike) || combined & TypeFlags.NumberLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.NumberLike) || + combined & TypeFlags.BigIntLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.BigIntLike) || combined & TypeFlags.ESSymbolLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.ESSymbolLike) || combined & TypeFlags.VoidLike && combined & (TypeFlags.DisjointDomains & ~TypeFlags.VoidLike)) { return true; @@ -8922,6 +8954,7 @@ namespace ts { const remove = t.flags & TypeFlags.StringLiteral && includes & TypeFlags.String || t.flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || + t.flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || t.flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || t.flags & TypeFlags.Literal && t.flags & TypeFlags.FreshLiteral && containsType(types, (t).regularType); if (remove) { @@ -9079,6 +9112,7 @@ namespace ts { const remove = t.flags & TypeFlags.String && includes & TypeFlags.StringLiteral || t.flags & TypeFlags.Number && includes & TypeFlags.NumberLiteral || + t.flags & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || t.flags & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol; if (remove) { orderedRemoveItemAt(types, i); @@ -9094,6 +9128,7 @@ namespace ts { if (!containsType(u.types, type)) { const primitive = type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.UniqueESSymbol ? esSymbolType : undefined; if (!primitive || !containsType(u.types, primitive)) { @@ -9170,6 +9205,7 @@ namespace ts { } if (includes & TypeFlags.String && includes & TypeFlags.StringLiteral || includes & TypeFlags.Number && includes & TypeFlags.NumberLiteral || + includes & TypeFlags.BigInt && includes & TypeFlags.BigIntLiteral || includes & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol) { removeRedundantPrimitiveTypes(typeSet, includes); } @@ -9232,13 +9268,24 @@ namespace ts { type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } + function getNumericLiteralValue(node: NumericLiteral): number | PseudoBigInt { + if (node.numericLiteralFlags & TokenFlags.BigInt) { + return { negative: false, base10Value: parsePseudoBigInt(node.text) }; + } + return +node.text; + } + + function getNumericLiteralType(node: NumericLiteral): LiteralType { + return getLiteralType(getNumericLiteralValue(node)); + } + function getLiteralTypeFromPropertyName(prop: Symbol, include: TypeFlags) { if (!(getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier)) { let type = getLateBoundSymbol(prop).nameType; if (!type && !isKnownSymbol(prop)) { const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration); - type = name && isNumericLiteral(name) ? getLiteralType(+name.text) : - name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : + type = name && isNumericLiteral(name) ? getNumericLiteralType(name) : + name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getNumericLiteralType(name.expression) : getLiteralType(symbolName(prop)); } if (type && type.flags & include) { @@ -9860,7 +9907,7 @@ namespace ts { if (right.flags & TypeFlags.Union) { return mapType(right, t => getSpreadType(left, t, symbol, typeFlags, objectFlags)); } - if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) { + if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) { return left; } @@ -9968,7 +10015,7 @@ namespace ts { return index; } - function createLiteralType(flags: TypeFlags, value: string | number, symbol: Symbol | undefined) { + function createLiteralType(flags: TypeFlags, value: string | number | PseudoBigInt, symbol: Symbol | undefined) { const type = createType(flags); type.symbol = symbol!; type.value = value; @@ -9993,16 +10040,18 @@ namespace ts { type; } - function getLiteralType(value: string | number, enumId?: number, symbol?: Symbol) { + function getLiteralType(value: string | number | PseudoBigInt, enumId?: number, symbol?: Symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where // EEE is a unique id for the containing enum type. - const qualifier = typeof value === "number" ? "#" : "@"; - const key = enumId ? enumId + qualifier + value : qualifier + value; + const qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n"; + const key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? pseudoBigIntToString(value) : value); let type = literalTypes.get(key); if (!type) { - const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : TypeFlags.StringLiteral) | (enumId ? TypeFlags.EnumLiteral : 0); + const flags = (typeof value === "number" ? TypeFlags.NumberLiteral : + typeof value === "string" ? TypeFlags.StringLiteral : TypeFlags.BigIntLiteral) | + (enumId ? TypeFlags.EnumLiteral : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; @@ -10064,6 +10113,8 @@ namespace ts { return stringType; case SyntaxKind.NumberKeyword: return numberType; + case SyntaxKind.BigIntKeyword: + return bigintType; case SyntaxKind.BooleanKeyword: return booleanType; case SyntaxKind.SymbolKeyword: @@ -11247,6 +11298,7 @@ namespace ts { if (s & TypeFlags.NumberLiteral && s & TypeFlags.EnumLiteral && t & TypeFlags.NumberLiteral && !(t & TypeFlags.EnumLiteral) && (source).value === (target).value) return true; + if (s & TypeFlags.BigIntLike && t & TypeFlags.BigInt) return true; if (s & TypeFlags.BooleanLike && t & TypeFlags.Boolean) return true; if (s & TypeFlags.ESSymbolLike && t & TypeFlags.ESSymbol) return true; if (s & TypeFlags.Enum && t & TypeFlags.Enum && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; @@ -13036,6 +13088,7 @@ namespace ts { return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral ? stringType : type.flags & TypeFlags.NumberLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : type; @@ -13045,6 +13098,7 @@ namespace ts { return type.flags & TypeFlags.EnumLiteral && type.flags & TypeFlags.FreshLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : + type.flags & TypeFlags.BigIntLiteral && type.flags & TypeFlags.FreshLiteral ? bigintType : type.flags & TypeFlags.BooleanLiteral && type.flags & TypeFlags.FreshLiteral ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; @@ -13084,6 +13138,10 @@ namespace ts { return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); } + function isZeroBigInt({value}: BigIntLiteralType) { + return value.base10Value === "0"; + } + function getFalsyFlagsOfTypes(types: Type[]): TypeFlags { let result: TypeFlags = 0; for (const t of types) { @@ -13099,6 +13157,7 @@ namespace ts { return type.flags & TypeFlags.Union ? getFalsyFlagsOfTypes((type).types) : type.flags & TypeFlags.StringLiteral ? (type).value === "" ? TypeFlags.StringLiteral : 0 : type.flags & TypeFlags.NumberLiteral ? (type).value === 0 ? TypeFlags.NumberLiteral : 0 : + type.flags & TypeFlags.BigIntLiteral ? isZeroBigInt(type) ? TypeFlags.BigIntLiteral : 0 : type.flags & TypeFlags.BooleanLiteral ? (type === falseType || type === regularFalseType) ? TypeFlags.BooleanLiteral : 0 : type.flags & TypeFlags.PossiblyFalsy; } @@ -13116,11 +13175,13 @@ namespace ts { function getDefinitelyFalsyPartOfType(type: Type): Type { return type.flags & TypeFlags.String ? emptyStringType : type.flags & TypeFlags.Number ? zeroType : + type.flags & TypeFlags.BigInt ? zeroBigIntType : type === regularFalseType || type === falseType || type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Null) || type.flags & TypeFlags.StringLiteral && (type).value === "" || - type.flags & TypeFlags.NumberLiteral && (type).value === 0 ? type : + type.flags & TypeFlags.NumberLiteral && (type).value === 0 || + type.flags & TypeFlags.BigIntLiteral && isZeroBigInt(type) ? type : neverType; } @@ -14498,8 +14559,17 @@ namespace ts { if (flags & TypeFlags.NumberLiteral) { const isZero = (type).value === 0; return strictNullChecks ? - isZero ? TypeFacts.ZeroStrictFacts : TypeFacts.NonZeroStrictFacts : - isZero ? TypeFacts.ZeroFacts : TypeFacts.NonZeroFacts; + isZero ? TypeFacts.ZeroNumberStrictFacts : TypeFacts.NonZeroNumberStrictFacts : + isZero ? TypeFacts.ZeroNumberFacts : TypeFacts.NonZeroNumberFacts; + } + if (flags & TypeFlags.BigInt) { + return strictNullChecks ? TypeFacts.BigIntStrictFacts : TypeFacts.BigIntFacts; + } + if (flags & TypeFlags.BigIntLiteral) { + const isZero = isZeroBigInt(type); + return strictNullChecks ? + isZero ? TypeFacts.ZeroBigIntStrictFacts : TypeFacts.NonZeroBigIntStrictFacts : + isZero ? TypeFacts.ZeroBigIntFacts : TypeFacts.NonZeroBigIntFacts; } if (flags & TypeFlags.Boolean) { return strictNullChecks ? TypeFacts.BooleanStrictFacts : TypeFacts.BooleanFacts; @@ -14810,10 +14880,12 @@ namespace ts { // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) { if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral)) { + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral) || + isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.BigIntLiteral)) { return mapType(typeWithPrimitives, t => t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) : t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t.flags & TypeFlags.BigInt ? extractTypesOfKind(typeWithLiterals, TypeFlags.BigInt | TypeFlags.BigIntLiteral) : t); } return typeWithPrimitives; @@ -21282,7 +21354,7 @@ namespace ts { } function checkArithmeticOperandType(operand: Node, type: Type, diagnostic: DiagnosticMessage): boolean { - if (!isTypeAssignableToKind(type, TypeFlags.NumberLike)) { + if (!isTypeAssignableTo(type, numberOrBigIntType)) { error(operand, diagnostic); return false; } @@ -21430,10 +21502,19 @@ namespace ts { } if (node.operand.kind === SyntaxKind.NumericLiteral) { if (node.operator === SyntaxKind.MinusToken) { - return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); + const value = getNumericLiteralValue(node.operand as NumericLiteral); + return getFreshTypeOfLiteralType(getLiteralType( + // Keep number as number, bigint as bigint + typeof value === "number" + ? -value + : { negative: !value.negative, base10Value: value.base10Value } + )); } else if (node.operator === SyntaxKind.PlusToken) { - return getFreshTypeOfLiteralType(getLiteralType(+(node.operand).text)); + if (isTypeAssignableToKind(operandType, TypeFlags.BigIntLike)) { + error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(operandType)); + } + return getFreshTypeOfLiteralType(getNumericLiteralType(node.operand as NumericLiteral)); } } switch (node.operator) { @@ -21444,7 +21525,13 @@ namespace ts { if (maybeTypeOfKind(operandType, TypeFlags.ESSymbolLike)) { error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator)); } - return numberType; + if (node.operator === SyntaxKind.PlusToken) { + if (maybeTypeOfKind(operandType, TypeFlags.BigIntLike)) { + error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(operandType)); + } + return numberType; + } + return getUnaryResultType(operandType); case SyntaxKind.ExclamationToken: checkTruthinessExpression(node.operand); const facts = getTypeFacts(operandType) & (TypeFacts.Truthy | TypeFacts.Falsy); @@ -21459,7 +21546,7 @@ namespace ts { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } - return numberType; + return getUnaryResultType(operandType); } return errorType; } @@ -21477,6 +21564,16 @@ namespace ts { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); } + return getUnaryResultType(operandType); + } + + function getUnaryResultType(operandType: Type): Type { + if (maybeTypeOfKind(operandType, TypeFlags.BigIntLike)) { + return isTypeAssignableToKind(operandType, TypeFlags.AnyOrUnknown) || maybeTypeOfKind(operandType, TypeFlags.NumberLike) + ? numberOrBigIntType + : bigintType; + } + // If it's not a bigint type, implicit coercion will result in a number return numberType; } @@ -21505,6 +21602,7 @@ namespace ts { return false; } return !!(kind & TypeFlags.NumberLike) && isTypeAssignableTo(source, numberType) || + !!(kind & TypeFlags.BigIntLike) && isTypeAssignableTo(source, bigintType) || !!(kind & TypeFlags.StringLike) && isTypeAssignableTo(source, stringType) || !!(kind & TypeFlags.BooleanLike) && isTypeAssignableTo(source, booleanType) || !!(kind & TypeFlags.Void) && isTypeAssignableTo(source, voidType) || @@ -21869,17 +21967,39 @@ namespace ts { (rightType.flags & TypeFlags.BooleanLike) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator)); + return numberType; } else { // otherwise just check each operand separately and report errors as normal const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); + let resultType: Type; + // If both are any or unknown, allow operation; assume it will resolve to number + if ((isTypeAssignableToKind(leftType, TypeFlags.AnyOrUnknown) && isTypeAssignableToKind(rightType, TypeFlags.AnyOrUnknown)) || + // Or, if neither could be bigint, implicit coercion results in a number result + !(maybeTypeOfKind(leftType, TypeFlags.BigIntLike) || maybeTypeOfKind(rightType, TypeFlags.BigIntLike)) + ) { + resultType = numberType; } + // At least one is assignable to bigint, so both should be only assignable to bigint + else if (isTypeAssignableToKind(leftType, TypeFlags.BigIntLike) && isTypeAssignableToKind(rightType, TypeFlags.BigIntLike)) { + switch (operator) { + case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: + case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: + reportOperatorError(); + } + resultType = bigintType; + } + else { + reportOperatorError(); + resultType = errorType; + } + if (leftOk && rightOk) { + checkAssignmentOperator(resultType); + } + return resultType; } - return numberType; case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: if (leftType === silentNeverType || rightType === silentNeverType) { @@ -21897,6 +22017,10 @@ namespace ts { // If both operands are of the Number primitive type, the result is of the Number primitive type. resultType = numberType; } + else if (isTypeAssignableToKind(leftType, TypeFlags.BigIntLike, /*strict*/ true) && isTypeAssignableToKind(rightType, TypeFlags.BigIntLike, /*strict*/ true)) { + // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type. + resultType = bigintType; + } else if (isTypeAssignableToKind(leftType, TypeFlags.StringLike, /*strict*/ true) || isTypeAssignableToKind(rightType, TypeFlags.StringLike, /*strict*/ true)) { // If one or both operands are of the String primitive type, the result is of the String primitive type. resultType = stringType; @@ -21928,7 +22052,9 @@ namespace ts { if (checkForDisallowedESSymbolOperand(operator)) { leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + if (!(isTypeComparableTo(leftType, rightType) || isTypeComparableTo(rightType, leftType) || + (isTypeAssignableTo(leftType, numberOrBigIntType) && isTypeAssignableTo(rightType, numberOrBigIntType)) + )) { reportOperatorError(); } } @@ -22259,6 +22385,7 @@ namespace ts { const constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; return maybeTypeOfKind(constraint, TypeFlags.String) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || maybeTypeOfKind(constraint, TypeFlags.Number) && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + maybeTypeOfKind(constraint, TypeFlags.BigInt) && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || maybeTypeOfKind(constraint, TypeFlags.ESSymbol) && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol) || isLiteralOfContextualType(candidateType, constraint); } @@ -22266,6 +22393,7 @@ namespace ts { // literal context for all literals of that primitive type. return !!(contextualType.flags & (TypeFlags.StringLiteral | TypeFlags.Index) && maybeTypeOfKind(candidateType, TypeFlags.StringLiteral) || contextualType.flags & TypeFlags.NumberLiteral && maybeTypeOfKind(candidateType, TypeFlags.NumberLiteral) || + contextualType.flags & TypeFlags.BigIntLiteral && maybeTypeOfKind(candidateType, TypeFlags.BigIntLiteral) || contextualType.flags & TypeFlags.BooleanLiteral && maybeTypeOfKind(candidateType, TypeFlags.BooleanLiteral) || contextualType.flags & TypeFlags.UniqueESSymbol && maybeTypeOfKind(candidateType, TypeFlags.UniqueESSymbol)); } @@ -22427,7 +22555,7 @@ namespace ts { return getFreshTypeOfLiteralType(getLiteralType((node as StringLiteralLike).text)); case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(node as NumericLiteral); - return getFreshTypeOfLiteralType(getLiteralType(+(node as NumericLiteral).text)); + return getFreshTypeOfLiteralType(getNumericLiteralType(node as NumericLiteral)); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: @@ -25835,6 +25963,7 @@ namespace ts { case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -26463,7 +26592,8 @@ namespace ts { return (expr).text; case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(expr); - return +(expr).text; + const literalValue = getNumericLiteralValue(expr); + return typeof literalValue === "number" ? literalValue : undefined; // don't evaluate bigint case SyntaxKind.ParenthesizedExpression: return evaluate((expr).expression); case SyntaxKind.Identifier: @@ -28517,6 +28647,9 @@ namespace ts { else if (isTypeAssignableToKind(type, TypeFlags.NumberLike)) { return TypeReferenceSerializationKind.NumberLikeType; } + else if (isTypeAssignableToKind(type, TypeFlags.BigIntLike)) { + return TypeReferenceSerializationKind.BigIntLikeType; + } else if (isTypeAssignableToKind(type, TypeFlags.StringLike)) { return TypeReferenceSerializationKind.StringLikeType; } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 01de5850471..39d3d5c3c83 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -68,13 +68,18 @@ namespace ts { /* @internal */ export function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote: boolean): StringLiteral; // tslint:disable-line unified-signatures /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ export function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - export function createLiteral(value: number): NumericLiteral; + export function createLiteral(value: number | PseudoBigInt): NumericLiteral; export function createLiteral(value: boolean): BooleanLiteral; - export function createLiteral(value: string | number | boolean): PrimaryExpression; - export function createLiteral(value: string | number | boolean | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote?: boolean): PrimaryExpression { + export function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; + export function createLiteral(value: string | number | PseudoBigInt | boolean | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier, isSingleQuote?: boolean): PrimaryExpression { if (typeof value === "number") { return createNumericLiteral(value + ""); } + if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt + const literal = createNumericLiteral(pseudoBigIntToString(value) + "n"); + literal.numericLiteralFlags |= TokenFlags.BigInt; + return literal; + } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index a5ab1e8475f..057dfc97a74 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -2006,6 +2006,9 @@ namespace ts { case TypeReferenceSerializationKind.VoidNullableOrNeverType: return createVoidZero(); + case TypeReferenceSerializationKind.BigIntLikeType: + return createIdentifier("BigInt"); + case TypeReferenceSerializationKind.BooleanType: return createIdentifier("Boolean"); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4a25a9f9eef..d926c56dc1d 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -271,6 +271,7 @@ namespace ts { UnknownKeyword, FromKeyword, GlobalKeyword, + BigIntKeyword, OfKeyword, // LastKeyword and LastToken and LastContextualKeyword // Parse tree nodes @@ -1109,6 +1110,7 @@ namespace ts { kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword + | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword @@ -1658,8 +1660,9 @@ namespace ts { BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` OctalSpecifier = 1 << 8, // e.g. `0o777` ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` + BigInt = 1 << 10, // e.g. `123n` BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier, - NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinarySpecifier | OctalSpecifier | ContainsSeparator + NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator | BigInt } export interface NumericLiteral extends LiteralExpression { @@ -3461,6 +3464,7 @@ namespace ts { // of a type, such as the global `Promise` type in lib.d.ts). VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. NumberLikeType, // The TypeReferenceNode resolves to a Number-like type. + BigIntLikeType, // The TypeReferenceNode resolves to a BigInt-like type. StringLikeType, // The TypeReferenceNode resolves to a String-like type. BooleanType, // The TypeReferenceNode resolves to a Boolean-like type. ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type. @@ -3805,60 +3809,63 @@ namespace ts { Number = 1 << 3, Boolean = 1 << 4, Enum = 1 << 5, - StringLiteral = 1 << 6, - NumberLiteral = 1 << 7, - BooleanLiteral = 1 << 8, - EnumLiteral = 1 << 9, // Always combined with StringLiteral, NumberLiteral, or Union - ESSymbol = 1 << 10, // Type of symbol primitive introduced in ES6 - UniqueESSymbol = 1 << 11, // unique symbol - Void = 1 << 12, - Undefined = 1 << 13, - Null = 1 << 14, - Never = 1 << 15, // Never type - TypeParameter = 1 << 16, // Type parameter - Object = 1 << 17, // Object type - Union = 1 << 18, // Union (T | U) - Intersection = 1 << 19, // Intersection (T & U) - Index = 1 << 20, // keyof T - IndexedAccess = 1 << 21, // T[K] - Conditional = 1 << 22, // T extends U ? X : Y - Substitution = 1 << 23, // Type parameter substitution - NonPrimitive = 1 << 24, // intrinsic object type + BigInt = 1 << 6, + StringLiteral = 1 << 7, + NumberLiteral = 1 << 8, + BooleanLiteral = 1 << 9, + EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union + BigIntLiteral = 1 << 11, + ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 + UniqueESSymbol = 1 << 13, // unique symbol + Void = 1 << 14, + Undefined = 1 << 15, + Null = 1 << 16, + Never = 1 << 17, // Never type + TypeParameter = 1 << 18, // Type parameter + Object = 1 << 19, // Object type + Union = 1 << 20, // Union (T | U) + Intersection = 1 << 21, // Intersection (T & U) + Index = 1 << 22, // keyof T + IndexedAccess = 1 << 23, // T[K] + Conditional = 1 << 24, // T extends U ? X : Y + Substitution = 1 << 25, // Type parameter substitution + NonPrimitive = 1 << 26, // intrinsic object type /* @internal */ - FreshLiteral = 1 << 25, // Fresh literal or unique type + FreshLiteral = 1 << 27, // Fresh literal or unique type /* @internal */ - UnionOfPrimitiveTypes = 1 << 26, // Type is union of primitive types + UnionOfPrimitiveTypes = 1 << 28, // Type is union of primitive types /* @internal */ - ContainsWideningType = 1 << 27, // Type is or contains undefined or null widening type + ContainsWideningType = 1 << 29, // Type is or contains undefined or null widening type /* @internal */ - ContainsObjectLiteral = 1 << 28, // Type is or contains object literal type + ContainsObjectLiteral = 1 << 30, // Type is or contains object literal type /* @internal */ - ContainsAnyFunctionType = 1 << 29, // Type is or contains the anyFunctionType + ContainsAnyFunctionType = 1 << 31, // Type is or contains the anyFunctionType /* @internal */ AnyOrUnknown = Any | Unknown, /* @internal */ Nullable = Undefined | Null, - Literal = StringLiteral | NumberLiteral | BooleanLiteral, + Literal = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral, Unit = Literal | UniqueESSymbol | Nullable, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol, /* @internal */ - DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, - PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean, + DefinitelyFalsy = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral | Void | Undefined | Null, + PossiblyFalsy = DefinitelyFalsy | String | Number | BigInt | Boolean, /* @internal */ - Intrinsic = Any | Unknown | String | Number | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, + Intrinsic = Any | Unknown | String | Number | BigInt | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, /* @internal */ - Primitive = String | Number | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol, + Primitive = String | Number | BigInt | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol, StringLike = String | StringLiteral, NumberLike = Number | NumberLiteral | Enum, + BigIntLike = BigInt | BigIntLiteral, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, ESSymbolLike = ESSymbol | UniqueESSymbol, VoidLike = Void | Undefined, /* @internal */ - DisjointDomains = NonPrimitive | StringLike | NumberLike | BooleanLike | ESSymbolLike | VoidLike | Null, + DisjointDomains = NonPrimitive | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbolLike | VoidLike | Null, UnionOrIntersection = Union | Intersection, StructuredType = Object | Union | Intersection, TypeVariable = TypeParameter | IndexedAccess, @@ -3869,7 +3876,7 @@ namespace ts { // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, + Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, NotUnionOrUnit = Any | Unknown | ESSymbol | Object | NonPrimitive, /* @internal */ NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | StructuredOrInstantiable, @@ -3926,10 +3933,11 @@ namespace ts { // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) + // BigInt literal types (TypeFlags.BigIntLiteral) export interface LiteralType extends Type { - value: string | number; // Value of literal - freshType: LiteralType; // Fresh version of type - regularType: LiteralType; // Regular version of type + value: string | number | PseudoBigInt; // Value of literal + freshType: LiteralType; // Fresh version of type + regularType: LiteralType; // Regular version of type } // Unique symbol types (TypeFlags.UniqueESSymbol) @@ -3945,6 +3953,10 @@ namespace ts { value: number; } + export interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + // Enum types (TypeFlags.Enum) export interface EnumType extends Type { } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 34d80992153..87795492a11 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -976,6 +976,7 @@ namespace ts { case SyntaxKind.AnyKeyword: case SyntaxKind.UnknownKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: @@ -6214,6 +6215,7 @@ namespace ts { || kind === SyntaxKind.AnyKeyword || kind === SyntaxKind.UnknownKeyword || kind === SyntaxKind.NumberKeyword + || kind === SyntaxKind.BigIntKeyword || kind === SyntaxKind.ObjectKeyword || kind === SyntaxKind.BooleanKeyword || kind === SyntaxKind.StringKeyword diff --git a/src/services/completions.ts b/src/services/completions.ts index c7d888b647e..90c005d2131 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -165,8 +165,9 @@ namespace ts.Completions { }); } - const completionNameForLiteral = JSON.stringify; - function createCompletionEntryForLiteral(literal: string | number): CompletionEntry { + const completionNameForLiteral = (literal: string | number | PseudoBigInt) => + typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); + function createCompletionEntryForLiteral(literal: string | number | PseudoBigInt): CompletionEntry { return { name: completionNameForLiteral(literal), kind: ScriptElementKind.string, kindModifiers: ScriptElementKindModifier.none, sortText: "0" }; } @@ -337,7 +338,7 @@ namespace ts.Completions { readonly isJsxInitializer: IsJsxInitializer; } function getSymbolCompletionFromEntryId(program: Program, log: Log, sourceFile: SourceFile, position: number, entryId: CompletionEntryIdentifier, - ): SymbolCompletion | { type: "request", request: Request } | { type: "literal", literal: string | number } | { type: "none" } { + ): 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); if (!completionData) { @@ -502,7 +503,7 @@ namespace ts.Completions { readonly isNewIdentifierLocation: boolean; readonly location: Node | undefined; readonly keywordFilters: KeywordCompletionFilters; - readonly literals: ReadonlyArray; + readonly literals: ReadonlyArray; readonly symbolToOriginInfoMap: SymbolOriginInfoMap; readonly recommendedCompletion: Symbol | undefined; readonly previousToken: Node | undefined; From 0499f5d80113d2486186a7ec5b87177d64ae3752 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 14:15:42 -0700 Subject: [PATCH 212/262] Add "bigint" to `typeof x` in baselines --- .../reference/TypeGuardWithEnumUnion.types | 8 +- .../ambientExportDefaultErrors.types | 4 +- .../reference/anonymousClassExpression1.types | 2 +- tests/baselines/reference/arrayFind.types | 2 +- ...WithoutReturnTypeAnnotationInference.types | 10 +- .../reference/castExpressionParentheses.types | 2 +- tests/baselines/reference/castOfAwait.types | 4 +- .../reference/checkJsdocTypeTag5.types | 2 +- .../classDoesNotDependOnBaseTypes.types | 2 +- .../commaOperatorLeftSideUnused.types | 2 +- ...tionalOperatorConditionIsBooleanType.types | 6 +- ...itionalOperatorConditoinIsStringType.types | 6 +- .../reference/conditionalTypes1.types | 4 +- .../reference/conditionalTypes2.types | 2 +- .../constLocalsInFunctionExpressions.types | 10 +- ...controlFlowAnalysisOnBareThisKeyword.types | 2 +- .../reference/controlFlowCommaOperator.types | 4 +- .../controlFlowDoWhileStatement.types | 2 +- .../reference/controlFlowForStatement.types | 8 +- .../baselines/reference/controlFlowIIFE.types | 6 +- .../reference/controlFlowIfStatement.types | 4 +- ...controlFlowInstanceOfGuardPrimitives.types | 2 +- .../reference/controlFlowWhileStatement.types | 2 +- .../controlFlowWithIncompleteTypes.types | 4 +- .../controlFlowWithTemplateLiterals.types | 2 +- ...eclarationEmitIdentifierPredicates01.types | 2 +- ...dentifierPredicatesWithPrivateName01.types | 2 +- ...eWithNonEntityNameExpressionHeritage.types | 4 +- .../definiteAssignmentAssertions.types | 2 +- .../discriminantsAndPrimitives.types | 8 +- .../reference/duplicateLocalVariable1.types | 2 +- ...onentiationOperatorInTempalteString4.types | 8 +- ...ntiationOperatorInTempalteString4ES6.types | 8 +- ...onentiationOperatorInTemplateString1.types | 12 +- ...ntiationOperatorInTemplateString1ES6.types | 12 +- ...onentiationOperatorInTemplateString2.types | 12 +- ...ntiationOperatorInTemplateString2ES6.types | 12 +- ...onentiationOperatorInTemplateString3.types | 12 +- ...ntiationOperatorInTemplateString3ES6.types | 12 +- ...atorInTemplateStringWithSyntaxError1.types | 20 +-- ...atorInTemplateStringWithSyntaxError2.types | 20 +-- ...atorInTemplateStringWithSyntaxError3.types | 20 +-- .../exponentiationOperatorSyntaxError2.types | 20 +-- ...InvalidSimpleUnaryExpressionOperands.types | 40 +++--- .../reference/exportAssignNonIdentifier.types | 2 +- .../expressionTypeNodeShouldError.types | 12 +- .../reference/fixSignatureCaching.types | 8 +- .../reference/implicitConstParameters.types | 2 +- .../interfaceDoesNotDependOnBaseTypes.types | 2 +- .../keywordExpressionInternalComments.types | 2 +- tests/baselines/reference/mappedTypes4.types | 2 +- .../narrowUnknownByTypeofObject.types | 2 +- .../reference/narrowingByTypeofInSwitch.types | 36 +++--- .../narrowingConstrainedTypeParameter.types | 2 +- .../reference/nestedLoopTypeGuards.types | 8 +- tests/baselines/reference/neverType.types | 4 +- .../reference/nonPrimitiveNarrow.types | 4 +- .../reference/nonPrimitiveStrictNull.types | 8 +- .../reference/overloadAssignmentCompat.types | 4 +- .../overloadResolutionOverNonCTLambdas.types | 2 +- .../reference/overloadReturnTypes.types | 2 +- tests/baselines/reference/parserharness.types | 22 ++-- ...fixUnaryOperatorsOnExportedVariables.types | 2 +- .../reference/recursiveTypeRelations.types | 4 +- .../baselines/reference/reservedWords2.types | 2 +- .../reference/returnTagTypeGuard.types | 4 +- .../strictTypeofUnionNarrowing.types | 8 +- .../reference/switchStatements.types | 4 +- tests/baselines/reference/symbolType17.types | 2 +- tests/baselines/reference/symbolType18.types | 2 +- tests/baselines/reference/symbolType19.types | 2 +- tests/baselines/reference/symbolType3.types | 2 +- .../reference/templateStringInTypeOf.types | 4 +- .../reference/templateStringInTypeOfES6.types | 4 +- ...lateStringWithEmbeddedTypeOfOperator.types | 2 +- ...eStringWithEmbeddedTypeOfOperatorES6.types | 2 +- .../reference/thisTypeInTypePredicate.types | 2 +- .../baselines/reference/throwStatements.types | 2 +- .../baselines/reference/typeGuardEnums.types | 4 +- .../reference/typeGuardInClass.types | 2 +- .../typeGuardIntersectionTypes.types | 2 +- .../reference/typeGuardNesting.types | 24 ++-- .../typeGuardOfFormExpr1AndExpr2.types | 18 +-- .../typeGuardOfFormExpr1OrExpr2.types | 18 +-- .../reference/typeGuardOfFormNotExpr.types | 20 +-- .../typeGuardOfFormTypeOfBoolean.types | 20 +-- ...FormTypeOfEqualEqualHasNoEffect.errors.txt | 4 +- ...ardOfFormTypeOfEqualEqualHasNoEffect.types | 8 +- .../typeGuardOfFormTypeOfFunction.types | 20 +-- ...eGuardOfFormTypeOfIsOrderIndependent.types | 8 +- ...OfFormTypeOfNotEqualHasNoEffect.errors.txt | 4 +- ...GuardOfFormTypeOfNotEqualHasNoEffect.types | 8 +- .../typeGuardOfFormTypeOfNumber.types | 20 +-- .../typeGuardOfFormTypeOfOther.errors.txt | 32 ++--- .../typeGuardOfFormTypeOfOther.types | 18 +-- ...ypeGuardOfFormTypeOfPrimitiveSubtype.types | 12 +- .../typeGuardOfFormTypeOfString.types | 20 +-- .../typeGuardOnContainerTypeNoHang.types | 2 +- .../reference/typeGuardRedundancy.types | 16 +-- .../typeGuardTautologicalConsistiency.types | 8 +- .../reference/typeGuardTypeOfUndefined.types | 64 +++++----- .../reference/typeGuardsAsAssertions.types | 12 +- .../reference/typeGuardsDefeat.types | 6 +- .../typeGuardsInClassAccessors.types | 40 +++--- .../reference/typeGuardsInClassMethods.types | 30 ++--- .../typeGuardsInConditionalExpression.types | 34 ++--- .../reference/typeGuardsInDoStatement.types | 6 +- .../typeGuardsInExternalModule.types | 4 +- .../reference/typeGuardsInForStatement.types | 6 +- .../reference/typeGuardsInFunction.types | 38 +++--- .../typeGuardsInFunctionAndModuleBlock.types | 26 ++-- .../reference/typeGuardsInGlobal.types | 2 +- .../reference/typeGuardsInIfStatement.types | 34 ++--- .../reference/typeGuardsInModule.types | 22 ++-- .../reference/typeGuardsInProperties.types | 12 +- ...GuardsInRightOperandOfAndAndOperator.types | 22 ++-- ...peGuardsInRightOperandOfOrOrOperator.types | 22 ++-- .../typeGuardsInWhileStatement.types | 6 +- .../typeGuardsNestedAssignments.types | 2 +- .../reference/typeGuardsObjectMethods.types | 20 +-- .../reference/typeGuardsOnClassProperty.types | 8 +- .../reference/typeGuardsTypeParameters.types | 4 +- .../reference/typeGuardsWithAny.types | 8 +- .../reference/typeOfOperator1.errors.txt | 4 +- .../baselines/reference/typeOfOperator1.types | 4 +- .../typeofOperatorInvalidOperations.types | 6 +- .../typeofOperatorWithAnyOtherType.types | 120 +++++++++--------- .../typeofOperatorWithBooleanType.types | 58 ++++----- .../typeofOperatorWithEnumType.types | 42 +++--- .../typeofOperatorWithNumberType.types | 86 ++++++------- .../typeofOperatorWithStringType.types | 86 ++++++------- .../reference/typeofUnknownSymbol.types | 4 +- .../reference/unionTypeInference.types | 4 +- tests/baselines/reference/unknownType1.types | 4 +- 134 files changed, 818 insertions(+), 818 deletions(-) diff --git a/tests/baselines/reference/TypeGuardWithEnumUnion.types b/tests/baselines/reference/TypeGuardWithEnumUnion.types index 9f51791f209..a568034f8b8 100644 --- a/tests/baselines/reference/TypeGuardWithEnumUnion.types +++ b/tests/baselines/reference/TypeGuardWithEnumUnion.types @@ -11,7 +11,7 @@ function f1(x: Color | string) { if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color >"number" : "number" @@ -38,7 +38,7 @@ function f2(x: Color | string | string[]) { if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"object" : "object" @@ -51,7 +51,7 @@ function f2(x: Color | string | string[]) { } if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"number" : "number" @@ -72,7 +72,7 @@ function f2(x: Color | string | string[]) { } if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"string" : "string" diff --git a/tests/baselines/reference/ambientExportDefaultErrors.types b/tests/baselines/reference/ambientExportDefaultErrors.types index 4da013dcf58..21e18cc978a 100644 --- a/tests/baselines/reference/ambientExportDefaultErrors.types +++ b/tests/baselines/reference/ambientExportDefaultErrors.types @@ -29,7 +29,7 @@ declare module "indirect" { >"indirect" : typeof import("indirect") export default typeof Foo.default; ->typeof Foo.default : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof Foo.default : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Foo.default : number >Foo : typeof Foo >default : number @@ -41,7 +41,7 @@ declare module "indirect2" { >"indirect2" : typeof import("indirect2") export = typeof Foo2; ->typeof Foo2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof Foo2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Foo2 : number } diff --git a/tests/baselines/reference/anonymousClassExpression1.types b/tests/baselines/reference/anonymousClassExpression1.types index 3bc01960492..2e761d10afd 100644 --- a/tests/baselines/reference/anonymousClassExpression1.types +++ b/tests/baselines/reference/anonymousClassExpression1.types @@ -4,7 +4,7 @@ function f() { return typeof class {} === "function"; >typeof class {} === "function" : boolean ->typeof class {} : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof class {} : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >class {} : typeof (Anonymous class) >"function" : "function" } diff --git a/tests/baselines/reference/arrayFind.types b/tests/baselines/reference/arrayFind.types index 8bc1b36f7f6..c5237183700 100644 --- a/tests/baselines/reference/arrayFind.types +++ b/tests/baselines/reference/arrayFind.types @@ -6,7 +6,7 @@ function isNumber(x: any): x is number { return typeof x === "number"; >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"number" : "number" } diff --git a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types index a7ccc2cd4e0..d07126c148e 100644 --- a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types +++ b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types @@ -100,17 +100,17 @@ var r6 = foo6(1); >1 : 1 function foo7(x) { ->foo7 : (x: any) => "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7 : (x: any) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any return typeof x; ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any } var r7 = foo7(1); ->r7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->foo7(1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->foo7 : (x: any) => "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>r7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7(1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7 : (x: any) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >1 : 1 // object types diff --git a/tests/baselines/reference/castExpressionParentheses.types b/tests/baselines/reference/castExpressionParentheses.types index 5f6e5b2122b..db38aad5a47 100644 --- a/tests/baselines/reference/castExpressionParentheses.types +++ b/tests/baselines/reference/castExpressionParentheses.types @@ -182,7 +182,7 @@ declare var A; >(typeof A).x : any >(typeof A) : any >typeof A : any ->typeof A : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A : any >x : any diff --git a/tests/baselines/reference/castOfAwait.types b/tests/baselines/reference/castOfAwait.types index afe075b67d9..34934b89128 100644 --- a/tests/baselines/reference/castOfAwait.types +++ b/tests/baselines/reference/castOfAwait.types @@ -8,7 +8,7 @@ async function f() { >0 : 0 typeof await 0; ->typeof await 0 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof await 0 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >await 0 : 0 >0 : 0 @@ -21,7 +21,7 @@ async function f() { >await void typeof void await 0 : undefined >void typeof void await 0 : undefined > typeof void await 0 : string ->typeof void await 0 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof void await 0 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" > void await 0 : number >void await 0 : undefined >await 0 : 0 diff --git a/tests/baselines/reference/checkJsdocTypeTag5.types b/tests/baselines/reference/checkJsdocTypeTag5.types index b16904c700d..816f86a80a6 100644 --- a/tests/baselines/reference/checkJsdocTypeTag5.types +++ b/tests/baselines/reference/checkJsdocTypeTag5.types @@ -68,7 +68,7 @@ function monaLisa(sb) { return typeof sb === 'string' ? 1 : 2; >typeof sb === 'string' ? 1 : 2 : 1 | 2 >typeof sb === 'string' : boolean ->typeof sb : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof sb : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >sb : any >'string' : "string" >1 : 1 diff --git a/tests/baselines/reference/classDoesNotDependOnBaseTypes.types b/tests/baselines/reference/classDoesNotDependOnBaseTypes.types index e8badbbe815..c50aef1cf14 100644 --- a/tests/baselines/reference/classDoesNotDependOnBaseTypes.types +++ b/tests/baselines/reference/classDoesNotDependOnBaseTypes.types @@ -18,7 +18,7 @@ var x: StringTree; if (typeof x !== "string") { >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : StringTree >"string" : "string" diff --git a/tests/baselines/reference/commaOperatorLeftSideUnused.types b/tests/baselines/reference/commaOperatorLeftSideUnused.types index ccfac66e734..585ac1ca7e0 100644 --- a/tests/baselines/reference/commaOperatorLeftSideUnused.types +++ b/tests/baselines/reference/commaOperatorLeftSideUnused.types @@ -158,7 +158,7 @@ xx = (typeof xx, 'unused'); >xx : any >(typeof xx, 'unused') : "unused" >typeof xx, 'unused' : "unused" ->typeof xx : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof xx : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >xx : any >'unused' : "unused" diff --git a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types b/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types index 17b5e6b5bff..20e3e132472 100644 --- a/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types +++ b/tests/baselines/reference/conditionalOperatorConditionIsBooleanType.types @@ -118,7 +118,7 @@ true ? exprString1 : exprBoolean1; // union typeof "123" == "string" ? exprBoolean1 : exprBoolean2; >typeof "123" == "string" ? exprBoolean1 : exprBoolean2 : boolean >typeof "123" == "string" : boolean ->typeof "123" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "123" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"123" : "123" >"string" : "string" >exprBoolean1 : boolean @@ -260,7 +260,7 @@ var resultIsBoolean3 = typeof "123" == "string" ? exprBoolean1 : exprBoolean2; >resultIsBoolean3 : boolean >typeof "123" == "string" ? exprBoolean1 : exprBoolean2 : boolean >typeof "123" == "string" : boolean ->typeof "123" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "123" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"123" : "123" >"string" : "string" >exprBoolean1 : boolean @@ -297,7 +297,7 @@ var resultIsStringOrBoolean4 = typeof "123" === "string" ? exprString1 : exprBoo >resultIsStringOrBoolean4 : string | boolean >typeof "123" === "string" ? exprString1 : exprBoolean1 : string | boolean >typeof "123" === "string" : boolean ->typeof "123" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "123" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"123" : "123" >"string" : "string" >exprString1 : string diff --git a/tests/baselines/reference/conditionalOperatorConditoinIsStringType.types b/tests/baselines/reference/conditionalOperatorConditoinIsStringType.types index cf20b244e93..62df9cba085 100644 --- a/tests/baselines/reference/conditionalOperatorConditoinIsStringType.types +++ b/tests/baselines/reference/conditionalOperatorConditoinIsStringType.types @@ -121,7 +121,7 @@ var array = ["1", "2", "3"]; typeof condString ? exprAny1 : exprAny2; >typeof condString ? exprAny1 : exprAny2 : any ->typeof condString : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof condString : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >condString : string >exprAny1 : any >exprAny2 : any @@ -252,7 +252,7 @@ var resultIsStringOrBoolean2 = "hello" ? exprString1 : exprBoolean1; // union var resultIsAny3 = typeof condString ? exprAny1 : exprAny2; >resultIsAny3 : any >typeof condString ? exprAny1 : exprAny2 : any ->typeof condString : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof condString : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >condString : string >exprAny1 : any >exprAny2 : any @@ -295,7 +295,7 @@ var resultIsObject3 = array[1] ? exprIsObject1 : exprIsObject2; var resultIsStringOrBoolean3 = typeof condString ? exprString1 : exprBoolean1; // union >resultIsStringOrBoolean3 : string | boolean >typeof condString ? exprString1 : exprBoolean1 : string | boolean ->typeof condString : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof condString : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >condString : string >exprString1 : string >exprBoolean1 : boolean diff --git a/tests/baselines/reference/conditionalTypes1.types b/tests/baselines/reference/conditionalTypes1.types index a8d388ecbed..00d1965eea4 100644 --- a/tests/baselines/reference/conditionalTypes1.types +++ b/tests/baselines/reference/conditionalTypes1.types @@ -413,13 +413,13 @@ function zeroOf(value: T) { >(typeof value === "number" ? 0 : typeof value === "string" ? "" : false) : false | "" | 0 >typeof value === "number" ? 0 : typeof value === "string" ? "" : false : false | "" | 0 >typeof value === "number" : boolean ->typeof value : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof value : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >value : T >"number" : "number" >0 : 0 >typeof value === "string" ? "" : false : false | "" >typeof value === "string" : boolean ->typeof value : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof value : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >value : T >"string" : "string" >"" : "" diff --git a/tests/baselines/reference/conditionalTypes2.types b/tests/baselines/reference/conditionalTypes2.types index b1fbfc1f483..58ce7e5d5b4 100644 --- a/tests/baselines/reference/conditionalTypes2.types +++ b/tests/baselines/reference/conditionalTypes2.types @@ -69,7 +69,7 @@ function isFunction(value: T): value is Extract { return typeof value === "function"; >typeof value === "function" : boolean ->typeof value : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof value : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >value : T >"function" : "function" } diff --git a/tests/baselines/reference/constLocalsInFunctionExpressions.types b/tests/baselines/reference/constLocalsInFunctionExpressions.types index 07d3392045c..33799cba36c 100644 --- a/tests/baselines/reference/constLocalsInFunctionExpressions.types +++ b/tests/baselines/reference/constLocalsInFunctionExpressions.types @@ -12,7 +12,7 @@ function f1() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -35,7 +35,7 @@ function f2() { if (typeof x !== "string") { >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -59,7 +59,7 @@ function f3() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -82,7 +82,7 @@ function f4() { if (typeof x !== "string") { >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -106,7 +106,7 @@ function f5() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/controlFlowAnalysisOnBareThisKeyword.types b/tests/baselines/reference/controlFlowAnalysisOnBareThisKeyword.types index 8765476270c..e9192d8323c 100644 --- a/tests/baselines/reference/controlFlowAnalysisOnBareThisKeyword.types +++ b/tests/baselines/reference/controlFlowAnalysisOnBareThisKeyword.types @@ -27,7 +27,7 @@ function bar(this: string | number) { if (typeof this === "string") { >typeof this === "string" : boolean ->typeof this : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this : string | number >"string" : "string" diff --git a/tests/baselines/reference/controlFlowCommaOperator.types b/tests/baselines/reference/controlFlowCommaOperator.types index d4e073295d7..6cc578c7531 100644 --- a/tests/baselines/reference/controlFlowCommaOperator.types +++ b/tests/baselines/reference/controlFlowCommaOperator.types @@ -17,7 +17,7 @@ function f(x: string | number | boolean) { >y : string | number | boolean >"" : "" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -36,7 +36,7 @@ function f(x: string | number | boolean) { >z : string | number | boolean >1 : 1 >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" diff --git a/tests/baselines/reference/controlFlowDoWhileStatement.types b/tests/baselines/reference/controlFlowDoWhileStatement.types index 1e70e4b82f1..94431485fe5 100644 --- a/tests/baselines/reference/controlFlowDoWhileStatement.types +++ b/tests/baselines/reference/controlFlowDoWhileStatement.types @@ -66,7 +66,7 @@ function c() { if (typeof x === "string") continue; >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/controlFlowForStatement.types b/tests/baselines/reference/controlFlowForStatement.types index 28c5ff36e66..01b1a007590 100644 --- a/tests/baselines/reference/controlFlowForStatement.types +++ b/tests/baselines/reference/controlFlowForStatement.types @@ -82,7 +82,7 @@ function d() { >x : string | number | boolean >"" : "" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >x = 5 : 5 @@ -106,7 +106,7 @@ function e() { >"" : "" >0 : 0 >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | true >"string" : "string" >x = "" || true : true @@ -127,7 +127,7 @@ function f() { for (; typeof x !== "string";) { >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -136,7 +136,7 @@ function f() { if (typeof x === "number") break; >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" diff --git a/tests/baselines/reference/controlFlowIIFE.types b/tests/baselines/reference/controlFlowIIFE.types index 7aaaad159fc..2116cfaa2ae 100644 --- a/tests/baselines/reference/controlFlowIIFE.types +++ b/tests/baselines/reference/controlFlowIIFE.types @@ -12,7 +12,7 @@ function f1() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -40,7 +40,7 @@ function f2() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -72,7 +72,7 @@ function f3() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/controlFlowIfStatement.types b/tests/baselines/reference/controlFlowIfStatement.types index 03141e26185..3f54468a24e 100644 --- a/tests/baselines/reference/controlFlowIfStatement.types +++ b/tests/baselines/reference/controlFlowIfStatement.types @@ -95,7 +95,7 @@ function c(data: string | T): T { if (typeof data === 'string') { >typeof data === 'string' : boolean ->typeof data : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof data : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >data : string | T >'string' : "string" @@ -117,7 +117,7 @@ function d(data: string | T): never { if (typeof data === 'string') { >typeof data === 'string' : boolean ->typeof data : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof data : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >data : string | T >'string' : "string" diff --git a/tests/baselines/reference/controlFlowInstanceOfGuardPrimitives.types b/tests/baselines/reference/controlFlowInstanceOfGuardPrimitives.types index 2531f6ae891..7b69b0dc1d9 100644 --- a/tests/baselines/reference/controlFlowInstanceOfGuardPrimitives.types +++ b/tests/baselines/reference/controlFlowInstanceOfGuardPrimitives.types @@ -22,7 +22,7 @@ function distinguish(thing: string | number | Date) { } else if (typeof thing === 'string') { >typeof thing === 'string' : boolean ->typeof thing : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof thing : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >thing : string | number >'string' : "string" diff --git a/tests/baselines/reference/controlFlowWhileStatement.types b/tests/baselines/reference/controlFlowWhileStatement.types index ae127a6bdca..713d7bd8d81 100644 --- a/tests/baselines/reference/controlFlowWhileStatement.types +++ b/tests/baselines/reference/controlFlowWhileStatement.types @@ -69,7 +69,7 @@ function c() { if (typeof x === "string") continue; >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/controlFlowWithIncompleteTypes.types b/tests/baselines/reference/controlFlowWithIncompleteTypes.types index f5e8f2bcf24..571ad8116c3 100644 --- a/tests/baselines/reference/controlFlowWithIncompleteTypes.types +++ b/tests/baselines/reference/controlFlowWithIncompleteTypes.types @@ -16,7 +16,7 @@ function foo1() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -49,7 +49,7 @@ function foo2() { if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"number" : "number" diff --git a/tests/baselines/reference/controlFlowWithTemplateLiterals.types b/tests/baselines/reference/controlFlowWithTemplateLiterals.types index 7775d26fe38..0a2c47b970c 100644 --- a/tests/baselines/reference/controlFlowWithTemplateLiterals.types +++ b/tests/baselines/reference/controlFlowWithTemplateLiterals.types @@ -4,7 +4,7 @@ declare const envVar: string | undefined; if (typeof envVar === `string`) { >typeof envVar === `string` : boolean ->typeof envVar : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof envVar : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >envVar : string | undefined >`string` : "string" diff --git a/tests/baselines/reference/declarationEmitIdentifierPredicates01.types b/tests/baselines/reference/declarationEmitIdentifierPredicates01.types index 934bb35f5e9..08c762c9685 100644 --- a/tests/baselines/reference/declarationEmitIdentifierPredicates01.types +++ b/tests/baselines/reference/declarationEmitIdentifierPredicates01.types @@ -5,7 +5,7 @@ export function f(x: any): x is number { return typeof x === "number"; >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"number" : "number" } diff --git a/tests/baselines/reference/declarationEmitIdentifierPredicatesWithPrivateName01.types b/tests/baselines/reference/declarationEmitIdentifierPredicatesWithPrivateName01.types index 2fca6b7518b..294fd2fa380 100644 --- a/tests/baselines/reference/declarationEmitIdentifierPredicatesWithPrivateName01.types +++ b/tests/baselines/reference/declarationEmitIdentifierPredicatesWithPrivateName01.types @@ -10,7 +10,7 @@ export function f(x: any): x is I { return typeof x.a === "number"; >typeof x.a === "number" : boolean ->typeof x.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x.a : any >x : any >a : any diff --git a/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.types b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.types index 9c43312be86..33fa4f8aac7 100644 --- a/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.types +++ b/tests/baselines/reference/declarationEmitInterfaceWithNonEntityNameExpressionHeritage.types @@ -3,7 +3,7 @@ class A { } >A : A interface Class extends (typeof A) { } ->(typeof A) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof A) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A : typeof A diff --git a/tests/baselines/reference/definiteAssignmentAssertions.types b/tests/baselines/reference/definiteAssignmentAssertions.types index 92646bab86e..95eaf7853b3 100644 --- a/tests/baselines/reference/definiteAssignmentAssertions.types +++ b/tests/baselines/reference/definiteAssignmentAssertions.types @@ -91,7 +91,7 @@ function f2() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/discriminantsAndPrimitives.types b/tests/baselines/reference/discriminantsAndPrimitives.types index 455c1595dc8..6498df3926e 100644 --- a/tests/baselines/reference/discriminantsAndPrimitives.types +++ b/tests/baselines/reference/discriminantsAndPrimitives.types @@ -23,7 +23,7 @@ function f1(x: Foo | Bar | string) { if (typeof x !== 'string') { >typeof x !== 'string' : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Foo | Bar >'string' : "string" @@ -49,7 +49,7 @@ function f2(x: Foo | Bar | string | undefined) { if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Foo | Bar | undefined >"object" : "object" @@ -78,7 +78,7 @@ function f3(x: Foo | Bar | string | null) { >x && typeof x !== "string" : boolean | "" | null >x : string | Foo | Bar | null >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Foo | Bar >"string" : "string" @@ -107,7 +107,7 @@ function f4(x: Foo | Bar | string | number | null) { >x && typeof x === "object" : boolean | "" | 0 | null >x : string | number | Foo | Bar | null >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | Foo | Bar >"object" : "object" diff --git a/tests/baselines/reference/duplicateLocalVariable1.types b/tests/baselines/reference/duplicateLocalVariable1.types index d19007d90aa..4a7dcb41919 100644 --- a/tests/baselines/reference/duplicateLocalVariable1.types +++ b/tests/baselines/reference/duplicateLocalVariable1.types @@ -121,7 +121,7 @@ export class TestRunner { if (typeof testcase.errorMessageRegEx === "string") { >typeof testcase.errorMessageRegEx === "string" : boolean ->typeof testcase.errorMessageRegEx : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof testcase.errorMessageRegEx : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >testcase.errorMessageRegEx : string >testcase : TestCase >errorMessageRegEx : string diff --git a/tests/baselines/reference/emitExponentiationOperatorInTempalteString4.types b/tests/baselines/reference/emitExponentiationOperatorInTempalteString4.types index 08bb88d6965..912a26f746f 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTempalteString4.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTempalteString4.types @@ -63,7 +63,7 @@ var s; `${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -161,14 +161,14 @@ var s; `${typeof (t1 ** t2 ** t1)} hello world ${typeof (t1 ** t2 ** t1)}`; >`${typeof (t1 ** t2 ** t1)} hello world ${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,7 +222,7 @@ var s; `hello ${typeof (t1 ** t2 ** t1)}`; >`hello ${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTempalteString4ES6.types b/tests/baselines/reference/emitExponentiationOperatorInTempalteString4ES6.types index 0918c28892a..08d0d591dfb 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTempalteString4ES6.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTempalteString4ES6.types @@ -63,7 +63,7 @@ var s; `${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -161,14 +161,14 @@ var s; `${typeof (t1 ** t2 ** t1)} hello world ${typeof (t1 ** t2 ** t1)}`; >`${typeof (t1 ** t2 ** t1)} hello world ${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,7 +222,7 @@ var s; `hello ${typeof (t1 ** t2 ** t1)}`; >`hello ${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString1.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString1.types index 326c947735b..0a40fc6f766 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString1.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString1.types @@ -53,7 +53,7 @@ var s; `${typeof (t1 ** t2 ** t1) }`; >`${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`${1 + typeof (t1 ** t2 ** t1) }` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `${typeof (t1 ** t2 ** t1)}${typeof (t1 ** t2 ** t1)}`; >`${typeof (t1 ** t2 ** t1)}${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }`; >`${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString1ES6.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString1ES6.types index 2aa89e26587..9d712e6e366 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString1ES6.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString1ES6.types @@ -53,7 +53,7 @@ var s; `${typeof (t1 ** t2 ** t1) }`; >`${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`${1 + typeof (t1 ** t2 ** t1) }` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `${typeof (t1 ** t2 ** t1)}${typeof (t1 ** t2 ** t1)}`; >`${typeof (t1 ** t2 ** t1)}${typeof (t1 ** t2 ** t1)}` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }`; >`${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString2.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString2.types index c7e861e8a39..9b583b03d28 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString2.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString2.types @@ -53,7 +53,7 @@ var s; `hello ${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`hello ${1 + typeof (t1 ** t2 ** t1) }` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `hello ${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `hello ${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString2ES6.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString2ES6.types index 31c845f91b8..c1c6394c63e 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString2ES6.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString2ES6.types @@ -53,7 +53,7 @@ var s; `hello ${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`hello ${1 + typeof (t1 ** t2 ** t1) }` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `hello ${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `hello ${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }`; >`hello ${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1) }` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString3.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString3.types index 6e0dea6b9dc..431d688f3b4 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString3.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString3.types @@ -53,7 +53,7 @@ var s; `${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`${1 + typeof (t1 ** t2 ** t1) } world` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1)} !!`; >`${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1)} !!` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/emitExponentiationOperatorInTemplateString3ES6.types b/tests/baselines/reference/emitExponentiationOperatorInTemplateString3ES6.types index 0ea9f7db87c..ccbacd4c719 100644 --- a/tests/baselines/reference/emitExponentiationOperatorInTemplateString3ES6.types +++ b/tests/baselines/reference/emitExponentiationOperatorInTemplateString3ES6.types @@ -53,7 +53,7 @@ var s; `${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -65,7 +65,7 @@ var s; >`${1 + typeof (t1 ** t2 ** t1) } world` : string >1 + typeof (t1 ** t2 ** t1) : string >1 : 1 ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -140,14 +140,14 @@ var s; `${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) } world`; >`${typeof (t1 ** t2 ** t1) }${typeof (t1 ** t2 ** t1) } world` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number @@ -222,14 +222,14 @@ var s; `${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1)} !!`; >`${typeof (t1 ** t2 ** t1) } hello world ${typeof (t1 ** t2 ** t1)} !!` : string ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number >t2 ** t1 : number >t2 : number >t1 : number ->typeof (t1 ** t2 ** t1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (t1 ** t2 ** t1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(t1 ** t2 ** t1) : number >t1 ** t2 ** t1 : number >t1 : number diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.types b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.types index b5323a24b98..8c7e7d27aa8 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.types +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError1.types @@ -17,7 +17,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -65,7 +65,7 @@ var s; `${typeof t1 ** t2 ** t1}`; >`${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -140,13 +140,13 @@ var s; `${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}`; >`${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -157,7 +157,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -165,7 +165,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -240,13 +240,13 @@ var s; `${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}`; >`${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -257,7 +257,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -265,7 +265,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.types b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.types index 7f99664658e..9cacc633c62 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.types +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError2.types @@ -54,7 +54,7 @@ var s; `hello ${typeof t1 ** t2 ** t1}`; >`hello ${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -65,7 +65,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -140,13 +140,13 @@ var s; `hello ${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}`; >`hello ${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -157,7 +157,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -165,7 +165,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -240,13 +240,13 @@ var s; `hello ${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}`; >`hello ${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1}` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -257,7 +257,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -265,7 +265,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number diff --git a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.types b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.types index 12303bf7c23..36d594f3821 100644 --- a/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.types +++ b/tests/baselines/reference/exponentiationOperatorInTemplateStringWithSyntaxError3.types @@ -54,7 +54,7 @@ var s; `${typeof t1 ** t2 ** t1} world`; >`${typeof t1 ** t2 ** t1} world` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -65,7 +65,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -140,13 +140,13 @@ var s; `${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1} world`; >`${typeof t1 ** t2 ** t1}${typeof t1 ** t2 ** t1} world` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -157,7 +157,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -165,7 +165,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -240,13 +240,13 @@ var s; `${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1} !!`; >`${typeof t1 ** t2 ** t1} hello world ${typeof t1 ** t2 ** t1} !!` : string >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number >t1 : number >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -257,7 +257,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number @@ -265,7 +265,7 @@ var s; >1 + typeof t1 ** t2 ** t1 : number >1 : 1 >typeof t1 ** t2 ** t1 : number ->typeof t1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof t1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >t1 : number >t2 ** t1 : number >t2 : number diff --git a/tests/baselines/reference/exponentiationOperatorSyntaxError2.types b/tests/baselines/reference/exponentiationOperatorSyntaxError2.types index 194aeb04939..5fa497b879f 100644 --- a/tests/baselines/reference/exponentiationOperatorSyntaxError2.types +++ b/tests/baselines/reference/exponentiationOperatorSyntaxError2.types @@ -70,34 +70,34 @@ delete temp++ ** 3; typeof --temp ** 3; >typeof --temp ** 3 : number ->typeof --temp : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof --temp : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >--temp : number >temp : any >3 : 3 typeof temp-- ** 3; >typeof temp-- ** 3 : number ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >3 : 3 typeof 3 ** 4; >typeof 3 ** 4 : number ->typeof 3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >3 : 3 >4 : 4 typeof temp++ ** 4; >typeof temp++ ** 4 : number ->typeof temp++ : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp++ : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp++ : number >temp : any >4 : 4 typeof temp-- ** 4; >typeof temp-- ** 4 : number ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >4 : 4 @@ -106,7 +106,7 @@ typeof temp-- ** 4; >1 ** typeof --temp ** 3 : number >1 : 1 >typeof --temp ** 3 : number ->typeof --temp : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof --temp : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >--temp : number >temp : any >3 : 3 @@ -115,7 +115,7 @@ typeof temp-- ** 4; >1 ** typeof temp-- ** 3 : number >1 : 1 >typeof temp-- ** 3 : number ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >3 : 3 @@ -124,7 +124,7 @@ typeof temp-- ** 4; >1 ** typeof 3 ** 4 : number >1 : 1 >typeof 3 ** 4 : number ->typeof 3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >3 : 3 >4 : 4 @@ -132,7 +132,7 @@ typeof temp-- ** 4; >1 ** typeof temp++ ** 4 : number >1 : 1 >typeof temp++ ** 4 : number ->typeof temp++ : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp++ : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp++ : number >temp : any >4 : 4 @@ -141,7 +141,7 @@ typeof temp-- ** 4; >1 ** typeof temp-- ** 4 : number >1 : 1 >typeof temp-- ** 4 : number ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >4 : 4 diff --git a/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.types b/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.types index 035fbc02625..eca7d9ecc83 100644 --- a/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.types +++ b/tests/baselines/reference/exponentiationOperatorWithInvalidSimpleUnaryExpressionOperands.types @@ -93,39 +93,39 @@ var temp: any; (typeof --temp) ** 3; >(typeof --temp) ** 3 : number ->(typeof --temp) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof --temp : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof --temp) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof --temp : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >--temp : number >temp : any >3 : 3 (typeof temp--) ** 3; >(typeof temp--) ** 3 : number ->(typeof temp--) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp--) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >3 : 3 (typeof 3) ** 4; >(typeof 3) ** 4 : number ->(typeof 3) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof 3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof 3) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >3 : 3 >4 : 4 (typeof temp++) ** 4; >(typeof temp++) ** 4 : number ->(typeof temp++) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp++ : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp++) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp++ : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp++ : number >temp : any >4 : 4 (typeof temp--) ** 4; >(typeof temp--) ** 4 : number ->(typeof temp--) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp--) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >4 : 4 @@ -134,8 +134,8 @@ var temp: any; >1 ** (typeof --temp) ** 3 : number >1 : 1 >(typeof --temp) ** 3 : number ->(typeof --temp) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof --temp : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof --temp) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof --temp : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >--temp : number >temp : any >3 : 3 @@ -144,8 +144,8 @@ var temp: any; >1 ** (typeof temp--) ** 3 : number >1 : 1 >(typeof temp--) ** 3 : number ->(typeof temp--) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp--) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >3 : 3 @@ -154,8 +154,8 @@ var temp: any; >1 ** (typeof 3) ** 4 : number >1 : 1 >(typeof 3) ** 4 : number ->(typeof 3) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof 3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof 3) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >3 : 3 >4 : 4 @@ -163,8 +163,8 @@ var temp: any; >1 ** (typeof temp++) ** 4 : number >1 : 1 >(typeof temp++) ** 4 : number ->(typeof temp++) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp++ : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp++) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp++ : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp++ : number >temp : any >4 : 4 @@ -173,8 +173,8 @@ var temp: any; >1 ** (typeof temp--) ** 4 : number >1 : 1 >(typeof temp--) ** 4 : number ->(typeof temp--) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof temp-- : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof temp--) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof temp-- : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >temp-- : number >temp : any >4 : 4 diff --git a/tests/baselines/reference/exportAssignNonIdentifier.types b/tests/baselines/reference/exportAssignNonIdentifier.types index e4426cdb12d..e457fd8a209 100644 --- a/tests/baselines/reference/exportAssignNonIdentifier.types +++ b/tests/baselines/reference/exportAssignNonIdentifier.types @@ -4,7 +4,7 @@ var x = 10; >10 : 10 export = typeof x; // Ok ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number === tests/cases/conformance/externalModules/foo2.ts === diff --git a/tests/baselines/reference/expressionTypeNodeShouldError.types b/tests/baselines/reference/expressionTypeNodeShouldError.types index 45c12d7c8ff..58bb3943e73 100644 --- a/tests/baselines/reference/expressionTypeNodeShouldError.types +++ b/tests/baselines/reference/expressionTypeNodeShouldError.types @@ -20,7 +20,7 @@ class C { const x: "".typeof(this.foo); >x : "" ->typeof(this.foo) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(this.foo) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(this.foo) : () => void >this.foo : () => void >this : this @@ -38,7 +38,7 @@ const nodes = document.getElementsByTagName("li"); type ItemType = "".typeof(nodes.item(0)); >ItemType : "" ->typeof(nodes.item(0)) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(nodes.item(0)) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(nodes.item(0)) : HTMLLIElement >nodes.item(0) : HTMLLIElement >nodes.item : (index: number) => HTMLLIElement @@ -61,7 +61,7 @@ class C2 { const x: 3.141592.typeof(this.foo); >x : 3.141592 ->typeof(this.foo) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(this.foo) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(this.foo) : () => void >this.foo : () => void >this : this @@ -79,7 +79,7 @@ const nodes2 = document.getElementsByTagName("li"); type ItemType2 = 4..typeof(nodes.item(0)); >ItemType2 : 4 ->typeof(nodes.item(0)) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(nodes.item(0)) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(nodes.item(0)) : HTMLLIElement >nodes.item(0) : HTMLLIElement >nodes.item : (index: number) => HTMLLIElement @@ -103,7 +103,7 @@ class C3 { const x: false.typeof(this.foo); >x : false >false : false ->typeof(this.foo) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(this.foo) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(this.foo) : () => void >this.foo : () => void >this : this @@ -122,7 +122,7 @@ const nodes3 = document.getElementsByTagName("li"); type ItemType3 = true.typeof(nodes.item(0)); >ItemType3 : true >true : true ->typeof(nodes.item(0)) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(nodes.item(0)) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(nodes.item(0)) : HTMLLIElement >nodes.item(0) : HTMLLIElement >nodes.item : (index: number) => HTMLLIElement diff --git a/tests/baselines/reference/fixSignatureCaching.types b/tests/baselines/reference/fixSignatureCaching.types index 8365196acd7..c278034e2cb 100644 --- a/tests/baselines/reference/fixSignatureCaching.types +++ b/tests/baselines/reference/fixSignatureCaching.types @@ -3422,7 +3422,7 @@ define(function () { if (typeof window !== 'undefined' && window.screen) { >typeof window !== 'undefined' && window.screen : Screen >typeof window !== 'undefined' : boolean ->typeof window : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof window : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >window : Window >'undefined' : "undefined" >window.screen : Screen @@ -3488,7 +3488,7 @@ define(function () { if (typeof module !== 'undefined' && module.exports) { >typeof module !== 'undefined' && module.exports : any >typeof module !== 'undefined' : boolean ->typeof module : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof module : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >module : any >'undefined' : "undefined" >module.exports : any @@ -3508,7 +3508,7 @@ define(function () { } else if (typeof define === 'function' && define.amd) { >typeof define === 'function' && define.amd : any >typeof define === 'function' : boolean ->typeof define : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof define : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >define : any >'function' : "function" >define.amd : any @@ -3520,7 +3520,7 @@ define(function () { } else if (typeof window !== 'undefined') { >typeof window !== 'undefined' : boolean ->typeof window : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof window : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >window : Window >'undefined' : "undefined" diff --git a/tests/baselines/reference/implicitConstParameters.types b/tests/baselines/reference/implicitConstParameters.types index 0aaf7b3c49b..e9a97ebc022 100644 --- a/tests/baselines/reference/implicitConstParameters.types +++ b/tests/baselines/reference/implicitConstParameters.types @@ -14,7 +14,7 @@ function fn(x: number | string) { if (typeof x === 'number') { >typeof x === 'number' : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >'number' : "number" diff --git a/tests/baselines/reference/interfaceDoesNotDependOnBaseTypes.types b/tests/baselines/reference/interfaceDoesNotDependOnBaseTypes.types index e948f8ac9ef..6883034052e 100644 --- a/tests/baselines/reference/interfaceDoesNotDependOnBaseTypes.types +++ b/tests/baselines/reference/interfaceDoesNotDependOnBaseTypes.types @@ -4,7 +4,7 @@ var x: StringTree; if (typeof x !== "string") { >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : StringTree >"string" : "string" diff --git a/tests/baselines/reference/keywordExpressionInternalComments.types b/tests/baselines/reference/keywordExpressionInternalComments.types index b987c1132fe..269fcb67c6e 100644 --- a/tests/baselines/reference/keywordExpressionInternalComments.types +++ b/tests/baselines/reference/keywordExpressionInternalComments.types @@ -4,7 +4,7 @@ >Array : ArrayConstructor /*1*/ typeof /*2*/ Array /*3*/; ->typeof /*2*/ Array : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof /*2*/ Array : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Array : ArrayConstructor /*1*/ void /*2*/ Array /*3*/; diff --git a/tests/baselines/reference/mappedTypes4.types b/tests/baselines/reference/mappedTypes4.types index fac8d982e92..d59d500d089 100644 --- a/tests/baselines/reference/mappedTypes4.types +++ b/tests/baselines/reference/mappedTypes4.types @@ -16,7 +16,7 @@ function boxify(obj: T): Boxified { if (typeof obj === "object") { >typeof obj === "object" : boolean ->typeof obj : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj : T >"object" : "object" diff --git a/tests/baselines/reference/narrowUnknownByTypeofObject.types b/tests/baselines/reference/narrowUnknownByTypeofObject.types index 98225861d1e..a4e1e034433 100644 --- a/tests/baselines/reference/narrowUnknownByTypeofObject.types +++ b/tests/baselines/reference/narrowUnknownByTypeofObject.types @@ -5,7 +5,7 @@ function foo(x: unknown) { if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown >"object" : "object" diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index a0d1c272d02..f823c57770c 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -104,7 +104,7 @@ function testUnion(x: Basic) { >x : Basic switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : Basic case 'number': assertNumber(x); return; @@ -160,7 +160,7 @@ function testExtendsUnion(x: T) { >x : T switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T case 'number': assertNumber(x); return; @@ -216,7 +216,7 @@ function testAny(x: any) { >x : any switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any case 'number': assertNumber(x); return; @@ -280,7 +280,7 @@ function testUnionExplicitDefault(x: Basic) { >x : Basic switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : Basic case 'number': assertNumber(x); return; @@ -319,7 +319,7 @@ function testUnionImplicitDefault(x: Basic) { >x : Basic switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : Basic case 'number': assertNumber(x); return; @@ -357,7 +357,7 @@ function testExtendsExplicitDefault(x: T) { >x : T switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T case 'number': assertNumber(x); return; @@ -397,7 +397,7 @@ function testExtendsImplicitDefault(x: T) { >x : T switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T case 'number': assertNumber(x); return; @@ -444,7 +444,7 @@ function exhaustiveChecks(x: number | string | L | R): string { >x : string | number | R | L switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | R | L case 'number': return x.toString(2); @@ -478,7 +478,7 @@ function exhaustiveChecksGenerics(x: T): stri >x : T switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T case 'number': return x.toString(2); @@ -516,7 +516,7 @@ function multipleGeneric(xy: X | Y): [X, string] | [Y, >xy : X | Y switch (typeof xy) { ->typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof xy : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >xy : X | Y case 'function': return [xy, xy(42)]; @@ -547,7 +547,7 @@ function multipleGenericFuse(xy: X | >xy : X | Y switch (typeof xy) { ->typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof xy : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >xy : X | Y case 'function': return [xy, 1]; @@ -574,7 +574,7 @@ function multipleGenericExhaustive(xy: X | Y): [X, str >xy : X | Y switch (typeof xy) { ->typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof xy : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >xy : X | Y case 'object': return [xy, xy.y]; @@ -600,7 +600,7 @@ function switchOrdering(x: string | number | boolean) { >x : string | number | boolean switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean case 'string': return assertString(x); @@ -641,7 +641,7 @@ function switchOrderingWithDefault(x: string | number | boolean) { >x : string | number | boolean } switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean case 'string': @@ -674,7 +674,7 @@ function fallThroughTest(x: string | number | boolean | object) { >x : string | number | boolean | object switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean | object case 'number': @@ -720,7 +720,7 @@ function unknownNarrowing(x: unknown) { >x : unknown switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown case 'number': assertNumber(x); return; @@ -776,7 +776,7 @@ function keyofNarrowing(k: keyof S) { >k1 : keyof S switch (typeof k) { ->typeof k : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof k : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >k : keyof S case 'number': assertNumber(k); assertKeyofS(k); return; @@ -813,7 +813,7 @@ function narrowingNarrows(x: {} | undefined) { >x : {} | undefined switch (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : {} | undefined case 'number': assertNumber(x); return; diff --git a/tests/baselines/reference/narrowingConstrainedTypeParameter.types b/tests/baselines/reference/narrowingConstrainedTypeParameter.types index 0d14846fc2a..1fadbfdb1c4 100644 --- a/tests/baselines/reference/narrowingConstrainedTypeParameter.types +++ b/tests/baselines/reference/narrowingConstrainedTypeParameter.types @@ -12,7 +12,7 @@ function isPet(pet: any): pet is Pet { return typeof pet.name === "string"; >typeof pet.name === "string" : boolean ->typeof pet.name : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof pet.name : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >pet.name : any >pet : any >name : any diff --git a/tests/baselines/reference/nestedLoopTypeGuards.types b/tests/baselines/reference/nestedLoopTypeGuards.types index e0279325012..116dd97e094 100644 --- a/tests/baselines/reference/nestedLoopTypeGuards.types +++ b/tests/baselines/reference/nestedLoopTypeGuards.types @@ -9,7 +9,7 @@ function f1() { if (typeof a !== 'boolean') { >typeof a !== 'boolean' : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : string | number | boolean >'boolean' : "boolean" @@ -34,7 +34,7 @@ function f1() { if (typeof a === 'string') { >typeof a === 'string' : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : string | number >'string' : "string" @@ -66,7 +66,7 @@ function f2() { if (typeof a === 'string') { >typeof a === 'string' : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : string | number >'string' : "string" @@ -78,7 +78,7 @@ function f2() { if (typeof a === 'string') { >typeof a === 'string' : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : string >'string' : "string" diff --git a/tests/baselines/reference/neverType.types b/tests/baselines/reference/neverType.types index 482f208eddb..7ae38d11f76 100644 --- a/tests/baselines/reference/neverType.types +++ b/tests/baselines/reference/neverType.types @@ -160,7 +160,7 @@ function f1(x: string | number) { if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"boolean" : "boolean" @@ -178,7 +178,7 @@ function f2(x: string | number) { if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"boolean" : "boolean" diff --git a/tests/baselines/reference/nonPrimitiveNarrow.types b/tests/baselines/reference/nonPrimitiveNarrow.types index d9abc6b252d..92b3ef0ea2e 100644 --- a/tests/baselines/reference/nonPrimitiveNarrow.types +++ b/tests/baselines/reference/nonPrimitiveNarrow.types @@ -27,7 +27,7 @@ if (a instanceof Narrow) { if (typeof a === 'number') { >typeof a === 'number' : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : object >'number' : "number" @@ -44,7 +44,7 @@ var b: object | null if (typeof b === 'object') { >typeof b === 'object' : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : object >'object' : "object" diff --git a/tests/baselines/reference/nonPrimitiveStrictNull.types b/tests/baselines/reference/nonPrimitiveStrictNull.types index 0dd0ace9f49..d313ed10d39 100644 --- a/tests/baselines/reference/nonPrimitiveStrictNull.types +++ b/tests/baselines/reference/nonPrimitiveStrictNull.types @@ -59,7 +59,7 @@ a = e; // ok if (typeof b !== 'object') { >typeof b !== 'object' : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : object | null >'object' : "object" @@ -72,7 +72,7 @@ if (typeof b !== 'object') { if (typeof b === 'object') { >typeof b === 'object' : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : object | null >'object' : "object" @@ -84,7 +84,7 @@ if (typeof b === 'object') { if (typeof d === 'object') { >typeof d === 'object' : boolean ->typeof d : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof d : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >d : object | null | undefined >'object' : "object" @@ -147,7 +147,7 @@ if (d === null) { if (typeof d === 'undefined') { >typeof d === 'undefined' : boolean ->typeof d : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof d : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >d : object | null | undefined >'undefined' : "undefined" diff --git a/tests/baselines/reference/overloadAssignmentCompat.types b/tests/baselines/reference/overloadAssignmentCompat.types index 3e24975e5ce..e91aab8cb5b 100644 --- a/tests/baselines/reference/overloadAssignmentCompat.types +++ b/tests/baselines/reference/overloadAssignmentCompat.types @@ -25,7 +25,7 @@ function attr(nameOrMap: any, value?: string): any { >nameOrMap && typeof nameOrMap === "object" : boolean >nameOrMap : any >typeof nameOrMap === "object" : boolean ->typeof nameOrMap : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof nameOrMap : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >nameOrMap : any >"object" : "object" @@ -64,7 +64,7 @@ function attr2(nameOrMap: any, value?: string): string { >nameOrMap && typeof nameOrMap === "object" : boolean >nameOrMap : any >typeof nameOrMap === "object" : boolean ->typeof nameOrMap : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof nameOrMap : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >nameOrMap : any >"object" : "object" diff --git a/tests/baselines/reference/overloadResolutionOverNonCTLambdas.types b/tests/baselines/reference/overloadResolutionOverNonCTLambdas.types index ce2171f1e9a..c1e89780eaf 100644 --- a/tests/baselines/reference/overloadResolutionOverNonCTLambdas.types +++ b/tests/baselines/reference/overloadResolutionOverNonCTLambdas.types @@ -32,7 +32,7 @@ module Bugs { return typeof args[index] !== 'undefined' >typeof args[index] !== 'undefined' ? args[index] : match : any >typeof args[index] !== 'undefined' : boolean ->typeof args[index] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof args[index] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >args[index] : any >args : any[] >index : any diff --git a/tests/baselines/reference/overloadReturnTypes.types b/tests/baselines/reference/overloadReturnTypes.types index 2fa1b8ef3ec..f455d652a02 100644 --- a/tests/baselines/reference/overloadReturnTypes.types +++ b/tests/baselines/reference/overloadReturnTypes.types @@ -24,7 +24,7 @@ function attr(nameOrMap: any, value?: string): any { >nameOrMap && typeof nameOrMap === "object" : boolean >nameOrMap : any >typeof nameOrMap === "object" : boolean ->typeof nameOrMap : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof nameOrMap : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >nameOrMap : any >"object" : "object" diff --git a/tests/baselines/reference/parserharness.types b/tests/baselines/reference/parserharness.types index 222ac9ab945..1d29ff94305 100644 --- a/tests/baselines/reference/parserharness.types +++ b/tests/baselines/reference/parserharness.types @@ -114,7 +114,7 @@ var typescriptServiceFile = IO.readFile(typescriptServiceFileName); if (typeof ActiveXObject === "function") { >typeof ActiveXObject === "function" : boolean ->typeof ActiveXObject : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ActiveXObject : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ActiveXObject : any >"function" : "function" @@ -125,7 +125,7 @@ if (typeof ActiveXObject === "function") { } else if (typeof require === "function") { >typeof require === "function" : boolean ->typeof require : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof require : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >require : any >"function" : "function" @@ -998,7 +998,7 @@ module Harness { if (typeof loggers[i][field] === 'function') { >typeof loggers[i][field] === 'function' : boolean ->typeof loggers[i][field] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof loggers[i][field] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >loggers[i][field] : any >loggers[i] : ILogger >loggers : ILogger[] @@ -1849,11 +1849,11 @@ module Harness { if (typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined") { >typeof WScript !== "undefined" && typeof global['WScript'].InitializeProjection !== "undefined" : boolean >typeof WScript !== "undefined" : boolean ->typeof WScript : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof WScript : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >WScript : typeof WScript >"undefined" : "undefined" >typeof global['WScript'].InitializeProjection !== "undefined" : boolean ->typeof global['WScript'].InitializeProjection : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof global['WScript'].InitializeProjection : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >global['WScript'].InitializeProjection : any >global['WScript'] : any >global : any @@ -2703,7 +2703,7 @@ module Harness { >fileExists : (s: string) => boolean >s : string >typeof this.fileCollection[s] !== 'undefined' : boolean ->typeof this.fileCollection[s] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this.fileCollection[s] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this.fileCollection[s] : any >this.fileCollection : {} >this : this @@ -3679,7 +3679,7 @@ module Harness { if (typeof target === "string") { >typeof target === "string" : boolean ->typeof target : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof target : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >target : any >"string" : "string" @@ -3690,7 +3690,7 @@ module Harness { } else if (typeof target === "number") { >typeof target === "number" : boolean ->typeof target : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof target : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >target : any >"number" : "number" @@ -3705,8 +3705,8 @@ module Harness { >Error : ErrorConstructor >"Expected string or number not " + (typeof target) : string >"Expected string or number not " : "Expected string or number not " ->(typeof target) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof target : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>(typeof target) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof target : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >target : any } @@ -7642,7 +7642,7 @@ module Harness { if (typeof process !== "undefined") { >typeof process !== "undefined" : boolean ->typeof process : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof process : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >process : typeof process >"undefined" : "undefined" diff --git a/tests/baselines/reference/prefixUnaryOperatorsOnExportedVariables.types b/tests/baselines/reference/prefixUnaryOperatorsOnExportedVariables.types index 42763ee46bd..e96dad97bd4 100644 --- a/tests/baselines/reference/prefixUnaryOperatorsOnExportedVariables.types +++ b/tests/baselines/reference/prefixUnaryOperatorsOnExportedVariables.types @@ -38,7 +38,7 @@ if (void x) { } if (typeof x) { ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : false } diff --git a/tests/baselines/reference/recursiveTypeRelations.types b/tests/baselines/reference/recursiveTypeRelations.types index 3ca21ccd8e5..cb0baef7919 100644 --- a/tests/baselines/reference/recursiveTypeRelations.types +++ b/tests/baselines/reference/recursiveTypeRelations.types @@ -53,7 +53,7 @@ export function css(styles: S, ...classNam } if (typeof arg == "string") { >typeof arg == "string" : boolean ->typeof arg : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof arg : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >arg : ClassNameArg >"string" : "string" @@ -64,7 +64,7 @@ export function css(styles: S, ...classNam } if (typeof arg == "object") { >typeof arg == "object" : boolean ->typeof arg : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof arg : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >arg : ClassNameArg >"object" : "object" diff --git a/tests/baselines/reference/reservedWords2.types b/tests/baselines/reference/reservedWords2.types index ecbd896de63..2ec19e01618 100644 --- a/tests/baselines/reference/reservedWords2.types +++ b/tests/baselines/reference/reservedWords2.types @@ -14,7 +14,7 @@ import * as while from "foo" >"foo" : "foo" var typeof = 10; ->typeof : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" > : any >10 : 10 diff --git a/tests/baselines/reference/returnTagTypeGuard.types b/tests/baselines/reference/returnTagTypeGuard.types index 5608cc38088..214099b8eb3 100644 --- a/tests/baselines/reference/returnTagTypeGuard.types +++ b/tests/baselines/reference/returnTagTypeGuard.types @@ -79,7 +79,7 @@ function isBoolean(value) { return typeof value === "boolean"; >typeof value === "boolean" : boolean ->typeof value : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof value : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >value : any >"boolean" : "boolean" } @@ -110,7 +110,7 @@ function isNumber(x) { return typeof x === "number" } >isNumber : (x: unknown) => x is number >x : unknown >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown >"number" : "number" diff --git a/tests/baselines/reference/strictTypeofUnionNarrowing.types b/tests/baselines/reference/strictTypeofUnionNarrowing.types index 1ec44e14ff0..bfaabcb3946 100644 --- a/tests/baselines/reference/strictTypeofUnionNarrowing.types +++ b/tests/baselines/reference/strictTypeofUnionNarrowing.types @@ -7,7 +7,7 @@ function stringify1(anything: { toString(): string } | undefined): string { return typeof anything === "string" ? anything.toUpperCase() : ""; >typeof anything === "string" ? anything.toUpperCase() : "" : string >typeof anything === "string" : boolean ->typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof anything : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >anything : { toString(): string; } | undefined >"string" : "string" >anything.toUpperCase() : string @@ -24,7 +24,7 @@ function stringify2(anything: {} | undefined): string { return typeof anything === "string" ? anything.toUpperCase() : ""; >typeof anything === "string" ? anything.toUpperCase() : "" : string >typeof anything === "string" : boolean ->typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof anything : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >anything : {} | undefined >"string" : "string" >anything.toUpperCase() : string @@ -41,7 +41,7 @@ function stringify3(anything: unknown | undefined): string { // should simplify return typeof anything === "string" ? anything.toUpperCase() : ""; >typeof anything === "string" ? anything.toUpperCase() : "" : string >typeof anything === "string" : boolean ->typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof anything : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >anything : unknown >"string" : "string" >anything.toUpperCase() : string @@ -59,7 +59,7 @@ function stringify4(anything: { toString?(): string } | undefined): string { return typeof anything === "string" ? anything.toUpperCase() : ""; >typeof anything === "string" ? anything.toUpperCase() : "" : string >typeof anything === "string" : boolean ->typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof anything : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >anything : {} | undefined >"string" : "string" >anything.toUpperCase() : string diff --git a/tests/baselines/reference/switchStatements.types b/tests/baselines/reference/switchStatements.types index 306483739e8..19c35398b0b 100644 --- a/tests/baselines/reference/switchStatements.types +++ b/tests/baselines/reference/switchStatements.types @@ -60,11 +60,11 @@ switch (x) { >'a' : "a" case typeof x: ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any case typeof M: ->typeof M : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M : typeof M case M.fn(1): diff --git a/tests/baselines/reference/symbolType17.types b/tests/baselines/reference/symbolType17.types index e9f808f453f..c093051ff59 100644 --- a/tests/baselines/reference/symbolType17.types +++ b/tests/baselines/reference/symbolType17.types @@ -10,7 +10,7 @@ x; if (typeof x === "symbol") { >typeof x === "symbol" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : symbol | Foo >"symbol" : "symbol" diff --git a/tests/baselines/reference/symbolType18.types b/tests/baselines/reference/symbolType18.types index 1329a827dce..d6ed93ef7f0 100644 --- a/tests/baselines/reference/symbolType18.types +++ b/tests/baselines/reference/symbolType18.types @@ -10,7 +10,7 @@ x; if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : symbol | Foo >"object" : "object" diff --git a/tests/baselines/reference/symbolType19.types b/tests/baselines/reference/symbolType19.types index 086cccfec06..99b157fe166 100644 --- a/tests/baselines/reference/symbolType19.types +++ b/tests/baselines/reference/symbolType19.types @@ -10,7 +10,7 @@ x; if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : symbol | E >"number" : "number" diff --git a/tests/baselines/reference/symbolType3.types b/tests/baselines/reference/symbolType3.types index 6f31861fd93..074a65d5130 100644 --- a/tests/baselines/reference/symbolType3.types +++ b/tests/baselines/reference/symbolType3.types @@ -17,7 +17,7 @@ void Symbol.toPrimitive; >toPrimitive : symbol typeof Symbol.toStringTag; ->typeof Symbol.toStringTag : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof Symbol.toStringTag : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Symbol.toStringTag : symbol >Symbol : SymbolConstructor >toStringTag : symbol diff --git a/tests/baselines/reference/templateStringInTypeOf.types b/tests/baselines/reference/templateStringInTypeOf.types index 5de62164a70..195150c6aa8 100644 --- a/tests/baselines/reference/templateStringInTypeOf.types +++ b/tests/baselines/reference/templateStringInTypeOf.types @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/templates/templateStringInTypeOf.ts === var x = typeof `abc${ 123 }def`; ->x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof `abc${ 123 }def` : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof `abc${ 123 }def` : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >`abc${ 123 }def` : string >123 : 123 diff --git a/tests/baselines/reference/templateStringInTypeOfES6.types b/tests/baselines/reference/templateStringInTypeOfES6.types index cc035a25501..27aab9cc9d9 100644 --- a/tests/baselines/reference/templateStringInTypeOfES6.types +++ b/tests/baselines/reference/templateStringInTypeOfES6.types @@ -1,7 +1,7 @@ === tests/cases/conformance/es6/templates/templateStringInTypeOfES6.ts === var x = typeof `abc${ 123 }def`; ->x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof `abc${ 123 }def` : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof `abc${ 123 }def` : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >`abc${ 123 }def` : string >123 : 123 diff --git a/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperator.types b/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperator.types index a7811bd03bd..3069fbb80f3 100644 --- a/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperator.types +++ b/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperator.types @@ -2,6 +2,6 @@ var x = `abc${ typeof "hi" }def`; >x : string >`abc${ typeof "hi" }def` : string ->typeof "hi" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "hi" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"hi" : "hi" diff --git a/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperatorES6.types b/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperatorES6.types index 27e593bf4b3..35608d6f604 100644 --- a/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperatorES6.types +++ b/tests/baselines/reference/templateStringWithEmbeddedTypeOfOperatorES6.types @@ -2,6 +2,6 @@ var x = `abc${ typeof "hi" }def`; >x : string >`abc${ typeof "hi" }def` : string ->typeof "hi" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "hi" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"hi" : "hi" diff --git a/tests/baselines/reference/thisTypeInTypePredicate.types b/tests/baselines/reference/thisTypeInTypePredicate.types index e13f8e3fc9c..c31ab771e79 100644 --- a/tests/baselines/reference/thisTypeInTypePredicate.types +++ b/tests/baselines/reference/thisTypeInTypePredicate.types @@ -13,6 +13,6 @@ const numbers = filter((x): x is number => 'number' == typeof x) >x : any >'number' == typeof x : boolean >'number' : "number" ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any diff --git a/tests/baselines/reference/throwStatements.types b/tests/baselines/reference/throwStatements.types index b07a32e92c0..4efe80360a1 100644 --- a/tests/baselines/reference/throwStatements.types +++ b/tests/baselines/reference/throwStatements.types @@ -163,7 +163,7 @@ throw aModule; >aModule : typeof M throw typeof M; ->typeof M : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M : typeof M var aClassInModule = new M.A(); diff --git a/tests/baselines/reference/typeGuardEnums.types b/tests/baselines/reference/typeGuardEnums.types index 4c3ae152475..8fda9ebe1a9 100644 --- a/tests/baselines/reference/typeGuardEnums.types +++ b/tests/baselines/reference/typeGuardEnums.types @@ -10,7 +10,7 @@ let x: number|string|E|V; if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | E | V >"number" : "number" @@ -24,7 +24,7 @@ else { if (typeof x !== "number") { >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | E | V >"number" : "number" diff --git a/tests/baselines/reference/typeGuardInClass.types b/tests/baselines/reference/typeGuardInClass.types index dc7d1daa992..60e2b214784 100644 --- a/tests/baselines/reference/typeGuardInClass.types +++ b/tests/baselines/reference/typeGuardInClass.types @@ -4,7 +4,7 @@ let x: string | number; if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardIntersectionTypes.types b/tests/baselines/reference/typeGuardIntersectionTypes.types index 1458d21301d..a9f43b49179 100644 --- a/tests/baselines/reference/typeGuardIntersectionTypes.types +++ b/tests/baselines/reference/typeGuardIntersectionTypes.types @@ -134,7 +134,7 @@ function hasLegs(x: Beast): x is Legged { return x && typeof x.legs === 'number' >x && typeof x.legs === 'number' : boolean >x : Beast >typeof x.legs === 'number' : boolean ->typeof x.legs : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x.legs : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x.legs : number | undefined >x : Beast >legs : number | undefined diff --git a/tests/baselines/reference/typeGuardNesting.types b/tests/baselines/reference/typeGuardNesting.types index c1396130c05..37f54d94681 100644 --- a/tests/baselines/reference/typeGuardNesting.types +++ b/tests/baselines/reference/typeGuardNesting.types @@ -7,13 +7,13 @@ if ((typeof strOrBool === 'boolean' && !strOrBool) || typeof strOrBool === 'stri >(typeof strOrBool === 'boolean' && !strOrBool) : boolean >typeof strOrBool === 'boolean' && !strOrBool : boolean >typeof strOrBool === 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'boolean' : "boolean" >!strOrBool : boolean >strOrBool : boolean >typeof strOrBool === 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | true >'string' : "string" @@ -22,7 +22,7 @@ if ((typeof strOrBool === 'boolean' && !strOrBool) || typeof strOrBool === 'stri >(typeof strOrBool === 'string') ? strOrBool : "string" : string >(typeof strOrBool === 'string') : boolean >typeof strOrBool === 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'string' : "string" >strOrBool : string @@ -33,7 +33,7 @@ if ((typeof strOrBool === 'boolean' && !strOrBool) || typeof strOrBool === 'stri >(typeof strOrBool === 'boolean') ? strOrBool : false : boolean >(typeof strOrBool === 'boolean') : boolean >typeof strOrBool === 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'boolean' : "boolean" >strOrBool : boolean @@ -44,7 +44,7 @@ if ((typeof strOrBool === 'boolean' && !strOrBool) || typeof strOrBool === 'stri >(typeof strOrBool !== 'boolean') ? strOrBool : "string" : string >(typeof strOrBool !== 'boolean') : boolean >typeof strOrBool !== 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'boolean' : "boolean" >strOrBool : string @@ -55,7 +55,7 @@ if ((typeof strOrBool === 'boolean' && !strOrBool) || typeof strOrBool === 'stri >(typeof strOrBool !== 'string') ? strOrBool : false : boolean >(typeof strOrBool !== 'string') : boolean >typeof strOrBool !== 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'string' : "string" >strOrBool : boolean @@ -67,13 +67,13 @@ if ((typeof strOrBool !== 'string' && !strOrBool) || typeof strOrBool !== 'boole >(typeof strOrBool !== 'string' && !strOrBool) : boolean >typeof strOrBool !== 'string' && !strOrBool : boolean >typeof strOrBool !== 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'string' : "string" >!strOrBool : boolean >strOrBool : boolean >typeof strOrBool !== 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | true >'boolean' : "boolean" @@ -82,7 +82,7 @@ if ((typeof strOrBool !== 'string' && !strOrBool) || typeof strOrBool !== 'boole >(typeof strOrBool === 'string') ? strOrBool : "string" : string >(typeof strOrBool === 'string') : boolean >typeof strOrBool === 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'string' : "string" >strOrBool : string @@ -93,7 +93,7 @@ if ((typeof strOrBool !== 'string' && !strOrBool) || typeof strOrBool !== 'boole >(typeof strOrBool === 'boolean') ? strOrBool : false : boolean >(typeof strOrBool === 'boolean') : boolean >typeof strOrBool === 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'boolean' : "boolean" >strOrBool : boolean @@ -104,7 +104,7 @@ if ((typeof strOrBool !== 'string' && !strOrBool) || typeof strOrBool !== 'boole >(typeof strOrBool !== 'boolean') ? strOrBool : "string" : string >(typeof strOrBool !== 'boolean') : boolean >typeof strOrBool !== 'boolean' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'boolean' : "boolean" >strOrBool : string @@ -115,7 +115,7 @@ if ((typeof strOrBool !== 'string' && !strOrBool) || typeof strOrBool !== 'boole >(typeof strOrBool !== 'string') ? strOrBool : false : boolean >(typeof strOrBool !== 'string') : boolean >typeof strOrBool !== 'string' : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >'string' : "string" >strOrBool : boolean diff --git a/tests/baselines/reference/typeGuardOfFormExpr1AndExpr2.types b/tests/baselines/reference/typeGuardOfFormExpr1AndExpr2.types index ca546d0c7c6..47d231444c6 100644 --- a/tests/baselines/reference/typeGuardOfFormExpr1AndExpr2.types +++ b/tests/baselines/reference/typeGuardOfFormExpr1AndExpr2.types @@ -39,11 +39,11 @@ var strOrNumOrBoolOrC: string | number | boolean | C; if (typeof strOrNumOrBool !== "string" && typeof strOrNumOrBool !== "number") { >typeof strOrNumOrBool !== "string" && typeof strOrNumOrBool !== "number" : boolean >typeof strOrNumOrBool !== "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >typeof strOrNumOrBool !== "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -63,15 +63,15 @@ if (typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "numbe >typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "number" && typeof strOrNumOrBoolOrC !== "boolean" : boolean >typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "number" : boolean >typeof strOrNumOrBoolOrC !== "string" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : string | number | boolean | C >"string" : "string" >typeof strOrNumOrBoolOrC !== "number" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : number | boolean | C >"number" : "number" >typeof strOrNumOrBoolOrC !== "boolean" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : boolean | C >"boolean" : "boolean" @@ -91,15 +91,15 @@ if (typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "numbe >typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "number" && typeof strOrNumOrBool === "boolean" : boolean >typeof strOrNumOrBoolOrC !== "string" && typeof strOrNumOrBoolOrC !== "number" : boolean >typeof strOrNumOrBoolOrC !== "string" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : string | number | boolean | C >"string" : "string" >typeof strOrNumOrBoolOrC !== "number" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : number | boolean | C >"number" : "number" >typeof strOrNumOrBool === "boolean" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"boolean" : "boolean" @@ -126,7 +126,7 @@ else { if (typeof strOrNumOrBool !== "string" && numOrBool !== strOrNumOrBool) { >typeof strOrNumOrBool !== "string" && numOrBool !== strOrNumOrBool : boolean >typeof strOrNumOrBool !== "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >numOrBool !== strOrNumOrBool : boolean diff --git a/tests/baselines/reference/typeGuardOfFormExpr1OrExpr2.types b/tests/baselines/reference/typeGuardOfFormExpr1OrExpr2.types index 50e0c2d158e..840f2e7a0bd 100644 --- a/tests/baselines/reference/typeGuardOfFormExpr1OrExpr2.types +++ b/tests/baselines/reference/typeGuardOfFormExpr1OrExpr2.types @@ -39,11 +39,11 @@ var strOrNumOrBoolOrC: string | number | boolean | C; if (typeof strOrNumOrBool === "string" || typeof strOrNumOrBool === "number") { >typeof strOrNumOrBool === "string" || typeof strOrNumOrBool === "number" : boolean >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >typeof strOrNumOrBool === "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -63,15 +63,15 @@ if (typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "numbe >typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "number" || typeof strOrNumOrBoolOrC === "boolean" : boolean >typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "number" : boolean >typeof strOrNumOrBoolOrC === "string" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : string | number | boolean | C >"string" : "string" >typeof strOrNumOrBoolOrC === "number" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : number | boolean | C >"number" : "number" >typeof strOrNumOrBoolOrC === "boolean" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : boolean | C >"boolean" : "boolean" @@ -91,15 +91,15 @@ if (typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "numbe >typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "number" || typeof strOrNumOrBool !== "boolean" : boolean >typeof strOrNumOrBoolOrC === "string" || typeof strOrNumOrBoolOrC === "number" : boolean >typeof strOrNumOrBoolOrC === "string" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : string | number | boolean | C >"string" : "string" >typeof strOrNumOrBoolOrC === "number" : boolean ->typeof strOrNumOrBoolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBoolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBoolOrC : number | boolean | C >"number" : "number" >typeof strOrNumOrBool !== "boolean" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"boolean" : "boolean" @@ -126,7 +126,7 @@ else { if (typeof strOrNumOrBool === "string" || numOrBool !== strOrNumOrBool) { >typeof strOrNumOrBool === "string" || numOrBool !== strOrNumOrBool : boolean >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >numOrBool !== strOrNumOrBool : boolean diff --git a/tests/baselines/reference/typeGuardOfFormNotExpr.types b/tests/baselines/reference/typeGuardOfFormNotExpr.types index 624bd7c71fc..6d89d3d8802 100644 --- a/tests/baselines/reference/typeGuardOfFormNotExpr.types +++ b/tests/baselines/reference/typeGuardOfFormNotExpr.types @@ -26,7 +26,7 @@ if (!(typeof strOrNum === "string")) { >!(typeof strOrNum === "string") : boolean >(typeof strOrNum === "string") : boolean >typeof strOrNum === "string" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"string" : "string" @@ -47,11 +47,11 @@ if (!(typeof strOrNumOrBool === "string" || typeof strOrNumOrBool === "number")) >(typeof strOrNumOrBool === "string" || typeof strOrNumOrBool === "number") : boolean >typeof strOrNumOrBool === "string" || typeof strOrNumOrBool === "number" : boolean >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >typeof strOrNumOrBool === "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -72,13 +72,13 @@ if (!(typeof strOrNumOrBool !== "string") || !(typeof strOrNumOrBool !== "number >!(typeof strOrNumOrBool !== "string") : boolean >(typeof strOrNumOrBool !== "string") : boolean >typeof strOrNumOrBool !== "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >!(typeof strOrNumOrBool !== "number") : boolean >(typeof strOrNumOrBool !== "number") : boolean >typeof strOrNumOrBool !== "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -99,11 +99,11 @@ if (!(typeof strOrNumOrBool !== "string" && typeof strOrNumOrBool !== "number")) >(typeof strOrNumOrBool !== "string" && typeof strOrNumOrBool !== "number") : boolean >typeof strOrNumOrBool !== "string" && typeof strOrNumOrBool !== "number" : boolean >typeof strOrNumOrBool !== "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >typeof strOrNumOrBool !== "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -124,13 +124,13 @@ if (!(typeof strOrNumOrBool === "string") && !(typeof strOrNumOrBool === "number >!(typeof strOrNumOrBool === "string") : boolean >(typeof strOrNumOrBool === "string") : boolean >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >!(typeof strOrNumOrBool === "number") : boolean >(typeof strOrNumOrBool === "number") : boolean >typeof strOrNumOrBool === "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : number | boolean >"number" : "number" @@ -151,7 +151,7 @@ if (!(typeof strOrNumOrBool === "string") && numOrBool !== strOrNumOrBool) { >!(typeof strOrNumOrBool === "string") : boolean >(typeof strOrNumOrBool === "string") : boolean >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" >numOrBool !== strOrNumOrBool : boolean diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfBoolean.types b/tests/baselines/reference/typeGuardOfFormTypeOfBoolean.types index 72697554f6a..c6d057bef0f 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfBoolean.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfBoolean.types @@ -42,7 +42,7 @@ var c: C; // - when false, removes the primitive type from the type of x. if (typeof strOrBool === "boolean") { >typeof strOrBool === "boolean" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"boolean" : "boolean" @@ -59,7 +59,7 @@ else { } if (typeof numOrBool === "boolean") { >typeof numOrBool === "boolean" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"boolean" : "boolean" @@ -76,7 +76,7 @@ else { } if (typeof strOrNumOrBool === "boolean") { >typeof strOrNumOrBool === "boolean" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"boolean" : "boolean" @@ -93,7 +93,7 @@ else { } if (typeof boolOrC === "boolean") { >typeof boolOrC === "boolean" : boolean ->typeof boolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof boolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >boolOrC : boolean | C >"boolean" : "boolean" @@ -111,7 +111,7 @@ else { if (typeof strOrNum === "boolean") { >typeof strOrNum === "boolean" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"boolean" : "boolean" @@ -131,7 +131,7 @@ else { // - when false, narrows the type of x by typeof x === s when true. if (typeof strOrBool !== "boolean") { >typeof strOrBool !== "boolean" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"boolean" : "boolean" @@ -148,7 +148,7 @@ else { } if (typeof numOrBool !== "boolean") { >typeof numOrBool !== "boolean" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"boolean" : "boolean" @@ -165,7 +165,7 @@ else { } if (typeof strOrNumOrBool !== "boolean") { >typeof strOrNumOrBool !== "boolean" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"boolean" : "boolean" @@ -182,7 +182,7 @@ else { } if (typeof boolOrC !== "boolean") { >typeof boolOrC !== "boolean" : boolean ->typeof boolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof boolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >boolOrC : boolean | C >"boolean" : "boolean" @@ -200,7 +200,7 @@ else { if (typeof strOrNum !== "boolean") { >typeof strOrNum !== "boolean" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"boolean" : "boolean" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.errors.txt b/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.errors.txt index 20cb4233dcf..e10cf2d1a78 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.errors.txt +++ b/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(13,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r1' must be of type 'string', but here has type 'number'. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(20,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r2' must be of type 'boolean', but here has type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(27,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r3' must be of type 'number', but here has type 'boolean'. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(30,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(30,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHasNoEffect.ts(34,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r4' must be of type 'C', but here has type 'string'. @@ -43,7 +43,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfEqualEqualHa if (typeof strOrC == "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. var r4 = strOrC; // string | C } else { diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.types b/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.types index d33d556cf98..9773c2b2225 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfEqualEqualHasNoEffect.types @@ -18,7 +18,7 @@ var strOrC: string | C; // typeof x == s has not effect on typeguard if (typeof strOrNum == "string") { >typeof strOrNum == "string" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"string" : "string" @@ -34,7 +34,7 @@ else { if (typeof strOrBool == "boolean") { >typeof strOrBool == "boolean" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"boolean" : "boolean" @@ -50,7 +50,7 @@ else { if (typeof numOrBool == "number") { >typeof numOrBool == "number" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"number" : "number" @@ -66,7 +66,7 @@ else { if (typeof strOrC == "Object") { >typeof strOrC == "Object" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"Object" : "Object" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfFunction.types b/tests/baselines/reference/typeGuardOfFormTypeOfFunction.types index 69ca4ced215..9729de4bdf5 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfFunction.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfFunction.types @@ -5,7 +5,7 @@ function f1(x: any) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"function" : "function" @@ -20,7 +20,7 @@ function f2(x: unknown) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown >"function" : "function" @@ -35,7 +35,7 @@ function f3(x: {}) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : {} >"function" : "function" @@ -50,7 +50,7 @@ function f4(x: T) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T >"function" : "function" @@ -66,7 +66,7 @@ function f5(x: { s: string }) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : { s: string; } >"function" : "function" @@ -81,7 +81,7 @@ function f6(x: () => string) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : () => string >"function" : "function" @@ -96,7 +96,7 @@ function f10(x: string | (() => string)) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | (() => string) >"function" : "function" @@ -116,7 +116,7 @@ function f11(x: { s: string } | (() => string)) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : { s: string; } | (() => string) >"function" : "function" @@ -137,7 +137,7 @@ function f12(x: { s: string } | { n: number }) { if (typeof x === "function") { >typeof x === "function" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : { s: string; } | { n: number; } >"function" : "function" @@ -169,7 +169,7 @@ function f100(obj: T, keys: K[]) : void { if (typeof item == 'function') >typeof item == 'function' : boolean ->typeof item : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof item : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >item : T[K] >'function' : "function" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfIsOrderIndependent.types b/tests/baselines/reference/typeGuardOfFormTypeOfIsOrderIndependent.types index be594983779..ec2a862f1b6 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfIsOrderIndependent.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfIsOrderIndependent.types @@ -26,7 +26,7 @@ var func: () => void; if ("string" === typeof strOrNum) { >"string" === typeof strOrNum : boolean >"string" : "string" ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number str = strOrNum; @@ -43,7 +43,7 @@ else { if ("function" === typeof strOrFunc) { >"function" === typeof strOrFunc : boolean >"function" : "function" ->typeof strOrFunc : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrFunc : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrFunc : string | (() => void) func = strOrFunc; @@ -60,7 +60,7 @@ else { if ("number" === typeof numOrBool) { >"number" === typeof numOrBool : boolean >"number" : "number" ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean num = numOrBool; @@ -77,7 +77,7 @@ else { if ("boolean" === typeof strOrBool) { >"boolean" === typeof strOrBool : boolean >"boolean" : "boolean" ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean bool = strOrBool; diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.errors.txt b/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.errors.txt index fcacac5ba25..a0e9cd0f7bf 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.errors.txt +++ b/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(13,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r1' must be of type 'number', but here has type 'string'. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(20,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r2' must be of type 'string', but here has type 'boolean'. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(27,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r3' must be of type 'boolean', but here has type 'number'. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(30,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(30,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasNoEffect.ts(34,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'r4' must be of type 'string', but here has type 'C'. @@ -43,7 +43,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfNotEqualHasN if (typeof strOrC != "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. var r4 = strOrC; // string | C } else { diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.types b/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.types index 0a0f835070f..0d452125ee8 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfNotEqualHasNoEffect.types @@ -18,7 +18,7 @@ var strOrC: string | C; // typeof x != s has not effect on typeguard if (typeof strOrNum != "string") { >typeof strOrNum != "string" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"string" : "string" @@ -34,7 +34,7 @@ else { if (typeof strOrBool != "boolean") { >typeof strOrBool != "boolean" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"boolean" : "boolean" @@ -50,7 +50,7 @@ else { if (typeof numOrBool != "number") { >typeof numOrBool != "number" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"number" : "number" @@ -66,7 +66,7 @@ else { if (typeof strOrC != "Object") { >typeof strOrC != "Object" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"Object" : "Object" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfNumber.types b/tests/baselines/reference/typeGuardOfFormTypeOfNumber.types index db95bff3e83..54d60e53bd7 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfNumber.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfNumber.types @@ -42,7 +42,7 @@ var c: C; // - when false, removes the primitive type from the type of x. if (typeof strOrNum === "number") { >typeof strOrNum === "number" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"number" : "number" @@ -59,7 +59,7 @@ else { } if (typeof numOrBool === "number") { >typeof numOrBool === "number" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"number" : "number" @@ -75,7 +75,7 @@ else { } if (typeof strOrNumOrBool === "number") { >typeof strOrNumOrBool === "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"number" : "number" @@ -92,7 +92,7 @@ else { } if (typeof numOrC === "number") { >typeof numOrC === "number" : boolean ->typeof numOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrC : number | C >"number" : "number" @@ -110,7 +110,7 @@ else { if (typeof strOrBool === "number") { >typeof strOrBool === "number" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"number" : "number" @@ -129,7 +129,7 @@ else { // - when false, narrows the type of x by typeof x === s when true. if (typeof strOrNum !== "number") { >typeof strOrNum !== "number" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"number" : "number" @@ -146,7 +146,7 @@ else { } if (typeof numOrBool !== "number") { >typeof numOrBool !== "number" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"number" : "number" @@ -162,7 +162,7 @@ else { } if (typeof strOrNumOrBool !== "number") { >typeof strOrNumOrBool !== "number" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"number" : "number" @@ -179,7 +179,7 @@ else { } if (typeof numOrC !== "number") { >typeof numOrC !== "number" : boolean ->typeof numOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrC : number | C >"number" : "number" @@ -197,7 +197,7 @@ else { if (typeof strOrBool !== "number") { >typeof strOrBool !== "number" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"number" : "number" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfOther.errors.txt b/tests/baselines/reference/typeGuardOfFormTypeOfOther.errors.txt index 0672bb4841c..d310abe9cd2 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfOther.errors.txt +++ b/tests/baselines/reference/typeGuardOfFormTypeOfOther.errors.txt @@ -1,15 +1,15 @@ -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(21,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(27,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(33,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(21,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(27,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(33,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(40,5): error TS2322: Type 'string | C' is not assignable to type 'C'. Type 'string' is not assignable to type 'C'. tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(43,9): error TS2322: Type 'string | C' is not assignable to type 'string'. Type 'C' is not assignable to type 'string'. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(46,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(56,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(62,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(68,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. -tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(46,5): error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(56,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(62,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(68,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75,5): error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. ==== tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts (10 errors) ==== @@ -35,7 +35,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, if (typeof strOrC === "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. c = strOrC; // C } else { @@ -43,7 +43,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, } if (typeof numOrC === "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. c = numOrC; // C } else { @@ -51,7 +51,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, } if (typeof boolOrC === "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. c = boolOrC; // C } else { @@ -72,7 +72,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, if (typeof strOrNumOrBool === "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. let q1: {} = strOrNumOrBool; // {} } else { @@ -84,7 +84,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, // - when false, narrows the type of x by typeof x === s when true. if (typeof strOrC !== "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. var r2: string = strOrC; // string } else { @@ -92,7 +92,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, } if (typeof numOrC !== "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. var r3: number = numOrC; // number } else { @@ -100,7 +100,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, } if (typeof boolOrC !== "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. var r4: boolean = boolOrC; // boolean } else { @@ -109,7 +109,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardOfFormTypeOfOther.ts(75, if (typeof strOrNumOrBool !== "Object") { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. +!!! error TS2367: This condition will always return 'true' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"Object"' have no overlap. let q1: string | number | boolean = strOrNumOrBool; // string | number | boolean } else { diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfOther.types b/tests/baselines/reference/typeGuardOfFormTypeOfOther.types index 889810f3447..268dd151293 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfOther.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfOther.types @@ -46,7 +46,7 @@ var c: C; if (typeof strOrC === "Object") { >typeof strOrC === "Object" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"Object" : "Object" @@ -62,7 +62,7 @@ else { } if (typeof numOrC === "Object") { >typeof numOrC === "Object" : boolean ->typeof numOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrC : number | C >"Object" : "Object" @@ -78,7 +78,7 @@ else { } if (typeof boolOrC === "Object") { >typeof boolOrC === "Object" : boolean ->typeof boolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof boolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >boolOrC : boolean | C >"Object" : "Object" @@ -94,7 +94,7 @@ else { } if (typeof strOrC === "Object" as string) { // comparison is OK with cast >typeof strOrC === "Object" as string : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"Object" as string : string >"Object" : "Object" @@ -112,7 +112,7 @@ else { if (typeof strOrNumOrBool === "Object") { >typeof strOrNumOrBool === "Object" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"Object" : "Object" @@ -131,7 +131,7 @@ else { // - when false, narrows the type of x by typeof x === s when true. if (typeof strOrC !== "Object") { >typeof strOrC !== "Object" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"Object" : "Object" @@ -147,7 +147,7 @@ else { } if (typeof numOrC !== "Object") { >typeof numOrC !== "Object" : boolean ->typeof numOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrC : number | C >"Object" : "Object" @@ -163,7 +163,7 @@ else { } if (typeof boolOrC !== "Object") { >typeof boolOrC !== "Object" : boolean ->typeof boolOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof boolOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >boolOrC : boolean | C >"Object" : "Object" @@ -180,7 +180,7 @@ else { if (typeof strOrNumOrBool !== "Object") { >typeof strOrNumOrBool !== "Object" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"Object" : "Object" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types index 4787c07d758..6367eb1776b 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types @@ -8,7 +8,7 @@ let b: {toString(): string}; if (typeof a === "number") { >typeof a === "number" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : {} >"number" : "number" @@ -18,7 +18,7 @@ if (typeof a === "number") { } if (typeof a === "string") { >typeof a === "string" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : {} >"string" : "string" @@ -28,7 +28,7 @@ if (typeof a === "string") { } if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : {} >"boolean" : "boolean" @@ -39,7 +39,7 @@ if (typeof a === "boolean") { if (typeof b === "number") { >typeof b === "number" : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : { toString(): string; } >"number" : "number" @@ -49,7 +49,7 @@ if (typeof b === "number") { } if (typeof b === "string") { >typeof b === "string" : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : { toString(): string; } >"string" : "string" @@ -59,7 +59,7 @@ if (typeof b === "string") { } if (typeof b === "boolean") { >typeof b === "boolean" : boolean ->typeof b : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof b : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >b : { toString(): string; } >"boolean" : "boolean" diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfString.types b/tests/baselines/reference/typeGuardOfFormTypeOfString.types index f211ae80cf2..3c1fd253e3a 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfString.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfString.types @@ -42,7 +42,7 @@ var c: C; // - when false, removes the primitive type from the type of x. if (typeof strOrNum === "string") { >typeof strOrNum === "string" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"string" : "string" @@ -59,7 +59,7 @@ else { } if (typeof strOrBool === "string") { >typeof strOrBool === "string" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"string" : "string" @@ -76,7 +76,7 @@ else { } if (typeof strOrNumOrBool === "string") { >typeof strOrNumOrBool === "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" @@ -93,7 +93,7 @@ else { } if (typeof strOrC === "string") { >typeof strOrC === "string" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"string" : "string" @@ -111,7 +111,7 @@ else { if (typeof numOrBool === "string") { >typeof numOrBool === "string" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"string" : "string" @@ -130,7 +130,7 @@ else { // - when false, narrows the type of x by typeof x === s when true. if (typeof strOrNum !== "string") { >typeof strOrNum !== "string" : boolean ->typeof strOrNum : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNum : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNum : string | number >"string" : "string" @@ -147,7 +147,7 @@ else { } if (typeof strOrBool !== "string") { >typeof strOrBool !== "string" : boolean ->typeof strOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrBool : string | boolean >"string" : "string" @@ -164,7 +164,7 @@ else { } if (typeof strOrNumOrBool !== "string") { >typeof strOrNumOrBool !== "string" : boolean ->typeof strOrNumOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrNumOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrNumOrBool : string | number | boolean >"string" : "string" @@ -181,7 +181,7 @@ else { } if (typeof strOrC !== "string") { >typeof strOrC !== "string" : boolean ->typeof strOrC : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof strOrC : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >strOrC : string | C >"string" : "string" @@ -199,7 +199,7 @@ else { if (typeof numOrBool !== "string") { >typeof numOrBool !== "string" : boolean ->typeof numOrBool : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof numOrBool : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >numOrBool : number | boolean >"string" : "string" diff --git a/tests/baselines/reference/typeGuardOnContainerTypeNoHang.types b/tests/baselines/reference/typeGuardOnContainerTypeNoHang.types index 43c286336a7..3448feb0ce6 100644 --- a/tests/baselines/reference/typeGuardOnContainerTypeNoHang.types +++ b/tests/baselines/reference/typeGuardOnContainerTypeNoHang.types @@ -9,7 +9,7 @@ export namespace TypeGuards { return typeof(value) === 'object' >typeof(value) === 'object' : boolean ->typeof(value) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof(value) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(value) : any >value : any >'object' : "object" diff --git a/tests/baselines/reference/typeGuardRedundancy.types b/tests/baselines/reference/typeGuardRedundancy.types index 2023defbb43..10bec968ed2 100644 --- a/tests/baselines/reference/typeGuardRedundancy.types +++ b/tests/baselines/reference/typeGuardRedundancy.types @@ -7,11 +7,11 @@ var r1 = typeof x === "string" && typeof x === "string" ? x.substr : x.toFixed; >typeof x === "string" && typeof x === "string" ? x.substr : x.toFixed : (from: number, length?: number) => string >typeof x === "string" && typeof x === "string" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string >"string" : "string" >x.substr : (from: number, length?: number) => string @@ -28,11 +28,11 @@ var r2 = !(typeof x === "string" && typeof x === "string") ? x.toFixed : x.subst >(typeof x === "string" && typeof x === "string") : boolean >typeof x === "string" && typeof x === "string" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string >"string" : "string" >x.toFixed : (fractionDigits?: number) => string @@ -47,11 +47,11 @@ var r3 = typeof x === "string" || typeof x === "string" ? x.substr : x.toFixed; >typeof x === "string" || typeof x === "string" ? x.substr : x.toFixed : (from: number, length?: number) => string >typeof x === "string" || typeof x === "string" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number >"string" : "string" >x.substr : (from: number, length?: number) => string @@ -68,11 +68,11 @@ var r4 = !(typeof x === "string" || typeof x === "string") ? x.toFixed : x.subst >(typeof x === "string" || typeof x === "string") : boolean >typeof x === "string" || typeof x === "string" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number >"string" : "string" >x.toFixed : (fractionDigits?: number) => string diff --git a/tests/baselines/reference/typeGuardTautologicalConsistiency.types b/tests/baselines/reference/typeGuardTautologicalConsistiency.types index 136b09674d8..02e3945c8e0 100644 --- a/tests/baselines/reference/typeGuardTautologicalConsistiency.types +++ b/tests/baselines/reference/typeGuardTautologicalConsistiency.types @@ -4,13 +4,13 @@ let stringOrNumber: string | number; if (typeof stringOrNumber === "number") { >typeof stringOrNumber === "number" : boolean ->typeof stringOrNumber : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof stringOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >stringOrNumber : string | number >"number" : "number" if (typeof stringOrNumber !== "number") { >typeof stringOrNumber !== "number" : boolean ->typeof stringOrNumber : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof stringOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >stringOrNumber : number >"number" : "number" @@ -22,11 +22,11 @@ if (typeof stringOrNumber === "number") { if (typeof stringOrNumber === "number" && typeof stringOrNumber !== "number") { >typeof stringOrNumber === "number" && typeof stringOrNumber !== "number" : boolean >typeof stringOrNumber === "number" : boolean ->typeof stringOrNumber : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof stringOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >stringOrNumber : string | number >"number" : "number" >typeof stringOrNumber !== "number" : boolean ->typeof stringOrNumber : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof stringOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >stringOrNumber : number >"number" : "number" diff --git a/tests/baselines/reference/typeGuardTypeOfUndefined.types b/tests/baselines/reference/typeGuardTypeOfUndefined.types index 00777ac0eae..750d44bb45c 100644 --- a/tests/baselines/reference/typeGuardTypeOfUndefined.types +++ b/tests/baselines/reference/typeGuardTypeOfUndefined.types @@ -6,13 +6,13 @@ function test1(a: any) { if (typeof a !== "undefined") { >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"boolean" : "boolean" @@ -36,13 +36,13 @@ function test2(a: any) { if (typeof a === "undefined") { >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : undefined >"boolean" : "boolean" @@ -67,11 +67,11 @@ function test3(a: any) { if (typeof a === "undefined" || typeof a === "boolean") { >typeof a === "undefined" || typeof a === "boolean" : boolean >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"boolean" : "boolean" @@ -91,11 +91,11 @@ function test4(a: any) { if (typeof a !== "undefined" && typeof a === "boolean") { >typeof a !== "undefined" && typeof a === "boolean" : boolean >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : any >"boolean" : "boolean" @@ -114,13 +114,13 @@ function test5(a: boolean | void) { if (typeof a !== "undefined") { >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean | void >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean >"boolean" : "boolean" @@ -144,13 +144,13 @@ function test6(a: boolean | void) { if (typeof a === "undefined") { >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean | void >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : undefined >"boolean" : "boolean" @@ -175,11 +175,11 @@ function test7(a: boolean | void) { if (typeof a === "undefined" || typeof a === "boolean") { >typeof a === "undefined" || typeof a === "boolean" : boolean >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean | void >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean >"boolean" : "boolean" @@ -199,11 +199,11 @@ function test8(a: boolean | void) { if (typeof a !== "undefined" && typeof a === "boolean") { >typeof a !== "undefined" && typeof a === "boolean" : boolean >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean | void >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : boolean >"boolean" : "boolean" @@ -222,13 +222,13 @@ function test9(a: boolean | number) { if (typeof a !== "undefined") { >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" @@ -252,13 +252,13 @@ function test10(a: boolean | number) { if (typeof a === "undefined") { >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : undefined >"boolean" : "boolean" @@ -283,11 +283,11 @@ function test11(a: boolean | number) { if (typeof a === "undefined" || typeof a === "boolean") { >typeof a === "undefined" || typeof a === "boolean" : boolean >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" @@ -307,11 +307,11 @@ function test12(a: boolean | number) { if (typeof a !== "undefined" && typeof a === "boolean") { >typeof a !== "undefined" && typeof a === "boolean" : boolean >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" @@ -330,13 +330,13 @@ function test13(a: boolean | number | void) { if (typeof a !== "undefined") { >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean | void >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" @@ -360,13 +360,13 @@ function test14(a: boolean | number | void) { if (typeof a === "undefined") { >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean | void >"undefined" : "undefined" if (typeof a === "boolean") { >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : undefined >"boolean" : "boolean" @@ -391,11 +391,11 @@ function test15(a: boolean | number | void) { if (typeof a === "undefined" || typeof a === "boolean") { >typeof a === "undefined" || typeof a === "boolean" : boolean >typeof a === "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean | void >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" @@ -415,11 +415,11 @@ function test16(a: boolean | number | void) { if (typeof a !== "undefined" && typeof a === "boolean") { >typeof a !== "undefined" && typeof a === "boolean" : boolean >typeof a !== "undefined" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean | void >"undefined" : "undefined" >typeof a === "boolean" : boolean ->typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >a : number | boolean >"boolean" : "boolean" diff --git a/tests/baselines/reference/typeGuardsAsAssertions.types b/tests/baselines/reference/typeGuardsAsAssertions.types index 792ac950aae..4139c84f77d 100644 --- a/tests/baselines/reference/typeGuardsAsAssertions.types +++ b/tests/baselines/reference/typeGuardsAsAssertions.types @@ -96,7 +96,7 @@ function foo1() { >x : string | number | boolean >typeof x === "string" ? x.slice() : "abc" : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >x.slice() : string @@ -130,7 +130,7 @@ function foo2() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -189,7 +189,7 @@ function f2() { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : undefined >"string" : "string" @@ -232,7 +232,7 @@ function f4() { if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : undefined >"boolean" : "boolean" @@ -250,11 +250,11 @@ function f5(x: string | number) { if (typeof x === "string" && typeof x === "number") { >typeof x === "string" && typeof x === "number" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string >"number" : "number" diff --git a/tests/baselines/reference/typeGuardsDefeat.types b/tests/baselines/reference/typeGuardsDefeat.types index eb46a998edb..90eb6c6db2d 100644 --- a/tests/baselines/reference/typeGuardsDefeat.types +++ b/tests/baselines/reference/typeGuardsDefeat.types @@ -15,7 +15,7 @@ function foo(x: number | string) { } if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -40,7 +40,7 @@ function foo2(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -76,7 +76,7 @@ function foo3(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInClassAccessors.types b/tests/baselines/reference/typeGuardsInClassAccessors.types index cd1b94d9ea9..3cc6901133c 100644 --- a/tests/baselines/reference/typeGuardsInClassAccessors.types +++ b/tests/baselines/reference/typeGuardsInClassAccessors.types @@ -25,7 +25,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -41,7 +41,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -62,7 +62,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -75,7 +75,7 @@ class ClassWithAccessors { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -91,7 +91,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -108,7 +108,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -124,7 +124,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -145,7 +145,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -158,7 +158,7 @@ class ClassWithAccessors { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -174,7 +174,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -191,7 +191,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -207,7 +207,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -228,7 +228,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -241,7 +241,7 @@ class ClassWithAccessors { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -257,7 +257,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -274,7 +274,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -290,7 +290,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -311,7 +311,7 @@ class ClassWithAccessors { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -324,7 +324,7 @@ class ClassWithAccessors { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -340,7 +340,7 @@ class ClassWithAccessors { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number diff --git a/tests/baselines/reference/typeGuardsInClassMethods.types b/tests/baselines/reference/typeGuardsInClassMethods.types index 3a45abcf155..2c659bc3f08 100644 --- a/tests/baselines/reference/typeGuardsInClassMethods.types +++ b/tests/baselines/reference/typeGuardsInClassMethods.types @@ -21,7 +21,7 @@ class C1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -37,7 +37,7 @@ class C1 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -50,7 +50,7 @@ class C1 { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -68,7 +68,7 @@ class C1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -84,7 +84,7 @@ class C1 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -97,7 +97,7 @@ class C1 { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -115,7 +115,7 @@ class C1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -131,7 +131,7 @@ class C1 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -144,7 +144,7 @@ class C1 { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -162,7 +162,7 @@ class C1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -178,7 +178,7 @@ class C1 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -191,7 +191,7 @@ class C1 { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -209,7 +209,7 @@ class C1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -225,7 +225,7 @@ class C1 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -238,7 +238,7 @@ class C1 { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number diff --git a/tests/baselines/reference/typeGuardsInConditionalExpression.types b/tests/baselines/reference/typeGuardsInConditionalExpression.types index 85d5380675d..19e11e2e888 100644 --- a/tests/baselines/reference/typeGuardsInConditionalExpression.types +++ b/tests/baselines/reference/typeGuardsInConditionalExpression.types @@ -13,7 +13,7 @@ function foo(x: number | string) { return typeof x === "string" >typeof x === "string" ? x.length // string : x++ : number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -33,7 +33,7 @@ function foo2(x: number | string) { return typeof x === "string" >typeof x === "string" ? ((x = "hello") && x) // string : x : string | number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -56,7 +56,7 @@ function foo3(x: number | string) { return typeof x === "string" >typeof x === "string" ? ((x = 10) && x) // number : x : number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -79,7 +79,7 @@ function foo4(x: number | string) { return typeof x === "string" >typeof x === "string" ? x // string : ((x = 10) && x) : string | number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -102,7 +102,7 @@ function foo5(x: number | string) { return typeof x === "string" >typeof x === "string" ? x // string : ((x = "hello") && x) : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -126,7 +126,7 @@ function foo6(x: number | string) { return typeof x === "string" >typeof x === "string" ? ((x = 10) && x) // number : ((x = "hello") && x) : string | number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -155,7 +155,7 @@ function foo7(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x === "hello" // boolean : typeof x === "boolean" ? x // boolean : x == 10 : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -167,7 +167,7 @@ function foo7(x: number | string | boolean) { : typeof x === "boolean" >typeof x === "boolean" ? x // boolean : x == 10 : boolean >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -189,7 +189,7 @@ function foo8(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x === "hello" : ((b = x) && // number | boolean (typeof x === "boolean" ? x // boolean : x == 10)) : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -210,7 +210,7 @@ function foo8(x: number | string | boolean) { >(typeof x === "boolean" ? x // boolean : x == 10) : boolean >typeof x === "boolean" ? x // boolean : x == 10 : boolean >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -234,7 +234,7 @@ function foo9(x: number | string) { return typeof x === "string" >typeof x === "string" ? ((y = x.length) && x === "hello") // boolean : x === 10 : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -267,7 +267,7 @@ function foo10(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x // string : ((b = x) // x is number | boolean && typeof x === "number" && x.toString()) : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -285,7 +285,7 @@ function foo10(x: number | string | boolean) { && typeof x === "number" >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -306,7 +306,7 @@ function foo11(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x // string : ((b = x) // x is number | boolean && typeof x === "number" && (x = 10) // assignment to x && x) : string | number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -325,7 +325,7 @@ function foo11(x: number | string | boolean) { && typeof x === "number" >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -349,7 +349,7 @@ function foo12(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? ((x = 10) && x.toString().length) // number : ((b = x) // x is number | boolean && typeof x === "number" && x) : number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -378,7 +378,7 @@ function foo12(x: number | string | boolean) { && typeof x === "number" >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" diff --git a/tests/baselines/reference/typeGuardsInDoStatement.types b/tests/baselines/reference/typeGuardsInDoStatement.types index c663ebbea54..d10a1e1901f 100644 --- a/tests/baselines/reference/typeGuardsInDoStatement.types +++ b/tests/baselines/reference/typeGuardsInDoStatement.types @@ -22,7 +22,7 @@ function a(x: string | number | boolean) { } while (typeof x === "string") >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -52,7 +52,7 @@ function b(x: string | number | boolean) { } while (typeof x === "string") >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -82,7 +82,7 @@ function c(x: string | number) { } while (typeof x === "string") >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInExternalModule.types b/tests/baselines/reference/typeGuardsInExternalModule.types index 86b47f9b5c6..fb5265a72e1 100644 --- a/tests/baselines/reference/typeGuardsInExternalModule.types +++ b/tests/baselines/reference/typeGuardsInExternalModule.types @@ -11,7 +11,7 @@ var var1: string | number; if (typeof var1 === "string") { >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" @@ -38,7 +38,7 @@ export var var2: string | number; if (typeof var2 === "string") { >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInForStatement.types b/tests/baselines/reference/typeGuardsInForStatement.types index 4ad1a283d40..3736ffd04da 100644 --- a/tests/baselines/reference/typeGuardsInForStatement.types +++ b/tests/baselines/reference/typeGuardsInForStatement.types @@ -11,7 +11,7 @@ function a(x: string | number) { >x : string | number >undefined : undefined >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"number" : "number" >x = undefined : undefined @@ -33,7 +33,7 @@ function b(x: string | number) { >x : string | number >undefined : undefined >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"number" : "number" >x = undefined : undefined @@ -58,7 +58,7 @@ function c(x: string | number) { >x : string | number >undefined : undefined >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"number" : "number" >x = undefined : undefined diff --git a/tests/baselines/reference/typeGuardsInFunction.types b/tests/baselines/reference/typeGuardsInFunction.types index a7dca0f709b..1d816e74115 100644 --- a/tests/baselines/reference/typeGuardsInFunction.types +++ b/tests/baselines/reference/typeGuardsInFunction.types @@ -20,7 +20,7 @@ function f(param: string | number) { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -36,7 +36,7 @@ function f(param: string | number) { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -49,7 +49,7 @@ function f(param: string | number) { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -74,7 +74,7 @@ function f1(param: string | number) { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -87,7 +87,7 @@ function f1(param: string | number) { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -100,7 +100,7 @@ function f1(param: string | number) { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -116,7 +116,7 @@ function f1(param: string | number) { >num : number >typeof var3 === "string" && var3.length : number >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" >var3.length : number @@ -128,7 +128,7 @@ function f1(param: string | number) { >num : number >typeof param1 === "string" && param1.length : number >typeof param1 === "string" : boolean ->typeof param1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param1 : string | number >"string" : "string" >param1.length : number @@ -158,7 +158,7 @@ function f2(param: string | number) { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -171,7 +171,7 @@ function f2(param: string | number) { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -184,7 +184,7 @@ function f2(param: string | number) { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -200,7 +200,7 @@ function f2(param: string | number) { >num : number >typeof var3 === "string" && var3.length : number >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" >var3.length : number @@ -212,7 +212,7 @@ function f2(param: string | number) { >num : number >typeof param1 === "string" && param1.length : number >typeof param1 === "string" : boolean ->typeof param1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param1 : string | number >"string" : "string" >param1.length : number @@ -245,7 +245,7 @@ function f3(param: string | number) { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -258,7 +258,7 @@ function f3(param: string | number) { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -271,7 +271,7 @@ function f3(param: string | number) { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -287,7 +287,7 @@ function f3(param: string | number) { >num : number >typeof var3 === "string" && var3.length : number >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" >var3.length : number @@ -299,7 +299,7 @@ function f3(param: string | number) { >num : number >typeof param1 === "string" && param1.length : number >typeof param1 === "string" : boolean ->typeof param1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param1 : string | number >"string" : "string" >param1.length : number @@ -329,7 +329,7 @@ strOrNum = typeof f4() === "string" && f4(); // string | number >strOrNum : string | number >typeof f4() === "string" && f4() : string | number >typeof f4() === "string" : boolean ->typeof f4() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof f4() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >f4() : string | number >f4 : () => string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInFunctionAndModuleBlock.types b/tests/baselines/reference/typeGuardsInFunctionAndModuleBlock.types index a425e4d632e..bf02447300f 100644 --- a/tests/baselines/reference/typeGuardsInFunctionAndModuleBlock.types +++ b/tests/baselines/reference/typeGuardsInFunctionAndModuleBlock.types @@ -8,7 +8,7 @@ function foo(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x : function f() { var b = x; // number | boolean return typeof x === "boolean" ? x.toString() // boolean : x.toString(); // number } () : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -27,7 +27,7 @@ function foo(x: number | string | boolean) { return typeof x === "boolean" >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -52,7 +52,7 @@ function foo2(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x : function f(a: number | boolean) { var b = x; // new scope - number | boolean return typeof x === "boolean" ? x.toString() // boolean : x.toString(); // number } (x) : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -72,7 +72,7 @@ function foo2(x: number | string | boolean) { return typeof x === "boolean" >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -98,7 +98,7 @@ function foo3(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x : (() => { var b = x; // new scope - number | boolean return typeof x === "boolean" ? x.toString() // boolean : x.toString(); // number })() : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -117,7 +117,7 @@ function foo3(x: number | string | boolean) { return typeof x === "boolean" >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -142,7 +142,7 @@ function foo4(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" ? x : ((a: number | boolean) => { var b = x; // new scope - number | boolean return typeof x === "boolean" ? x.toString() // boolean : x.toString(); // number })(x) : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -162,7 +162,7 @@ function foo4(x: number | string | boolean) { return typeof x === "boolean" >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -188,7 +188,7 @@ function foo5(x: number | string | boolean) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -223,7 +223,7 @@ module m { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -238,7 +238,7 @@ module m { >y : string >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -275,7 +275,7 @@ module m1 { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -290,7 +290,7 @@ module m1 { >y : string >typeof x === "boolean" ? x.toString() // boolean : x.toString() : string >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" diff --git a/tests/baselines/reference/typeGuardsInGlobal.types b/tests/baselines/reference/typeGuardsInGlobal.types index 7ccc2defe27..27a2f3d09a2 100644 --- a/tests/baselines/reference/typeGuardsInGlobal.types +++ b/tests/baselines/reference/typeGuardsInGlobal.types @@ -11,7 +11,7 @@ var var1: string | number; if (typeof var1 === "string") { >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInIfStatement.types b/tests/baselines/reference/typeGuardsInIfStatement.types index 76ae48432f8..e2e0d19290c 100644 --- a/tests/baselines/reference/typeGuardsInIfStatement.types +++ b/tests/baselines/reference/typeGuardsInIfStatement.types @@ -9,7 +9,7 @@ function foo(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -30,7 +30,7 @@ function foo2(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -53,7 +53,7 @@ function foo3(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -76,7 +76,7 @@ function foo4(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -99,7 +99,7 @@ function foo5(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -122,7 +122,7 @@ function foo6(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -150,7 +150,7 @@ function foo7(x: number | string | boolean) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -161,7 +161,7 @@ function foo7(x: number | string | boolean) { } else if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -181,7 +181,7 @@ function foo8(x: number | string | boolean) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -197,7 +197,7 @@ function foo8(x: number | string | boolean) { if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"boolean" : "boolean" @@ -222,7 +222,7 @@ function foo9(x: number | string) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -253,7 +253,7 @@ function foo10(x: number | string | boolean) { // Mixing typeguard narrowing in if statement with conditional expression typeguard if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -273,7 +273,7 @@ function foo10(x: number | string | boolean) { return typeof x === "number" >typeof x === "number" ? x === 10 // number : x : boolean >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -294,7 +294,7 @@ function foo11(x: number | string | boolean) { // Assigning value to x deep inside another guard stops narrowing of type too if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -312,7 +312,7 @@ function foo11(x: number | string | boolean) { return typeof x === "number" >typeof x === "number" ? ( // change value of x x = 10 && x.toString() // number | boolean | string ) : ( // do not change value y = x && x.toString() // number | boolean | string ) : string >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -356,7 +356,7 @@ function foo12(x: number | string | boolean) { // Assigning value to x in outer guard shouldn't stop narrowing in the inner expression if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -379,7 +379,7 @@ function foo12(x: number | string | boolean) { return typeof x === "number" >typeof x === "number" ? x.toString() // number : x.toString() : any >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number >"number" : "number" diff --git a/tests/baselines/reference/typeGuardsInModule.types b/tests/baselines/reference/typeGuardsInModule.types index a14c47e3cca..0e3e164c0ef 100644 --- a/tests/baselines/reference/typeGuardsInModule.types +++ b/tests/baselines/reference/typeGuardsInModule.types @@ -22,7 +22,7 @@ module m1 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -35,7 +35,7 @@ module m1 { if (typeof var2 === "string") { >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" @@ -59,7 +59,7 @@ module m1 { if (typeof var3 === "string") { >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" @@ -94,7 +94,7 @@ module m2 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -107,7 +107,7 @@ module m2 { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -120,7 +120,7 @@ module m2 { >strOrNum : string | number >typeof var3 === "string" && var3 : string >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" >var3 : string @@ -131,7 +131,7 @@ module m2 { if (typeof var4 === "string") { >typeof var4 === "string" : boolean ->typeof var4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var4 : string | number >"string" : "string" @@ -155,7 +155,7 @@ module m2 { if (typeof var5 === "string") { >typeof var5 === "string" : boolean ->typeof var5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var5 : string | number >"string" : "string" @@ -183,7 +183,7 @@ module m3.m4 { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -196,7 +196,7 @@ module m3.m4 { if (typeof var2 === "string") { >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" @@ -220,7 +220,7 @@ module m3.m4 { if (typeof var3 === "string") { >typeof var3 === "string" : boolean ->typeof var3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var3 : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsInProperties.types b/tests/baselines/reference/typeGuardsInProperties.types index e1a7bd82464..1bf3ee62a41 100644 --- a/tests/baselines/reference/typeGuardsInProperties.types +++ b/tests/baselines/reference/typeGuardsInProperties.types @@ -32,7 +32,7 @@ class C1 { >strOrNum : string | number >typeof this.pp1 === "string" && this.pp1 : string >typeof this.pp1 === "string" : boolean ->typeof this.pp1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this.pp1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this.pp1 : string | number >this : this >pp1 : string | number @@ -46,7 +46,7 @@ class C1 { >strOrNum : string | number >typeof this.pp2 === "string" && this.pp2 : string >typeof this.pp2 === "string" : boolean ->typeof this.pp2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this.pp2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this.pp2 : string | number >this : this >pp2 : string | number @@ -60,7 +60,7 @@ class C1 { >strOrNum : string | number >typeof this.pp3 === "string" && this.pp3 : string >typeof this.pp3 === "string" : boolean ->typeof this.pp3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this.pp3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this.pp3 : string | number >this : this >pp3 : string | number @@ -78,7 +78,7 @@ strOrNum = typeof c1.pp2 === "string" && c1.pp2; // string | number >strOrNum : string | number >typeof c1.pp2 === "string" && c1.pp2 : string >typeof c1.pp2 === "string" : boolean ->typeof c1.pp2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof c1.pp2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >c1.pp2 : string | number >c1 : C1 >pp2 : string | number @@ -92,7 +92,7 @@ strOrNum = typeof c1.pp3 === "string" && c1.pp3; // string | number >strOrNum : string | number >typeof c1.pp3 === "string" && c1.pp3 : string >typeof c1.pp3 === "string" : boolean ->typeof c1.pp3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof c1.pp3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >c1.pp3 : string | number >c1 : C1 >pp3 : string | number @@ -113,7 +113,7 @@ strOrNum = typeof obj1.x === "string" && obj1.x; // string | number >strOrNum : string | number >typeof obj1.x === "string" && obj1.x : string >typeof obj1.x === "string" : boolean ->typeof obj1.x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.x : string | number >obj1 : { x: string | number; } >x : string | number diff --git a/tests/baselines/reference/typeGuardsInRightOperandOfAndAndOperator.types b/tests/baselines/reference/typeGuardsInRightOperandOfAndAndOperator.types index 7235a1d80c2..166dd9ac0e1 100644 --- a/tests/baselines/reference/typeGuardsInRightOperandOfAndAndOperator.types +++ b/tests/baselines/reference/typeGuardsInRightOperandOfAndAndOperator.types @@ -8,7 +8,7 @@ function foo(x: number | string) { return typeof x === "string" && x.length === 10; // string >typeof x === "string" && x.length === 10 : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >x.length === 10 : boolean @@ -25,7 +25,7 @@ function foo2(x: number | string) { return typeof x === "string" && ((x = 10) && x); // string | number >typeof x === "string" && ((x = 10) && x) : number >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >((x = 10) && x) : number @@ -44,7 +44,7 @@ function foo3(x: number | string) { return typeof x === "string" && ((x = "hello") && x); // string | number >typeof x === "string" && ((x = "hello") && x) : string >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >((x = "hello") && x) : string @@ -63,13 +63,13 @@ function foo4(x: number | string | boolean) { >typeof x !== "string" // string | number | boolean && typeof x !== "number" // number | boolean && x : boolean >typeof x !== "string" // string | number | boolean && typeof x !== "number" : boolean >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" && typeof x !== "number" // number | boolean >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -87,7 +87,7 @@ function foo5(x: number | string | boolean) { return typeof x !== "string" // string | number | boolean >typeof x !== "string" // string | number | boolean && ((b = x) && (typeof x !== "number" // number | boolean && x)) : boolean >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -101,7 +101,7 @@ function foo5(x: number | string | boolean) { >(typeof x !== "number" // number | boolean && x) : boolean >typeof x !== "number" // number | boolean && x : boolean >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -116,7 +116,7 @@ function foo6(x: number | string | boolean) { return typeof x !== "string" // string | number | boolean >typeof x !== "string" // string | number | boolean && (typeof x !== "number" // number | boolean ? x // boolean : x === 10) : boolean >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -124,7 +124,7 @@ function foo6(x: number | string | boolean) { >(typeof x !== "number" // number | boolean ? x // boolean : x === 10) : boolean >typeof x !== "number" // number | boolean ? x // boolean : x === 10 : boolean >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -150,7 +150,7 @@ function foo7(x: number | string | boolean) { return typeof x !== "string" >typeof x !== "string" && ((z = x) // number | boolean && (typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // x is number // do not change value : ((y = x) && x.toString()))) : string >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -166,7 +166,7 @@ function foo7(x: number | string | boolean) { >(typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // x is number // do not change value : ((y = x) && x.toString())) : string >typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // x is number // do not change value : ((y = x) && x.toString()) : string >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" diff --git a/tests/baselines/reference/typeGuardsInRightOperandOfOrOrOperator.types b/tests/baselines/reference/typeGuardsInRightOperandOfOrOrOperator.types index d8d807bad70..d3335cd75be 100644 --- a/tests/baselines/reference/typeGuardsInRightOperandOfOrOrOperator.types +++ b/tests/baselines/reference/typeGuardsInRightOperandOfOrOrOperator.types @@ -9,7 +9,7 @@ function foo(x: number | string) { return typeof x !== "string" || x.length === 10; // string >typeof x !== "string" || x.length === 10 : boolean >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >x.length === 10 : boolean @@ -26,7 +26,7 @@ function foo2(x: number | string) { return typeof x !== "string" || ((x = 10) || x); // string | number >typeof x !== "string" || ((x = 10) || x) : number | true >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >((x = 10) || x) : number @@ -45,7 +45,7 @@ function foo3(x: number | string) { return typeof x !== "string" || ((x = "hello") || x); // string | number >typeof x !== "string" || ((x = "hello") || x) : string | true >typeof x !== "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" >((x = "hello") || x) : string @@ -64,13 +64,13 @@ function foo4(x: number | string | boolean) { >typeof x === "string" // string | number | boolean || typeof x === "number" // number | boolean || x : boolean >typeof x === "string" // string | number | boolean || typeof x === "number" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" || typeof x === "number" // number | boolean >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -88,7 +88,7 @@ function foo5(x: number | string | boolean) { return typeof x === "string" // string | number | boolean >typeof x === "string" // string | number | boolean || ((b = x) || (typeof x === "number" // number | boolean || x)) : number | boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -102,7 +102,7 @@ function foo5(x: number | string | boolean) { >(typeof x === "number" // number | boolean || x) : boolean >typeof x === "number" // number | boolean || x : boolean >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -117,7 +117,7 @@ function foo6(x: number | string | boolean) { return typeof x === "string" // string | number | boolean >typeof x === "string" // string | number | boolean || (typeof x !== "number" // number | boolean ? x // boolean : x === 10) : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -125,7 +125,7 @@ function foo6(x: number | string | boolean) { >(typeof x !== "number" // number | boolean ? x // boolean : x === 10) : boolean >typeof x !== "number" // number | boolean ? x // boolean : x === 10 : boolean >typeof x !== "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" @@ -151,7 +151,7 @@ function foo7(x: number | string | boolean) { return typeof x === "string" >typeof x === "string" || ((z = x) // number | boolean || (typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // number | boolean | string // do not change value : ((y = x) && x.toString()))) : string | number | true >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number | boolean >"string" : "string" @@ -167,7 +167,7 @@ function foo7(x: number | string | boolean) { >(typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // number | boolean | string // do not change value : ((y = x) && x.toString())) : string >typeof x === "number" // change value of x ? ((x = 10) && x.toString()) // number | boolean | string // do not change value : ((y = x) && x.toString()) : string >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number | boolean >"number" : "number" diff --git a/tests/baselines/reference/typeGuardsInWhileStatement.types b/tests/baselines/reference/typeGuardsInWhileStatement.types index cdcff209c08..6f2e68d9747 100644 --- a/tests/baselines/reference/typeGuardsInWhileStatement.types +++ b/tests/baselines/reference/typeGuardsInWhileStatement.types @@ -8,7 +8,7 @@ function a(x: string | number) { while (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -29,7 +29,7 @@ function b(x: string | number) { while (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" @@ -53,7 +53,7 @@ function c(x: string | number) { while (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | number >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsNestedAssignments.types b/tests/baselines/reference/typeGuardsNestedAssignments.types index b3d89b2f9e6..31b832e1b31 100644 --- a/tests/baselines/reference/typeGuardsNestedAssignments.types +++ b/tests/baselines/reference/typeGuardsNestedAssignments.types @@ -97,7 +97,7 @@ function f4() { if (typeof (x = getStringOrNumberOrNull()) === "number") { >typeof (x = getStringOrNumberOrNull()) === "number" : boolean ->typeof (x = getStringOrNumberOrNull()) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (x = getStringOrNumberOrNull()) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(x = getStringOrNumberOrNull()) : string | number | null >x = getStringOrNumberOrNull() : string | number | null >x : string | number | null diff --git a/tests/baselines/reference/typeGuardsObjectMethods.types b/tests/baselines/reference/typeGuardsObjectMethods.types index 37121822b28..14e002d6ebd 100644 --- a/tests/baselines/reference/typeGuardsObjectMethods.types +++ b/tests/baselines/reference/typeGuardsObjectMethods.types @@ -27,7 +27,7 @@ var obj1 = { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -43,7 +43,7 @@ var obj1 = { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -56,7 +56,7 @@ var obj1 = { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -76,7 +76,7 @@ var obj1 = { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -92,7 +92,7 @@ var obj1 = { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -113,7 +113,7 @@ var obj1 = { >num : number >typeof var1 === "string" && var1.length : number >typeof var1 === "string" : boolean ->typeof var1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var1 : string | number >"string" : "string" >var1.length : number @@ -129,7 +129,7 @@ var obj1 = { >num : number >typeof var2 === "string" && var2.length : number >typeof var2 === "string" : boolean ->typeof var2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof var2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >var2 : string | number >"string" : "string" >var2.length : number @@ -142,7 +142,7 @@ var obj1 = { >num : number >typeof param === "string" && param.length : number >typeof param === "string" : boolean ->typeof param : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof param : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >param : string | number >"string" : "string" >param.length : number @@ -156,7 +156,7 @@ strOrNum = typeof obj1.method(strOrNum) === "string" && obj1.method(strOrNum); >strOrNum : string | number >typeof obj1.method(strOrNum) === "string" && obj1.method(strOrNum) : string | number >typeof obj1.method(strOrNum) === "string" : boolean ->typeof obj1.method(strOrNum) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.method(strOrNum) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.method(strOrNum) : string | number >obj1.method : (param: string | number) => string | number >obj1 : { method(param: string | number): string | number; prop: string | number; } @@ -175,7 +175,7 @@ strOrNum = typeof obj1.prop === "string" && obj1.prop; >strOrNum : string | number >typeof obj1.prop === "string" && obj1.prop : string >typeof obj1.prop === "string" : boolean ->typeof obj1.prop : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.prop : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.prop : string | number >obj1 : { method(param: string | number): string | number; prop: string | number; } >prop : string | number diff --git a/tests/baselines/reference/typeGuardsOnClassProperty.types b/tests/baselines/reference/typeGuardsOnClassProperty.types index 510fac963d0..6a79412237a 100644 --- a/tests/baselines/reference/typeGuardsOnClassProperty.types +++ b/tests/baselines/reference/typeGuardsOnClassProperty.types @@ -22,7 +22,7 @@ class D { return typeof data === "string" ? data : data.join(" "); >typeof data === "string" ? data : data.join(" ") : string >typeof data === "string" : boolean ->typeof data : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof data : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >data : string | string[] >"string" : "string" >data : string @@ -39,7 +39,7 @@ class D { return typeof this.data === "string" ? this.data : this.data.join(" "); >typeof this.data === "string" ? this.data : this.data.join(" ") : string >typeof this.data === "string" : boolean ->typeof this.data : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof this.data : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >this.data : string | string[] >this : this >data : string | string[] @@ -81,7 +81,7 @@ var o: { if (typeof o.prop1 === "string" && o.prop1.toLowerCase()) {} >typeof o.prop1 === "string" && o.prop1.toLowerCase() : string >typeof o.prop1 === "string" : boolean ->typeof o.prop1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof o.prop1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >o.prop1 : string | number >o : { prop1: string | number; prop2: string | boolean; } >prop1 : string | number @@ -102,7 +102,7 @@ var prop1 = o.prop1; if (typeof prop1 === "string" && prop1.toLocaleLowerCase()) { } >typeof prop1 === "string" && prop1.toLocaleLowerCase() : string >typeof prop1 === "string" : boolean ->typeof prop1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof prop1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >prop1 : string | number >"string" : "string" >prop1.toLocaleLowerCase() : string diff --git a/tests/baselines/reference/typeGuardsTypeParameters.types b/tests/baselines/reference/typeGuardsTypeParameters.types index 71dbb4881aa..e6db4e578e8 100644 --- a/tests/baselines/reference/typeGuardsTypeParameters.types +++ b/tests/baselines/reference/typeGuardsTypeParameters.types @@ -38,7 +38,7 @@ function f2(x: T) { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : T >"string" : "string" @@ -79,7 +79,7 @@ function fun(item: { [P in keyof T]: T[P] }) { if (typeof value === "string") { >typeof value === "string" : boolean ->typeof value : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof value : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >value : { [P in keyof T]: T[P]; }[Extract] >"string" : "string" diff --git a/tests/baselines/reference/typeGuardsWithAny.types b/tests/baselines/reference/typeGuardsWithAny.types index b34257d3843..a483ca6ce74 100644 --- a/tests/baselines/reference/typeGuardsWithAny.types +++ b/tests/baselines/reference/typeGuardsWithAny.types @@ -24,7 +24,7 @@ else { if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"string" : "string" @@ -42,7 +42,7 @@ else { if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"number" : "number" @@ -60,7 +60,7 @@ else { if (typeof x === "boolean") { >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"boolean" : "boolean" @@ -78,7 +78,7 @@ else { if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"object" : "object" diff --git a/tests/baselines/reference/typeOfOperator1.errors.txt b/tests/baselines/reference/typeOfOperator1.errors.txt index 75fc25d243c..137b58c0365 100644 --- a/tests/baselines/reference/typeOfOperator1.errors.txt +++ b/tests/baselines/reference/typeOfOperator1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/typeOfOperator1.ts(3,5): error TS2322: Type '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' is not assignable to type 'number'. +tests/cases/compiler/typeOfOperator1.ts(3,5): error TS2322: Type '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' is not assignable to type 'number'. Type '"string"' is not assignable to type 'number'. @@ -7,5 +7,5 @@ tests/cases/compiler/typeOfOperator1.ts(3,5): error TS2322: Type '"string" | "nu var y: string = typeof x; var z: number = typeof x; ~ -!!! error TS2322: Type '"string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function"' is not assignable to type 'number'. +!!! error TS2322: Type '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' is not assignable to type 'number'. !!! error TS2322: Type '"string"' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/typeOfOperator1.types b/tests/baselines/reference/typeOfOperator1.types index 0fc7b68c7e8..2c1d43a2ee4 100644 --- a/tests/baselines/reference/typeOfOperator1.types +++ b/tests/baselines/reference/typeOfOperator1.types @@ -5,11 +5,11 @@ var x = 1; var y: string = typeof x; >y : string ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number var z: number = typeof x; >z : number ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : number diff --git a/tests/baselines/reference/typeofOperatorInvalidOperations.types b/tests/baselines/reference/typeofOperatorInvalidOperations.types index 7b88d823f4a..06aae70699d 100644 --- a/tests/baselines/reference/typeofOperatorInvalidOperations.types +++ b/tests/baselines/reference/typeofOperatorInvalidOperations.types @@ -5,12 +5,12 @@ var ANY = ANY typeof ; //expect error >ANY : any >ANY : any ->typeof : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" > : any // miss an operand var ANY1 = typeof ; ->ANY1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ANY1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" > : any diff --git a/tests/baselines/reference/typeofOperatorWithAnyOtherType.types b/tests/baselines/reference/typeofOperatorWithAnyOtherType.types index e3b9ae1eea9..37695941e11 100644 --- a/tests/baselines/reference/typeofOperatorWithAnyOtherType.types +++ b/tests/baselines/reference/typeofOperatorWithAnyOtherType.types @@ -62,121 +62,121 @@ var objA = new A(); // any type var var ResultIsString1 = typeof ANY1; ->ResultIsString1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ANY1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY1 : any var ResultIsString2 = typeof ANY2; ->ResultIsString2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ANY2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY2 : any[] var ResultIsString3 = typeof A; ->ResultIsString3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A : typeof A var ResultIsString4 = typeof M; ->ResultIsString4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof M : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M : typeof M var ResultIsString5 = typeof obj; ->ResultIsString5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof obj : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj : () => {} var ResultIsString6 = typeof obj1; ->ResultIsString6 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof obj1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString6 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1 : { x: string; y: () => void; } // any type literal var ResultIsString7 = typeof undefined; ->ResultIsString7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof undefined : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof undefined : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >undefined : undefined var ResultIsString8 = typeof null; ->ResultIsString8 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof null : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString8 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof null : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >null : null var ResultIsString9 = typeof {}; ->ResultIsString9 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof {} : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString9 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof {} : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{} : {} // any type expressions var ResultIsString10 = typeof ANY2[0]; ->ResultIsString10 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ANY2[0] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString10 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY2[0] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY2[0] : any >ANY2 : any[] >0 : 0 var ResultIsString11 = typeof objA.a; ->ResultIsString11 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString11 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : any >objA : A >a : any var ResultIsString12 = typeof obj1.x; ->ResultIsString12 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof obj1.x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString12 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.x : string >obj1 : { x: string; y: () => void; } >x : string var ResultIsString13 = typeof M.n; ->ResultIsString13 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString13 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : any >M : typeof M >n : any var ResultIsString14 = typeof foo(); ->ResultIsString14 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString14 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : any >foo : () => any var ResultIsString15 = typeof A.foo(); ->ResultIsString15 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A.foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString15 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo() : any >A.foo : () => any >A : typeof A >foo : () => any var ResultIsString16 = typeof (ANY + ANY1); ->ResultIsString16 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (ANY + ANY1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString16 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (ANY + ANY1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(ANY + ANY1) : any >ANY + ANY1 : any >ANY : any >ANY1 : any var ResultIsString17 = typeof (null + undefined); ->ResultIsString17 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (null + undefined) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString17 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (null + undefined) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(null + undefined) : any >null + undefined : any >null : null >undefined : undefined var ResultIsString18 = typeof (null + null); ->ResultIsString18 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (null + null) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString18 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (null + null) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(null + null) : any >null + null : any >null : null >null : null var ResultIsString19 = typeof (undefined + undefined); ->ResultIsString19 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (undefined + undefined) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString19 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (undefined + undefined) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(undefined + undefined) : any >undefined + undefined : any >undefined : undefined @@ -184,16 +184,16 @@ var ResultIsString19 = typeof (undefined + undefined); // multiple typeof operators var ResultIsString20 = typeof typeof ANY; ->ResultIsString20 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof ANY : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ANY : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString20 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof ANY : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY : any var ResultIsString21 = typeof typeof typeof (ANY + ANY1); ->ResultIsString21 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof typeof (ANY + ANY1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof (ANY + ANY1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (ANY + ANY1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString21 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof typeof (ANY + ANY1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof (ANY + ANY1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (ANY + ANY1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(ANY + ANY1) : any >ANY + ANY1 : any >ANY : any @@ -201,43 +201,43 @@ var ResultIsString21 = typeof typeof typeof (ANY + ANY1); // miss assignment operators typeof ANY; ->typeof ANY : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY : any typeof ANY1; ->typeof ANY1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY1 : any typeof ANY2[0]; ->typeof ANY2[0] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY2[0] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY2[0] : any >ANY2 : any[] >0 : 0 typeof ANY, ANY1; >typeof ANY, ANY1 : any ->typeof ANY : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY : any >ANY1 : any typeof obj1; ->typeof obj1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1 : { x: string; y: () => void; } typeof obj1.x; ->typeof obj1.x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.x : string >obj1 : { x: string; y: () => void; } >x : string typeof objA.a; ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : any >objA : A >a : any typeof M.n; ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : any >M : typeof M >n : any @@ -254,43 +254,43 @@ var r: () => any; z: typeof ANY; >z : any ->typeof ANY : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY : any x: typeof ANY2; >x : any ->typeof ANY2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ANY2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ANY2 : any[] r: typeof foo; >r : any ->typeof foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo : () => any z: typeof objA.a; >z : any ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : any >objA : A >a : any z: typeof A.foo; >z : any ->typeof A.foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo : () => any >A : typeof A >foo : () => any z: typeof M.n; >z : any ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : any >M : typeof M >n : any z: typeof obj1.x; >z : any ->typeof obj1.x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof obj1.x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >obj1.x : string >obj1 : { x: string; y: () => void; } >x : string diff --git a/tests/baselines/reference/typeofOperatorWithBooleanType.types b/tests/baselines/reference/typeofOperatorWithBooleanType.types index e709a017d1e..c0c6cbf0976 100644 --- a/tests/baselines/reference/typeofOperatorWithBooleanType.types +++ b/tests/baselines/reference/typeofOperatorWithBooleanType.types @@ -31,19 +31,19 @@ var objA = new A(); // boolean type var var ResultIsString1 = typeof BOOLEAN; ->ResultIsString1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof BOOLEAN : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof BOOLEAN : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >BOOLEAN : boolean // boolean type literal var ResultIsString2 = typeof true; ->ResultIsString2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof true : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof true : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >true : true var ResultIsString3 = typeof { x: true, y: false }; ->ResultIsString3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof { x: true, y: false } : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof { x: true, y: false } : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{ x: true, y: false } : { x: boolean; y: boolean; } >x : boolean >true : true @@ -52,28 +52,28 @@ var ResultIsString3 = typeof { x: true, y: false }; // boolean type expressions var ResultIsString4 = typeof objA.a; ->ResultIsString4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : boolean >objA : A >a : boolean var ResultIsString5 = typeof M.n; ->ResultIsString5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : boolean >M : typeof M >n : boolean var ResultIsString6 = typeof foo(); ->ResultIsString6 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString6 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : boolean >foo : () => boolean var ResultIsString7 = typeof A.foo(); ->ResultIsString7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A.foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo() : boolean >A.foo : () => boolean >A : typeof A @@ -81,39 +81,39 @@ var ResultIsString7 = typeof A.foo(); // multiple typeof operator var ResultIsString8 = typeof typeof BOOLEAN; ->ResultIsString8 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof BOOLEAN : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof BOOLEAN : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString8 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof BOOLEAN : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof BOOLEAN : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >BOOLEAN : boolean // miss assignment operators typeof true; ->typeof true : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof true : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >true : true typeof BOOLEAN; ->typeof BOOLEAN : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof BOOLEAN : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >BOOLEAN : boolean typeof foo(); ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : boolean >foo : () => boolean typeof true, false; >typeof true, false : false ->typeof true : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof true : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >true : true >false : false typeof objA.a; ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : boolean >objA : A >a : boolean typeof M.n; ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : boolean >M : typeof M >n : boolean @@ -130,12 +130,12 @@ var r: () => boolean; z: typeof BOOLEAN; >z : any ->typeof BOOLEAN : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof BOOLEAN : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >BOOLEAN : boolean r: typeof foo; >r : any ->typeof foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo : () => boolean var y = { a: true, b: false}; @@ -148,28 +148,28 @@ var y = { a: true, b: false}; z: typeof y.a; >z : any ->typeof y.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof y.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >y.a : boolean >y : { a: boolean; b: boolean; } >a : boolean z: typeof objA.a; >z : any ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : boolean >objA : A >a : boolean z: typeof A.foo; >z : any ->typeof A.foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo : () => boolean >A : typeof A >foo : () => boolean z: typeof M.n; >z : any ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : boolean >M : typeof M >n : boolean diff --git a/tests/baselines/reference/typeofOperatorWithEnumType.types b/tests/baselines/reference/typeofOperatorWithEnumType.types index ccbb7bef2c5..ffe8b70ea80 100644 --- a/tests/baselines/reference/typeofOperatorWithEnumType.types +++ b/tests/baselines/reference/typeofOperatorWithEnumType.types @@ -12,26 +12,26 @@ enum ENUM1 { A, B, "" }; // enum type var var ResultIsString1 = typeof ENUM; ->ResultIsString1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM : typeof ENUM var ResultIsString2 = typeof ENUM1; ->ResultIsString2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ENUM1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM1 : typeof ENUM1 // enum type expressions var ResultIsString3 = typeof ENUM1["A"]; ->ResultIsString3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ENUM1["A"] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM1["A"] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM1["A"] : ENUM1.A >ENUM1 : typeof ENUM1 >"A" : "A" var ResultIsString4 = typeof (ENUM[0] + ENUM1["B"]); ->ResultIsString4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (ENUM[0] + ENUM1["B"]) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (ENUM[0] + ENUM1["B"]) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(ENUM[0] + ENUM1["B"]) : string >ENUM[0] + ENUM1["B"] : string >ENUM[0] : string @@ -43,16 +43,16 @@ var ResultIsString4 = typeof (ENUM[0] + ENUM1["B"]); // multiple typeof operators var ResultIsString5 = typeof typeof ENUM; ->ResultIsString5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM : typeof ENUM var ResultIsString6 = typeof typeof typeof (ENUM[0] + ENUM1.B); ->ResultIsString6 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString6 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (ENUM[0] + ENUM1.B) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(ENUM[0] + ENUM1.B) : string >ENUM[0] + ENUM1.B : string >ENUM[0] : string @@ -64,22 +64,22 @@ var ResultIsString6 = typeof typeof typeof (ENUM[0] + ENUM1.B); // miss assignment operators typeof ENUM; ->typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM : typeof ENUM typeof ENUM1; ->typeof ENUM1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM1 : typeof ENUM1 typeof ENUM1["B"]; ->typeof ENUM1["B"] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM1["B"] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM1["B"] : ENUM1.B >ENUM1 : typeof ENUM1 >"B" : "B" typeof ENUM, ENUM1; >typeof ENUM, ENUM1 : typeof ENUM1 ->typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM : typeof ENUM >ENUM1 : typeof ENUM1 @@ -89,11 +89,11 @@ enum z { }; z: typeof ENUM; >z : any ->typeof ENUM : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM : typeof ENUM z: typeof ENUM1; >z : any ->typeof ENUM1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof ENUM1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >ENUM1 : typeof ENUM1 diff --git a/tests/baselines/reference/typeofOperatorWithNumberType.types b/tests/baselines/reference/typeofOperatorWithNumberType.types index 918fe2dcc3d..e035c206e7f 100644 --- a/tests/baselines/reference/typeofOperatorWithNumberType.types +++ b/tests/baselines/reference/typeofOperatorWithNumberType.types @@ -37,24 +37,24 @@ var objA = new A(); // number type var var ResultIsString1 = typeof NUMBER; ->ResultIsString1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof NUMBER : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER : number var ResultIsString2 = typeof NUMBER1; ->ResultIsString2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof NUMBER1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER1 : number[] // number type literal var ResultIsString3 = typeof 1; ->ResultIsString3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof 1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >1 : 1 var ResultIsString4 = typeof { x: 1, y: 2}; ->ResultIsString4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof { x: 1, y: 2} : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof { x: 1, y: 2} : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{ x: 1, y: 2} : { x: number; y: number; } >x : number >1 : 1 @@ -62,8 +62,8 @@ var ResultIsString4 = typeof { x: 1, y: 2}; >2 : 2 var ResultIsString5 = typeof { x: 1, y: (n: number) => { return n; } }; ->ResultIsString5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof { x: 1, y: (n: number) => { return n; } } : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof { x: 1, y: (n: number) => { return n; } } : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{ x: 1, y: (n: number) => { return n; } } : { x: number; y: (n: number) => number; } >x : number >1 : 1 @@ -74,43 +74,43 @@ var ResultIsString5 = typeof { x: 1, y: (n: number) => { return n; } }; // number type expressions var ResultIsString6 = typeof objA.a; ->ResultIsString6 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString6 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : number >objA : A >a : number var ResultIsString7 = typeof M.n; ->ResultIsString7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : number >M : typeof M >n : number var ResultIsString8 = typeof NUMBER1[0]; ->ResultIsString8 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof NUMBER1[0] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString8 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER1[0] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER1[0] : number >NUMBER1 : number[] >0 : 0 var ResultIsString9 = typeof foo(); ->ResultIsString9 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString9 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : number >foo : () => number var ResultIsString10 = typeof A.foo(); ->ResultIsString10 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A.foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString10 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo() : number >A.foo : () => number >A : typeof A >foo : () => number var ResultIsString11 = typeof (NUMBER + NUMBER); ->ResultIsString11 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (NUMBER + NUMBER) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString11 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (NUMBER + NUMBER) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(NUMBER + NUMBER) : number >NUMBER + NUMBER : number >NUMBER : number @@ -118,16 +118,16 @@ var ResultIsString11 = typeof (NUMBER + NUMBER); // multiple typeof operators var ResultIsString12 = typeof typeof NUMBER; ->ResultIsString12 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof NUMBER : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof NUMBER : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString12 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof NUMBER : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER : number var ResultIsString13 = typeof typeof typeof (NUMBER + NUMBER); ->ResultIsString13 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof typeof (NUMBER + NUMBER) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof (NUMBER + NUMBER) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (NUMBER + NUMBER) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString13 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof typeof (NUMBER + NUMBER) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof (NUMBER + NUMBER) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (NUMBER + NUMBER) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(NUMBER + NUMBER) : number >NUMBER + NUMBER : number >NUMBER : number @@ -135,37 +135,37 @@ var ResultIsString13 = typeof typeof typeof (NUMBER + NUMBER); // miss assignment operators typeof 1; ->typeof 1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof 1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >1 : 1 typeof NUMBER; ->typeof NUMBER : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER : number typeof NUMBER1; ->typeof NUMBER1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER1 : number[] typeof foo(); ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : number >foo : () => number typeof objA.a; ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : number >objA : A >a : number typeof M.n; ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : number >M : typeof M >n : number typeof objA.a, M.n; >typeof objA.a, M.n : number ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : number >objA : A >a : number @@ -182,17 +182,17 @@ var x: number[]; z: typeof NUMBER; >z : any ->typeof NUMBER : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER : number x: typeof NUMBER1; >x : any ->typeof NUMBER1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof NUMBER1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >NUMBER1 : number[] r: typeof foo; >r : any ->typeof foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo : () => number var y = { a: 1, b: 2 }; @@ -205,28 +205,28 @@ var y = { a: 1, b: 2 }; z: typeof y.a; >z : any ->typeof y.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof y.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >y.a : number >y : { a: number; b: number; } >a : number z: typeof objA.a; >z : any ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : number >objA : A >a : number z: typeof A.foo; >z : any ->typeof A.foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo : () => number >A : typeof A >foo : () => number z: typeof M.n; >z : any ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : number >M : typeof M >n : number diff --git a/tests/baselines/reference/typeofOperatorWithStringType.types b/tests/baselines/reference/typeofOperatorWithStringType.types index ca4f445c9e6..c1ae2959c9b 100644 --- a/tests/baselines/reference/typeofOperatorWithStringType.types +++ b/tests/baselines/reference/typeofOperatorWithStringType.types @@ -37,24 +37,24 @@ var objA = new A(); // string type var var ResultIsString1 = typeof STRING; ->ResultIsString1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof STRING : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING : string var ResultIsString2 = typeof STRING1; ->ResultIsString2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof STRING1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING1 : string[] // string type literal var ResultIsString3 = typeof ""; ->ResultIsString3 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof "" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString3 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"" : "" var ResultIsString4 = typeof { x: "", y: "" }; ->ResultIsString4 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof { x: "", y: "" } : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString4 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof { x: "", y: "" } : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{ x: "", y: "" } : { x: string; y: string; } >x : string >"" : "" @@ -62,8 +62,8 @@ var ResultIsString4 = typeof { x: "", y: "" }; >"" : "" var ResultIsString5 = typeof { x: "", y: (s: string) => { return s; } }; ->ResultIsString5 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof { x: "", y: (s: string) => { return s; } } : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString5 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof { x: "", y: (s: string) => { return s; } } : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >{ x: "", y: (s: string) => { return s; } } : { x: string; y: (s: string) => string; } >x : string >"" : "" @@ -74,51 +74,51 @@ var ResultIsString5 = typeof { x: "", y: (s: string) => { return s; } }; // string type expressions var ResultIsString6 = typeof objA.a; ->ResultIsString6 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString6 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : string >objA : A >a : string var ResultIsString7 = typeof M.n; ->ResultIsString7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : string >M : typeof M >n : string var ResultIsString8 = typeof STRING1[0]; ->ResultIsString8 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof STRING1[0] : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString8 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING1[0] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING1[0] : string >STRING1 : string[] >0 : 0 var ResultIsString9 = typeof foo(); ->ResultIsString9 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString9 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : string >foo : () => string var ResultIsString10 = typeof A.foo(); ->ResultIsString10 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof A.foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString10 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo() : string >A.foo : () => string >A : typeof A >foo : () => string var ResultIsString11 = typeof (STRING + STRING); ->ResultIsString11 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (STRING + STRING) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString11 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (STRING + STRING) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(STRING + STRING) : string >STRING + STRING : string >STRING : string >STRING : string var ResultIsString12 = typeof STRING.charAt(0); ->ResultIsString12 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof STRING.charAt(0) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString12 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING.charAt(0) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING.charAt(0) : string >STRING.charAt : (pos: number) => string >STRING : string @@ -127,16 +127,16 @@ var ResultIsString12 = typeof STRING.charAt(0); // multiple typeof operators var ResultIsString13 = typeof typeof STRING; ->ResultIsString13 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof STRING : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof STRING : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString13 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof STRING : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING : string var ResultIsString14 = typeof typeof typeof (STRING + STRING); ->ResultIsString14 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof typeof (STRING + STRING) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof typeof (STRING + STRING) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof (STRING + STRING) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>ResultIsString14 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof typeof (STRING + STRING) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof typeof (STRING + STRING) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof (STRING + STRING) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >(STRING + STRING) : string >STRING + STRING : string >STRING : string @@ -144,25 +144,25 @@ var ResultIsString14 = typeof typeof typeof (STRING + STRING); // miss assignment operators typeof ""; ->typeof "" : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof "" : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >"" : "" typeof STRING; ->typeof STRING : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING : string typeof STRING1; ->typeof STRING1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING1 : string[] typeof foo(); ->typeof foo() : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo() : string >foo : () => string typeof objA.a, M.n; >typeof objA.a, M.n : string ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : string >objA : A >a : string @@ -182,17 +182,17 @@ var r: () => string; z: typeof STRING; >z : any ->typeof STRING : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING : string x: typeof STRING1; >x : any ->typeof STRING1 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof STRING1 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >STRING1 : string[] r: typeof foo; >r : any ->typeof foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >foo : () => string var y = { a: "", b: "" }; @@ -205,28 +205,28 @@ var y = { a: "", b: "" }; z: typeof y.a; >z : any ->typeof y.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof y.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >y.a : string >y : { a: string; b: string; } >a : string z: typeof objA.a; >z : any ->typeof objA.a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof objA.a : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >objA.a : string >objA : A >a : string z: typeof A.foo; >z : any ->typeof A.foo : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A.foo : () => string >A : typeof A >foo : () => string z: typeof M.n; >z : any ->typeof M.n : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof M.n : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >M.n : string >M : typeof M >n : string diff --git a/tests/baselines/reference/typeofUnknownSymbol.types b/tests/baselines/reference/typeofUnknownSymbol.types index 7e9d5bdc174..62ee810d6df 100644 --- a/tests/baselines/reference/typeofUnknownSymbol.types +++ b/tests/baselines/reference/typeofUnknownSymbol.types @@ -1,7 +1,7 @@ === tests/cases/compiler/typeofUnknownSymbol.ts === // previously gave no error here var x = typeof whatsthis ->x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->typeof whatsthis : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof whatsthis : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >whatsthis : any diff --git a/tests/baselines/reference/unionTypeInference.types b/tests/baselines/reference/unionTypeInference.types index 50bbdbc3170..e712916c2ff 100644 --- a/tests/baselines/reference/unionTypeInference.types +++ b/tests/baselines/reference/unionTypeInference.types @@ -82,11 +82,11 @@ function h(x: string|boolean|T): T { >typeof x === "string" || typeof x === "boolean" ? undefined : x : T >typeof x === "string" || typeof x === "boolean" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | boolean | T >"string" : "string" >typeof x === "boolean" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : boolean | T >"boolean" : "boolean" >undefined : undefined diff --git a/tests/baselines/reference/unknownType1.types b/tests/baselines/reference/unknownType1.types index 1da9979912b..aaaf73bb709 100644 --- a/tests/baselines/reference/unknownType1.types +++ b/tests/baselines/reference/unknownType1.types @@ -199,11 +199,11 @@ function f20(x: unknown) { if (typeof x === "string" || typeof x === "number") { >typeof x === "string" || typeof x === "number" : boolean >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown >"string" : "string" >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : unknown >"number" : "number" From 188c07865a966939f66a4c452674c1ee10a2fece Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 14:26:56 -0700 Subject: [PATCH 213/262] Scan bigint literals --- src/compiler/binder.ts | 8 +- src/compiler/parser.ts | 5 +- src/compiler/scanner.ts | 122 +++-- src/compiler/types.ts | 1 + .../reference/api/tsserverlibrary.d.ts | 443 +++++++++--------- tests/baselines/reference/api/typescript.d.ts | 443 +++++++++--------- 6 files changed, 532 insertions(+), 490 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 6881dc60e98..0d6a91def8c 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -3697,9 +3697,13 @@ namespace ts { break; case SyntaxKind.NumericLiteral: - if ((node).numericLiteralFlags & TokenFlags.BinaryOrOctalSpecifier) { + const flags = (node).numericLiteralFlags; + if (flags & TokenFlags.BinaryOrOctalSpecifier) { transformFlags |= TransformFlags.AssertES2015; } + if (flags & TokenFlags.BigInt) { + transformFlags |= TransformFlags.AssertESNext; + } break; case SyntaxKind.ForOfStatement: @@ -3718,6 +3722,7 @@ namespace ts { case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.ObjectKeyword: case SyntaxKind.StringKeyword: @@ -3926,6 +3931,7 @@ namespace ts { return TransformFlags.MethodOrAccessorExcludes; case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.ObjectKeyword: diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 77bf0351242..376afe43d2c 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2247,8 +2247,7 @@ namespace ts { function parseLiteralLikeNode(kind: SyntaxKind): LiteralExpression | LiteralLikeNode { const node = createNode(kind); - const text = scanner.getTokenValue(); - node.text = text; + node.text = scanner.getTokenValue(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; @@ -2902,6 +2901,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.UndefinedKeyword: @@ -2960,6 +2960,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.UniqueKeyword: diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 1a5c4336b63..22b90df6799 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -64,6 +64,7 @@ namespace ts { abstract: SyntaxKind.AbstractKeyword, any: SyntaxKind.AnyKeyword, as: SyntaxKind.AsKeyword, + bigint: SyntaxKind.BigIntKeyword, boolean: SyntaxKind.BooleanKeyword, break: SyntaxKind.BreakKeyword, case: SyntaxKind.CaseKeyword, @@ -943,18 +944,26 @@ namespace ts { end = pos; } } + let result: string; if (tokenFlags & TokenFlags.ContainsSeparator) { - let result = mainFragment; + result = mainFragment; if (decimalFragment) { result += "." + decimalFragment; } if (scientificFragment) { result += scientificFragment; } - return "" + +result; } else { - return "" + +(text.substring(start, end)); // No need to use all the fragments; no _ removal needed + result = text.substring(start, end); // No need to use all the fragments; no _ removal needed + } + if (decimalFragment === undefined && !(tokenFlags & TokenFlags.Scientific)) { + tokenValue = result; + checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return tokenValue; + } + else { + return "" + +result; // if value is not an integer, it can be safely coerced to a number } } @@ -971,24 +980,24 @@ namespace ts { * returning -1 if the given number is unavailable. */ function scanExactNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { - return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + const valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators); + return valueString ? parseInt(valueString, 16) : -1; } /** * Scans as many hexadecimal digits as are available in the text, - * returning -1 if the given number of digits was unavailable. + * returning "" if the given number of digits was unavailable. */ - function scanMinimumNumberOfHexDigits(count: number, canHaveSeparators: boolean): number { + function scanMinimumNumberOfHexDigits(count: number, canHaveSeparators: boolean): string { return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators); } - function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean, canHaveSeparators: boolean): number { - let digits = 0; - let value = 0; + function scanHexDigits(minCount: number, scanAsManyAsPossible: boolean, canHaveSeparators: boolean): string { + let valueChars: number[] = []; let allowSeparator = false; let isPreviousTokenSeparator = false; - while (digits < minCount || scanAsManyAsPossible) { - const ch = text.charCodeAt(pos); + while (valueChars.length < minCount || scanAsManyAsPossible) { + let ch = text.charCodeAt(pos); if (canHaveSeparators && ch === CharacterCodes._) { tokenFlags |= TokenFlags.ContainsSeparator; if (allowSeparator) { @@ -1005,29 +1014,25 @@ namespace ts { continue; } allowSeparator = canHaveSeparators; - if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { - value = value * 16 + ch - CharacterCodes._0; + if (ch >= CharacterCodes.A && ch <= CharacterCodes.F) { + ch += CharacterCodes.a - CharacterCodes.A; // standardize hex literals to lowercase } - else if (ch >= CharacterCodes.A && ch <= CharacterCodes.F) { - value = value * 16 + ch - CharacterCodes.A + 10; - } - else if (ch >= CharacterCodes.a && ch <= CharacterCodes.f) { - value = value * 16 + ch - CharacterCodes.a + 10; - } - else { + else if (!((ch >= CharacterCodes._0 && ch <= CharacterCodes._9) || + (ch >= CharacterCodes.a && ch <= CharacterCodes.f) + )) { break; } + valueChars.push(ch); pos++; - digits++; isPreviousTokenSeparator = false; } - if (digits < minCount) { - value = -1; + if (valueChars.length < minCount) { + valueChars = []; } if (text.charCodeAt(pos - 1) === CharacterCodes._) { error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } - return value; + return String.fromCharCode(...valueChars); } function scanString(jsxAttributeString = false): string { @@ -1207,7 +1212,8 @@ namespace ts { } function scanExtendedUnicodeEscape(): string { - const escapedValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; let isInvalidExtendedEscape = false; // Validate the value of the digit @@ -1309,13 +1315,10 @@ namespace ts { return token = SyntaxKind.Identifier; } - function scanBinaryOrOctalDigits(base: number): number { - Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); - - let value = 0; + function scanBinaryOrOctalDigits(base: 2 | 8): string { + let value = ""; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. - let numberOfDigits = 0; let separatorAllowed = false; let isPreviousTokenSeparator = false; while (true) { @@ -1337,27 +1340,41 @@ namespace ts { continue; } separatorAllowed = true; - const valueOfCh = ch - CharacterCodes._0; - if (!isDigit(ch) || valueOfCh >= base) { + if (!isDigit(ch) || ch - CharacterCodes._0 >= base) { break; } - value = value * base + valueOfCh; + value += text[pos]; pos++; - numberOfDigits++; isPreviousTokenSeparator = false; } - // Invalid binaryIntegerLiteral or octalIntegerLiteral - if (numberOfDigits === 0) { - return -1; - } if (text.charCodeAt(pos - 1) === CharacterCodes._) { // Literal ends with underscore - not allowed error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); - return value; } return value; } + function checkBigIntSuffix(): void { + if (text.charCodeAt(pos) === CharacterCodes.n) { + tokenFlags |= TokenFlags.BigInt; + tokenValue += "n"; + // Use base 10 instead of base 2 or base 8 for shorter literals + if (tokenFlags & TokenFlags.BinaryOrOctalSpecifier) { + tokenValue = parsePseudoBigInt(tokenValue) + "n"; + } + pos++; + } + else { // not a bigint, so can convert to number in simplified form + // Number() may not support 0b or 0o, so use parseInt() instead + const numericValue = tokenFlags & TokenFlags.BinarySpecifier + ? parseInt(tokenValue.slice(2), 2) // skip "0b" + : tokenFlags & TokenFlags.OctalSpecifier + ? parseInt(tokenValue.slice(2), 8) // skip "0o" + : +tokenValue; + tokenValue = "" + numericValue; + } + } + function scan(): SyntaxKind { startPos = pos; tokenFlags = 0; @@ -1582,35 +1599,38 @@ namespace ts { case CharacterCodes._0: if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.X || text.charCodeAt(pos + 1) === CharacterCodes.x)) { pos += 2; - let value = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); - if (value < 0) { + tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true); + if (!tokenValue) { error(Diagnostics.Hexadecimal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0x" + tokenValue; tokenFlags |= TokenFlags.HexSpecifier; + checkBigIntSuffix(); return token = SyntaxKind.NumericLiteral; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.B || text.charCodeAt(pos + 1) === CharacterCodes.b)) { pos += 2; - let value = scanBinaryOrOctalDigits(/* base */ 2); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 2); + if (!tokenValue) { error(Diagnostics.Binary_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0b" + tokenValue; tokenFlags |= TokenFlags.BinarySpecifier; + checkBigIntSuffix(); return token = SyntaxKind.NumericLiteral; } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.O || text.charCodeAt(pos + 1) === CharacterCodes.o)) { pos += 2; - let value = scanBinaryOrOctalDigits(/* base */ 8); - if (value < 0) { + tokenValue = scanBinaryOrOctalDigits(/* base */ 8); + if (!tokenValue) { error(Diagnostics.Octal_digit_expected); - value = 0; + tokenValue = "0"; } - tokenValue = "" + value; + tokenValue = "0o" + tokenValue; tokenFlags |= TokenFlags.OctalSpecifier; + checkBigIntSuffix(); return token = SyntaxKind.NumericLiteral; } // Try to parse as an octal diff --git a/src/compiler/types.ts b/src/compiler/types.ts index d926c56dc1d..9d696e3a8d0 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -31,6 +31,7 @@ namespace ts { | SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword + | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9f447a12c35..62577f6c747 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -73,7 +73,7 @@ declare namespace ts { end: number; } type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; - type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -221,172 +221,173 @@ declare namespace ts { UnknownKeyword = 142, FromKeyword = 143, GlobalKeyword = 144, - OfKeyword = 145, - QualifiedName = 146, - ComputedPropertyName = 147, - TypeParameter = 148, - Parameter = 149, - Decorator = 150, - PropertySignature = 151, - PropertyDeclaration = 152, - MethodSignature = 153, - MethodDeclaration = 154, - Constructor = 155, - GetAccessor = 156, - SetAccessor = 157, - CallSignature = 158, - ConstructSignature = 159, - IndexSignature = 160, - TypePredicate = 161, - TypeReference = 162, - FunctionType = 163, - ConstructorType = 164, - TypeQuery = 165, - TypeLiteral = 166, - ArrayType = 167, - TupleType = 168, - OptionalType = 169, - RestType = 170, - UnionType = 171, - IntersectionType = 172, - ConditionalType = 173, - InferType = 174, - ParenthesizedType = 175, - ThisType = 176, - TypeOperator = 177, - IndexedAccessType = 178, - MappedType = 179, - LiteralType = 180, - ImportType = 181, - ObjectBindingPattern = 182, - ArrayBindingPattern = 183, - BindingElement = 184, - ArrayLiteralExpression = 185, - ObjectLiteralExpression = 186, - PropertyAccessExpression = 187, - ElementAccessExpression = 188, - CallExpression = 189, - NewExpression = 190, - TaggedTemplateExpression = 191, - TypeAssertionExpression = 192, - ParenthesizedExpression = 193, - FunctionExpression = 194, - ArrowFunction = 195, - DeleteExpression = 196, - TypeOfExpression = 197, - VoidExpression = 198, - AwaitExpression = 199, - PrefixUnaryExpression = 200, - PostfixUnaryExpression = 201, - BinaryExpression = 202, - ConditionalExpression = 203, - TemplateExpression = 204, - YieldExpression = 205, - SpreadElement = 206, - ClassExpression = 207, - OmittedExpression = 208, - ExpressionWithTypeArguments = 209, - AsExpression = 210, - NonNullExpression = 211, - MetaProperty = 212, - SyntheticExpression = 213, - TemplateSpan = 214, - SemicolonClassElement = 215, - Block = 216, - VariableStatement = 217, - EmptyStatement = 218, - ExpressionStatement = 219, - IfStatement = 220, - DoStatement = 221, - WhileStatement = 222, - ForStatement = 223, - ForInStatement = 224, - ForOfStatement = 225, - ContinueStatement = 226, - BreakStatement = 227, - ReturnStatement = 228, - WithStatement = 229, - SwitchStatement = 230, - LabeledStatement = 231, - ThrowStatement = 232, - TryStatement = 233, - DebuggerStatement = 234, - VariableDeclaration = 235, - VariableDeclarationList = 236, - FunctionDeclaration = 237, - ClassDeclaration = 238, - InterfaceDeclaration = 239, - TypeAliasDeclaration = 240, - EnumDeclaration = 241, - ModuleDeclaration = 242, - ModuleBlock = 243, - CaseBlock = 244, - NamespaceExportDeclaration = 245, - ImportEqualsDeclaration = 246, - ImportDeclaration = 247, - ImportClause = 248, - NamespaceImport = 249, - NamedImports = 250, - ImportSpecifier = 251, - ExportAssignment = 252, - ExportDeclaration = 253, - NamedExports = 254, - ExportSpecifier = 255, - MissingDeclaration = 256, - ExternalModuleReference = 257, - JsxElement = 258, - JsxSelfClosingElement = 259, - JsxOpeningElement = 260, - JsxClosingElement = 261, - JsxFragment = 262, - JsxOpeningFragment = 263, - JsxClosingFragment = 264, - JsxAttribute = 265, - JsxAttributes = 266, - JsxSpreadAttribute = 267, - JsxExpression = 268, - CaseClause = 269, - DefaultClause = 270, - HeritageClause = 271, - CatchClause = 272, - PropertyAssignment = 273, - ShorthandPropertyAssignment = 274, - SpreadAssignment = 275, - EnumMember = 276, - SourceFile = 277, - Bundle = 278, - UnparsedSource = 279, - InputFiles = 280, - JSDocTypeExpression = 281, - JSDocAllType = 282, - JSDocUnknownType = 283, - JSDocNullableType = 284, - JSDocNonNullableType = 285, - JSDocOptionalType = 286, - JSDocFunctionType = 287, - JSDocVariadicType = 288, - JSDocComment = 289, - JSDocTypeLiteral = 290, - JSDocSignature = 291, - JSDocTag = 292, - JSDocAugmentsTag = 293, - JSDocClassTag = 294, - JSDocCallbackTag = 295, - JSDocEnumTag = 296, - JSDocParameterTag = 297, - JSDocReturnTag = 298, - JSDocThisTag = 299, - JSDocTypeTag = 300, - JSDocTemplateTag = 301, - JSDocTypedefTag = 302, - JSDocPropertyTag = 303, - SyntaxList = 304, - NotEmittedStatement = 305, - PartiallyEmittedExpression = 306, - CommaListExpression = 307, - MergeDeclarationMarker = 308, - EndOfDeclarationMarker = 309, - Count = 310, + BigIntKeyword = 145, + OfKeyword = 146, + QualifiedName = 147, + ComputedPropertyName = 148, + TypeParameter = 149, + Parameter = 150, + Decorator = 151, + PropertySignature = 152, + PropertyDeclaration = 153, + MethodSignature = 154, + MethodDeclaration = 155, + Constructor = 156, + GetAccessor = 157, + SetAccessor = 158, + CallSignature = 159, + ConstructSignature = 160, + IndexSignature = 161, + TypePredicate = 162, + TypeReference = 163, + FunctionType = 164, + ConstructorType = 165, + TypeQuery = 166, + TypeLiteral = 167, + ArrayType = 168, + TupleType = 169, + OptionalType = 170, + RestType = 171, + UnionType = 172, + IntersectionType = 173, + ConditionalType = 174, + InferType = 175, + ParenthesizedType = 176, + ThisType = 177, + TypeOperator = 178, + IndexedAccessType = 179, + MappedType = 180, + LiteralType = 181, + ImportType = 182, + ObjectBindingPattern = 183, + ArrayBindingPattern = 184, + BindingElement = 185, + ArrayLiteralExpression = 186, + ObjectLiteralExpression = 187, + PropertyAccessExpression = 188, + ElementAccessExpression = 189, + CallExpression = 190, + NewExpression = 191, + TaggedTemplateExpression = 192, + TypeAssertionExpression = 193, + ParenthesizedExpression = 194, + FunctionExpression = 195, + ArrowFunction = 196, + DeleteExpression = 197, + TypeOfExpression = 198, + VoidExpression = 199, + AwaitExpression = 200, + PrefixUnaryExpression = 201, + PostfixUnaryExpression = 202, + BinaryExpression = 203, + ConditionalExpression = 204, + TemplateExpression = 205, + YieldExpression = 206, + SpreadElement = 207, + ClassExpression = 208, + OmittedExpression = 209, + ExpressionWithTypeArguments = 210, + AsExpression = 211, + NonNullExpression = 212, + MetaProperty = 213, + SyntheticExpression = 214, + TemplateSpan = 215, + SemicolonClassElement = 216, + Block = 217, + VariableStatement = 218, + EmptyStatement = 219, + ExpressionStatement = 220, + IfStatement = 221, + DoStatement = 222, + WhileStatement = 223, + ForStatement = 224, + ForInStatement = 225, + ForOfStatement = 226, + ContinueStatement = 227, + BreakStatement = 228, + ReturnStatement = 229, + WithStatement = 230, + SwitchStatement = 231, + LabeledStatement = 232, + ThrowStatement = 233, + TryStatement = 234, + DebuggerStatement = 235, + VariableDeclaration = 236, + VariableDeclarationList = 237, + FunctionDeclaration = 238, + ClassDeclaration = 239, + InterfaceDeclaration = 240, + TypeAliasDeclaration = 241, + EnumDeclaration = 242, + ModuleDeclaration = 243, + ModuleBlock = 244, + CaseBlock = 245, + NamespaceExportDeclaration = 246, + ImportEqualsDeclaration = 247, + ImportDeclaration = 248, + ImportClause = 249, + NamespaceImport = 250, + NamedImports = 251, + ImportSpecifier = 252, + ExportAssignment = 253, + ExportDeclaration = 254, + NamedExports = 255, + ExportSpecifier = 256, + MissingDeclaration = 257, + ExternalModuleReference = 258, + JsxElement = 259, + JsxSelfClosingElement = 260, + JsxOpeningElement = 261, + JsxClosingElement = 262, + JsxFragment = 263, + JsxOpeningFragment = 264, + JsxClosingFragment = 265, + JsxAttribute = 266, + JsxAttributes = 267, + JsxSpreadAttribute = 268, + JsxExpression = 269, + CaseClause = 270, + DefaultClause = 271, + HeritageClause = 272, + CatchClause = 273, + PropertyAssignment = 274, + ShorthandPropertyAssignment = 275, + SpreadAssignment = 276, + EnumMember = 277, + SourceFile = 278, + Bundle = 279, + UnparsedSource = 280, + InputFiles = 281, + JSDocTypeExpression = 282, + JSDocAllType = 283, + JSDocUnknownType = 284, + JSDocNullableType = 285, + JSDocNonNullableType = 286, + JSDocOptionalType = 287, + JSDocFunctionType = 288, + JSDocVariadicType = 289, + JSDocComment = 290, + JSDocTypeLiteral = 291, + JSDocSignature = 292, + JSDocTag = 293, + JSDocAugmentsTag = 294, + JSDocClassTag = 295, + JSDocCallbackTag = 296, + JSDocEnumTag = 297, + JSDocParameterTag = 298, + JSDocReturnTag = 299, + JSDocThisTag = 300, + JSDocTypeTag = 301, + JSDocTemplateTag = 302, + JSDocTypedefTag = 303, + JSDocPropertyTag = 304, + SyntaxList = 305, + NotEmittedStatement = 306, + PartiallyEmittedExpression = 307, + CommaListExpression = 308, + MergeDeclarationMarker = 309, + EndOfDeclarationMarker = 310, + Count = 311, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -394,15 +395,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 145, + LastKeyword = 146, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 161, - LastTypeNode = 181, + FirstTypeNode = 162, + LastTypeNode = 182, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 145, + LastToken = 146, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -411,11 +412,11 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 146, - FirstJSDocNode = 281, - LastJSDocNode = 303, - FirstJSDocTagNode = 292, - LastJSDocTagNode = 303 + FirstNode = 147, + FirstJSDocNode = 282, + LastJSDocNode = 304, + FirstJSDocTagNode = 293, + LastJSDocTagNode = 304 } enum NodeFlags { None = 0, @@ -727,7 +728,7 @@ declare namespace ts { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; } interface ImportTypeNode extends NodeWithTypeArguments { kind: SyntaxKind.ImportType; @@ -2164,44 +2165,47 @@ declare namespace ts { Number = 8, Boolean = 16, Enum = 32, - StringLiteral = 64, - NumberLiteral = 128, - BooleanLiteral = 256, - EnumLiteral = 512, - ESSymbol = 1024, - UniqueESSymbol = 2048, - Void = 4096, - Undefined = 8192, - Null = 16384, - Never = 32768, - TypeParameter = 65536, - Object = 131072, - Union = 262144, - Intersection = 524288, - Index = 1048576, - IndexedAccess = 2097152, - Conditional = 4194304, - Substitution = 8388608, - NonPrimitive = 16777216, - Literal = 448, - Unit = 27072, - StringOrNumberLiteral = 192, - PossiblyFalsy = 29148, - StringLike = 68, - NumberLike = 168, - BooleanLike = 272, - EnumLike = 544, - ESSymbolLike = 3072, - VoidLike = 12288, - UnionOrIntersection = 786432, - StructuredType = 917504, - TypeVariable = 2162688, - InstantiableNonPrimitive = 14745600, - InstantiablePrimitive = 1048576, - Instantiable = 15794176, - StructuredOrInstantiable = 16711680, - Narrowable = 33492479, - NotUnionOrUnit = 16909315 + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2212,7 +2216,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2225,6 +2229,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -3657,9 +3664,9 @@ declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - function createLiteral(value: number): NumericLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(value: string | number | boolean): PrimaryExpression; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index d2ec3ab1d12..875a293fee2 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -73,7 +73,7 @@ declare namespace ts { end: number; } type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown | KeywordSyntaxKind; - type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; + type KeywordSyntaxKind = SyntaxKind.AbstractKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FromKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.GetKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InferKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.IsKeyword | SyntaxKind.KeyOfKeyword | SyntaxKind.LetKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SetKeyword | SyntaxKind.StaticKeyword | SyntaxKind.StringKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.OfKeyword; type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, @@ -221,172 +221,173 @@ declare namespace ts { UnknownKeyword = 142, FromKeyword = 143, GlobalKeyword = 144, - OfKeyword = 145, - QualifiedName = 146, - ComputedPropertyName = 147, - TypeParameter = 148, - Parameter = 149, - Decorator = 150, - PropertySignature = 151, - PropertyDeclaration = 152, - MethodSignature = 153, - MethodDeclaration = 154, - Constructor = 155, - GetAccessor = 156, - SetAccessor = 157, - CallSignature = 158, - ConstructSignature = 159, - IndexSignature = 160, - TypePredicate = 161, - TypeReference = 162, - FunctionType = 163, - ConstructorType = 164, - TypeQuery = 165, - TypeLiteral = 166, - ArrayType = 167, - TupleType = 168, - OptionalType = 169, - RestType = 170, - UnionType = 171, - IntersectionType = 172, - ConditionalType = 173, - InferType = 174, - ParenthesizedType = 175, - ThisType = 176, - TypeOperator = 177, - IndexedAccessType = 178, - MappedType = 179, - LiteralType = 180, - ImportType = 181, - ObjectBindingPattern = 182, - ArrayBindingPattern = 183, - BindingElement = 184, - ArrayLiteralExpression = 185, - ObjectLiteralExpression = 186, - PropertyAccessExpression = 187, - ElementAccessExpression = 188, - CallExpression = 189, - NewExpression = 190, - TaggedTemplateExpression = 191, - TypeAssertionExpression = 192, - ParenthesizedExpression = 193, - FunctionExpression = 194, - ArrowFunction = 195, - DeleteExpression = 196, - TypeOfExpression = 197, - VoidExpression = 198, - AwaitExpression = 199, - PrefixUnaryExpression = 200, - PostfixUnaryExpression = 201, - BinaryExpression = 202, - ConditionalExpression = 203, - TemplateExpression = 204, - YieldExpression = 205, - SpreadElement = 206, - ClassExpression = 207, - OmittedExpression = 208, - ExpressionWithTypeArguments = 209, - AsExpression = 210, - NonNullExpression = 211, - MetaProperty = 212, - SyntheticExpression = 213, - TemplateSpan = 214, - SemicolonClassElement = 215, - Block = 216, - VariableStatement = 217, - EmptyStatement = 218, - ExpressionStatement = 219, - IfStatement = 220, - DoStatement = 221, - WhileStatement = 222, - ForStatement = 223, - ForInStatement = 224, - ForOfStatement = 225, - ContinueStatement = 226, - BreakStatement = 227, - ReturnStatement = 228, - WithStatement = 229, - SwitchStatement = 230, - LabeledStatement = 231, - ThrowStatement = 232, - TryStatement = 233, - DebuggerStatement = 234, - VariableDeclaration = 235, - VariableDeclarationList = 236, - FunctionDeclaration = 237, - ClassDeclaration = 238, - InterfaceDeclaration = 239, - TypeAliasDeclaration = 240, - EnumDeclaration = 241, - ModuleDeclaration = 242, - ModuleBlock = 243, - CaseBlock = 244, - NamespaceExportDeclaration = 245, - ImportEqualsDeclaration = 246, - ImportDeclaration = 247, - ImportClause = 248, - NamespaceImport = 249, - NamedImports = 250, - ImportSpecifier = 251, - ExportAssignment = 252, - ExportDeclaration = 253, - NamedExports = 254, - ExportSpecifier = 255, - MissingDeclaration = 256, - ExternalModuleReference = 257, - JsxElement = 258, - JsxSelfClosingElement = 259, - JsxOpeningElement = 260, - JsxClosingElement = 261, - JsxFragment = 262, - JsxOpeningFragment = 263, - JsxClosingFragment = 264, - JsxAttribute = 265, - JsxAttributes = 266, - JsxSpreadAttribute = 267, - JsxExpression = 268, - CaseClause = 269, - DefaultClause = 270, - HeritageClause = 271, - CatchClause = 272, - PropertyAssignment = 273, - ShorthandPropertyAssignment = 274, - SpreadAssignment = 275, - EnumMember = 276, - SourceFile = 277, - Bundle = 278, - UnparsedSource = 279, - InputFiles = 280, - JSDocTypeExpression = 281, - JSDocAllType = 282, - JSDocUnknownType = 283, - JSDocNullableType = 284, - JSDocNonNullableType = 285, - JSDocOptionalType = 286, - JSDocFunctionType = 287, - JSDocVariadicType = 288, - JSDocComment = 289, - JSDocTypeLiteral = 290, - JSDocSignature = 291, - JSDocTag = 292, - JSDocAugmentsTag = 293, - JSDocClassTag = 294, - JSDocCallbackTag = 295, - JSDocEnumTag = 296, - JSDocParameterTag = 297, - JSDocReturnTag = 298, - JSDocThisTag = 299, - JSDocTypeTag = 300, - JSDocTemplateTag = 301, - JSDocTypedefTag = 302, - JSDocPropertyTag = 303, - SyntaxList = 304, - NotEmittedStatement = 305, - PartiallyEmittedExpression = 306, - CommaListExpression = 307, - MergeDeclarationMarker = 308, - EndOfDeclarationMarker = 309, - Count = 310, + BigIntKeyword = 145, + OfKeyword = 146, + QualifiedName = 147, + ComputedPropertyName = 148, + TypeParameter = 149, + Parameter = 150, + Decorator = 151, + PropertySignature = 152, + PropertyDeclaration = 153, + MethodSignature = 154, + MethodDeclaration = 155, + Constructor = 156, + GetAccessor = 157, + SetAccessor = 158, + CallSignature = 159, + ConstructSignature = 160, + IndexSignature = 161, + TypePredicate = 162, + TypeReference = 163, + FunctionType = 164, + ConstructorType = 165, + TypeQuery = 166, + TypeLiteral = 167, + ArrayType = 168, + TupleType = 169, + OptionalType = 170, + RestType = 171, + UnionType = 172, + IntersectionType = 173, + ConditionalType = 174, + InferType = 175, + ParenthesizedType = 176, + ThisType = 177, + TypeOperator = 178, + IndexedAccessType = 179, + MappedType = 180, + LiteralType = 181, + ImportType = 182, + ObjectBindingPattern = 183, + ArrayBindingPattern = 184, + BindingElement = 185, + ArrayLiteralExpression = 186, + ObjectLiteralExpression = 187, + PropertyAccessExpression = 188, + ElementAccessExpression = 189, + CallExpression = 190, + NewExpression = 191, + TaggedTemplateExpression = 192, + TypeAssertionExpression = 193, + ParenthesizedExpression = 194, + FunctionExpression = 195, + ArrowFunction = 196, + DeleteExpression = 197, + TypeOfExpression = 198, + VoidExpression = 199, + AwaitExpression = 200, + PrefixUnaryExpression = 201, + PostfixUnaryExpression = 202, + BinaryExpression = 203, + ConditionalExpression = 204, + TemplateExpression = 205, + YieldExpression = 206, + SpreadElement = 207, + ClassExpression = 208, + OmittedExpression = 209, + ExpressionWithTypeArguments = 210, + AsExpression = 211, + NonNullExpression = 212, + MetaProperty = 213, + SyntheticExpression = 214, + TemplateSpan = 215, + SemicolonClassElement = 216, + Block = 217, + VariableStatement = 218, + EmptyStatement = 219, + ExpressionStatement = 220, + IfStatement = 221, + DoStatement = 222, + WhileStatement = 223, + ForStatement = 224, + ForInStatement = 225, + ForOfStatement = 226, + ContinueStatement = 227, + BreakStatement = 228, + ReturnStatement = 229, + WithStatement = 230, + SwitchStatement = 231, + LabeledStatement = 232, + ThrowStatement = 233, + TryStatement = 234, + DebuggerStatement = 235, + VariableDeclaration = 236, + VariableDeclarationList = 237, + FunctionDeclaration = 238, + ClassDeclaration = 239, + InterfaceDeclaration = 240, + TypeAliasDeclaration = 241, + EnumDeclaration = 242, + ModuleDeclaration = 243, + ModuleBlock = 244, + CaseBlock = 245, + NamespaceExportDeclaration = 246, + ImportEqualsDeclaration = 247, + ImportDeclaration = 248, + ImportClause = 249, + NamespaceImport = 250, + NamedImports = 251, + ImportSpecifier = 252, + ExportAssignment = 253, + ExportDeclaration = 254, + NamedExports = 255, + ExportSpecifier = 256, + MissingDeclaration = 257, + ExternalModuleReference = 258, + JsxElement = 259, + JsxSelfClosingElement = 260, + JsxOpeningElement = 261, + JsxClosingElement = 262, + JsxFragment = 263, + JsxOpeningFragment = 264, + JsxClosingFragment = 265, + JsxAttribute = 266, + JsxAttributes = 267, + JsxSpreadAttribute = 268, + JsxExpression = 269, + CaseClause = 270, + DefaultClause = 271, + HeritageClause = 272, + CatchClause = 273, + PropertyAssignment = 274, + ShorthandPropertyAssignment = 275, + SpreadAssignment = 276, + EnumMember = 277, + SourceFile = 278, + Bundle = 279, + UnparsedSource = 280, + InputFiles = 281, + JSDocTypeExpression = 282, + JSDocAllType = 283, + JSDocUnknownType = 284, + JSDocNullableType = 285, + JSDocNonNullableType = 286, + JSDocOptionalType = 287, + JSDocFunctionType = 288, + JSDocVariadicType = 289, + JSDocComment = 290, + JSDocTypeLiteral = 291, + JSDocSignature = 292, + JSDocTag = 293, + JSDocAugmentsTag = 294, + JSDocClassTag = 295, + JSDocCallbackTag = 296, + JSDocEnumTag = 297, + JSDocParameterTag = 298, + JSDocReturnTag = 299, + JSDocThisTag = 300, + JSDocTypeTag = 301, + JSDocTemplateTag = 302, + JSDocTypedefTag = 303, + JSDocPropertyTag = 304, + SyntaxList = 305, + NotEmittedStatement = 306, + PartiallyEmittedExpression = 307, + CommaListExpression = 308, + MergeDeclarationMarker = 309, + EndOfDeclarationMarker = 310, + Count = 311, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -394,15 +395,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 145, + LastKeyword = 146, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 161, - LastTypeNode = 181, + FirstTypeNode = 162, + LastTypeNode = 182, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 145, + LastToken = 146, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -411,11 +412,11 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 146, - FirstJSDocNode = 281, - LastJSDocNode = 303, - FirstJSDocTagNode = 292, - LastJSDocTagNode = 303 + FirstNode = 147, + FirstJSDocNode = 282, + LastJSDocNode = 304, + FirstJSDocTagNode = 293, + LastJSDocTagNode = 304 } enum NodeFlags { None = 0, @@ -727,7 +728,7 @@ declare namespace ts { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BigIntKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; } interface ImportTypeNode extends NodeWithTypeArguments { kind: SyntaxKind.ImportType; @@ -2164,44 +2165,47 @@ declare namespace ts { Number = 8, Boolean = 16, Enum = 32, - StringLiteral = 64, - NumberLiteral = 128, - BooleanLiteral = 256, - EnumLiteral = 512, - ESSymbol = 1024, - UniqueESSymbol = 2048, - Void = 4096, - Undefined = 8192, - Null = 16384, - Never = 32768, - TypeParameter = 65536, - Object = 131072, - Union = 262144, - Intersection = 524288, - Index = 1048576, - IndexedAccess = 2097152, - Conditional = 4194304, - Substitution = 8388608, - NonPrimitive = 16777216, - Literal = 448, - Unit = 27072, - StringOrNumberLiteral = 192, - PossiblyFalsy = 29148, - StringLike = 68, - NumberLike = 168, - BooleanLike = 272, - EnumLike = 544, - ESSymbolLike = 3072, - VoidLike = 12288, - UnionOrIntersection = 786432, - StructuredType = 917504, - TypeVariable = 2162688, - InstantiableNonPrimitive = 14745600, - InstantiablePrimitive = 1048576, - Instantiable = 15794176, - StructuredOrInstantiable = 16711680, - Narrowable = 33492479, - NotUnionOrUnit = 16909315 + BigInt = 64, + StringLiteral = 128, + NumberLiteral = 256, + BooleanLiteral = 512, + EnumLiteral = 1024, + BigIntLiteral = 2048, + ESSymbol = 4096, + UniqueESSymbol = 8192, + Void = 16384, + Undefined = 32768, + Null = 65536, + Never = 131072, + TypeParameter = 262144, + Object = 524288, + Union = 1048576, + Intersection = 2097152, + Index = 4194304, + IndexedAccess = 8388608, + Conditional = 16777216, + Substitution = 33554432, + NonPrimitive = 67108864, + Literal = 2944, + Unit = 109440, + StringOrNumberLiteral = 384, + PossiblyFalsy = 117724, + StringLike = 132, + NumberLike = 296, + BigIntLike = 2112, + BooleanLike = 528, + EnumLike = 1056, + ESSymbolLike = 12288, + VoidLike = 49152, + UnionOrIntersection = 3145728, + StructuredType = 3670016, + TypeVariable = 8650752, + InstantiableNonPrimitive = 58982400, + InstantiablePrimitive = 4194304, + Instantiable = 63176704, + StructuredOrInstantiable = 66846720, + Narrowable = 133970943, + NotUnionOrUnit = 67637251 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2212,7 +2216,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2225,6 +2229,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -3657,9 +3664,9 @@ declare namespace ts { function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; /** If a node is passed, creates a string literal whose source text is read from a source node during emit. */ function createLiteral(value: string | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | Identifier): StringLiteral; - function createLiteral(value: number): NumericLiteral; + function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; - function createLiteral(value: string | number | boolean): PrimaryExpression; + function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; From 95c24c6c6ab0898d906f2f798258aa332dd8b582 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 15:12:17 -0700 Subject: [PATCH 214/262] experimentalBigInt compiler flag --- src/compiler/checker.ts | 3 +++ src/compiler/commandLineParser.ts | 6 ++++++ src/compiler/types.ts | 1 + .../reference/api/tsserverlibrary.d.ts | 1 + tests/baselines/reference/api/typescript.d.ts | 1 + .../Default initialized TSConfig/tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../tsconfig.json | 1 + .../warnExperimentalBigIntLiteral.errors.txt | 17 +++++++++++++++++ .../reference/warnExperimentalBigIntLiteral.js | 7 +++++++ .../warnExperimentalBigIntLiteral.symbols | 7 +++++++ .../warnExperimentalBigIntLiteral.types | 15 +++++++++++++++ .../compiler/warnExperimentalBigIntLiteral.ts | 2 ++ 19 files changed, 69 insertions(+) create mode 100644 tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt create mode 100644 tests/baselines/reference/warnExperimentalBigIntLiteral.js create mode 100644 tests/baselines/reference/warnExperimentalBigIntLiteral.symbols create mode 100644 tests/baselines/reference/warnExperimentalBigIntLiteral.types create mode 100644 tests/cases/compiler/warnExperimentalBigIntLiteral.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5e03f1b3987..0353b21869d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9270,6 +9270,9 @@ namespace ts { function getNumericLiteralValue(node: NumericLiteral): number | PseudoBigInt { if (node.numericLiteralFlags & TokenFlags.BigInt) { + if (!compilerOptions.experimentalBigInt) { + error(node, Diagnostics.Experimental_support_for_BigInt_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalBigInt_option_to_remove_this_warning); + } return { negative: false, base10Value: parsePseudoBigInt(node.text) }; } return +node.text; diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index cbd6188ff66..9c333f2cadf 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -584,6 +584,12 @@ namespace ts { category: Diagnostics.Experimental_Options, description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, + { + name: "experimentalBigInt", + type: "boolean", + category: Diagnostics.Experimental_Options, + description: Diagnostics.Enables_experimental_support_for_ESNext_BigInt_expressions + }, // Advanced { diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 9d696e3a8d0..9607b95b8e3 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4499,6 +4499,7 @@ namespace ts { downlevelIteration?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; + experimentalBigInt?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; /*@internal*/help?: boolean; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 62577f6c747..68113b99ca1 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2458,6 +2458,7 @@ declare namespace ts { downlevelIteration?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; + experimentalBigInt?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; importHelpers?: boolean; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 875a293fee2..fee1057fd2d 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2458,6 +2458,7 @@ declare namespace ts { downlevelIteration?: boolean; emitBOM?: boolean; emitDecoratorMetadata?: boolean; + experimentalBigInt?: boolean; experimentalDecorators?: boolean; forceConsistentCasingInFileNames?: boolean; importHelpers?: boolean; diff --git a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json index e4e3d7b8ec4..778fb9572f4 100644 --- a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json index 1919671c489..16462f9d660 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json @@ -56,6 +56,7 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ /* Advanced Options */ "noErrorTruncation": true, /* Do not truncate error messages. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json index 3b49dee6e3d..fa8e2c70a66 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json index d91e167877d..2d2d84b100c 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json index e6107b29b4c..68329ceecb5 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json @@ -56,6 +56,7 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ }, "files": [ "file0.st", diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json index 7c18b695c7b..eb13052b37c 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json index e4e3d7b8ec4..778fb9572f4 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json index eedcc357043..c9afe008935 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json index 6fc7833730f..37444c9a5de 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json @@ -56,5 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt new file mode 100644 index 00000000000..8a1207f4510 --- /dev/null +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,22): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,29): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,39): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,48): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. + + +==== tests/cases/compiler/warnExperimentalBigIntLiteral.ts (4 errors) ==== + const normalNumber = 123; // should not error + const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error + ~~~~ +!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. + ~~~~~~~ +!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. + ~~~~~~ +!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. + ~~~~~ +!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. \ No newline at end of file diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.js b/tests/baselines/reference/warnExperimentalBigIntLiteral.js new file mode 100644 index 00000000000..3f856417130 --- /dev/null +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.js @@ -0,0 +1,7 @@ +//// [warnExperimentalBigIntLiteral.ts] +const normalNumber = 123; // should not error +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error + +//// [warnExperimentalBigIntLiteral.js] +var normalNumber = 123; // should not error +var bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols new file mode 100644 index 00000000000..a54991a7bd5 --- /dev/null +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/warnExperimentalBigIntLiteral.ts === +const normalNumber = 123; // should not error +>normalNumber : Symbol(normalNumber, Decl(warnExperimentalBigIntLiteral.ts, 0, 5)) + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : Symbol(bigintNumber, Decl(warnExperimentalBigIntLiteral.ts, 1, 5)) + diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.types b/tests/baselines/reference/warnExperimentalBigIntLiteral.types new file mode 100644 index 00000000000..1a15f5d5dae --- /dev/null +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.types @@ -0,0 +1,15 @@ +=== tests/cases/compiler/warnExperimentalBigIntLiteral.ts === +const normalNumber = 123; // should not error +>normalNumber : 123 +>123 : 123 + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : bigint +>123n * 0b1111n + 0o444n * 0x7fn : bigint +>123n * 0b1111n : bigint +>123n : 123n +>0b1111n : 15n +>0o444n * 0x7fn : bigint +>0o444n : 292n +>0x7fn : 127n + diff --git a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts new file mode 100644 index 00000000000..f837a17f7a1 --- /dev/null +++ b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts @@ -0,0 +1,2 @@ +const normalNumber = 123; // should not error +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error \ No newline at end of file From a93131319e2315d6565981de55644eba2c5fd06f Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Sat, 29 Sep 2018 15:19:52 -0700 Subject: [PATCH 215/262] Add bigint tests --- .../reference/bigintIndex.errors.txt | 37 + tests/baselines/reference/bigintIndex.js | 41 + tests/baselines/reference/bigintIndex.symbols | 64 ++ tests/baselines/reference/bigintIndex.types | 98 +++ .../reference/bigintWithLib.errors.txt | 77 ++ tests/baselines/reference/bigintWithLib.js | 94 +++ .../baselines/reference/bigintWithLib.symbols | 206 +++++ tests/baselines/reference/bigintWithLib.types | 334 ++++++++ .../reference/bigintWithoutLib.errors.txt | 155 ++++ tests/baselines/reference/bigintWithoutLib.js | 97 +++ .../reference/bigintWithoutLib.symbols | 154 ++++ .../reference/bigintWithoutLib.types | 336 ++++++++ .../numberVsBigIntOperations.errors.txt | 289 +++++++ .../reference/numberVsBigIntOperations.js | 274 +++++++ .../numberVsBigIntOperations.symbols | 350 +++++++++ .../reference/numberVsBigIntOperations.types | 729 ++++++++++++++++++ .../reference/parseBigInt.errors.txt | 124 +++ tests/baselines/reference/parseBigInt.js | 149 ++++ tests/baselines/reference/parseBigInt.symbols | 179 +++++ tests/baselines/reference/parseBigInt.types | 256 ++++++ .../warnExperimentalBigIntLiteral.errors.txt | 23 +- .../warnExperimentalBigIntLiteral.js | 4 + .../warnExperimentalBigIntLiteral.symbols | 10 +- .../warnExperimentalBigIntLiteral.types | 6 + tests/cases/compiler/bigintIndex.ts | 25 + tests/cases/compiler/bigintWithLib.ts | 50 ++ tests/cases/compiler/bigintWithoutLib.ts | 52 ++ .../compiler/numberVsBigIntOperations.ts | 96 +++ tests/cases/compiler/parseBigInt.ts | 72 ++ .../compiler/warnExperimentalBigIntLiteral.ts | 2 + 30 files changed, 4372 insertions(+), 11 deletions(-) create mode 100644 tests/baselines/reference/bigintIndex.errors.txt create mode 100644 tests/baselines/reference/bigintIndex.js create mode 100644 tests/baselines/reference/bigintIndex.symbols create mode 100644 tests/baselines/reference/bigintIndex.types create mode 100644 tests/baselines/reference/bigintWithLib.errors.txt create mode 100644 tests/baselines/reference/bigintWithLib.js create mode 100644 tests/baselines/reference/bigintWithLib.symbols create mode 100644 tests/baselines/reference/bigintWithLib.types create mode 100644 tests/baselines/reference/bigintWithoutLib.errors.txt create mode 100644 tests/baselines/reference/bigintWithoutLib.js create mode 100644 tests/baselines/reference/bigintWithoutLib.symbols create mode 100644 tests/baselines/reference/bigintWithoutLib.types create mode 100644 tests/baselines/reference/numberVsBigIntOperations.errors.txt create mode 100644 tests/baselines/reference/numberVsBigIntOperations.js create mode 100644 tests/baselines/reference/numberVsBigIntOperations.symbols create mode 100644 tests/baselines/reference/numberVsBigIntOperations.types create mode 100644 tests/baselines/reference/parseBigInt.errors.txt create mode 100644 tests/baselines/reference/parseBigInt.js create mode 100644 tests/baselines/reference/parseBigInt.symbols create mode 100644 tests/baselines/reference/parseBigInt.types create mode 100644 tests/cases/compiler/bigintIndex.ts create mode 100644 tests/cases/compiler/bigintWithLib.ts create mode 100644 tests/cases/compiler/bigintWithoutLib.ts create mode 100644 tests/cases/compiler/numberVsBigIntOperations.ts create mode 100644 tests/cases/compiler/parseBigInt.ts diff --git a/tests/baselines/reference/bigintIndex.errors.txt b/tests/baselines/reference/bigintIndex.errors.txt new file mode 100644 index 00000000000..a862f44e658 --- /dev/null +++ b/tests/baselines/reference/bigintIndex.errors.txt @@ -0,0 +1,37 @@ +tests/cases/compiler/bigintIndex.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/bigintIndex.ts(8,11): error TS2538: Type '1n' cannot be used as an index type. +tests/cases/compiler/bigintIndex.ts(14,1): error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. +tests/cases/compiler/bigintIndex.ts(19,12): error TS2538: Type 'bigint' cannot be used as an index type. + + +==== tests/cases/compiler/bigintIndex.ts (4 errors) ==== + interface BigIntIndex { + [index: bigint]: E; // should error + ~~~~~ +!!! error TS1023: An index signature parameter type must be 'string' or 'number'. + } + + const arr: number[] = [1, 2, 3]; + let num: number = arr[1]; + num = arr["1"]; + num = arr[1n]; // should error + ~~ +!!! error TS2538: Type '1n' cannot be used as an index type. + + let key: keyof any; // should be type "string | number | symbol" + key = 123; + key = "abc"; + key = Symbol(); + key = 123n; // should error + ~~~ +!!! error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. + + // Show correct usage of bigint index: explicitly convert to string + const bigNum: bigint = 0n; + const typedArray = new Uint8Array(3); + typedArray[bigNum] = 0xAA; // should error + ~~~~~~ +!!! error TS2538: Type 'bigint' cannot be used as an index type. + typedArray[String(bigNum)] = 0xAA; + typedArray["1"] = 0xBB; + typedArray[2] = 0xCC; \ No newline at end of file diff --git a/tests/baselines/reference/bigintIndex.js b/tests/baselines/reference/bigintIndex.js new file mode 100644 index 00000000000..9f87ad8a8aa --- /dev/null +++ b/tests/baselines/reference/bigintIndex.js @@ -0,0 +1,41 @@ +//// [bigintIndex.ts] +interface BigIntIndex { + [index: bigint]: E; // should error +} + +const arr: number[] = [1, 2, 3]; +let num: number = arr[1]; +num = arr["1"]; +num = arr[1n]; // should error + +let key: keyof any; // should be type "string | number | symbol" +key = 123; +key = "abc"; +key = Symbol(); +key = 123n; // should error + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +const typedArray = new Uint8Array(3); +typedArray[bigNum] = 0xAA; // should error +typedArray[String(bigNum)] = 0xAA; +typedArray["1"] = 0xBB; +typedArray[2] = 0xCC; + +//// [bigintIndex.js] +const arr = [1, 2, 3]; +let num = arr[1]; +num = arr["1"]; +num = arr[1n]; // should error +let key; // should be type "string | number | symbol" +key = 123; +key = "abc"; +key = Symbol(); +key = 123n; // should error +// Show correct usage of bigint index: explicitly convert to string +const bigNum = 0n; +const typedArray = new Uint8Array(3); +typedArray[bigNum] = 0xAA; // should error +typedArray[String(bigNum)] = 0xAA; +typedArray["1"] = 0xBB; +typedArray[2] = 0xCC; diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols new file mode 100644 index 00000000000..94187845fc3 --- /dev/null +++ b/tests/baselines/reference/bigintIndex.symbols @@ -0,0 +1,64 @@ +=== tests/cases/compiler/bigintIndex.ts === +interface BigIntIndex { +>BigIntIndex : Symbol(BigIntIndex, Decl(bigintIndex.ts, 0, 0)) +>E : Symbol(E, Decl(bigintIndex.ts, 0, 22)) + + [index: bigint]: E; // should error +>index : Symbol(index, Decl(bigintIndex.ts, 1, 5)) +>E : Symbol(E, Decl(bigintIndex.ts, 0, 22)) +} + +const arr: number[] = [1, 2, 3]; +>arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) + +let num: number = arr[1]; +>num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) +>arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) + +num = arr["1"]; +>num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) +>arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) + +num = arr[1n]; // should error +>num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) +>arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) + +let key: keyof any; // should be type "string | number | symbol" +>key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) + +key = 123; +>key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) + +key = "abc"; +>key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) + +key = Symbol(); +>key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +key = 123n; // should error +>key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +>bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) + +const typedArray = new Uint8Array(3); +>typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +typedArray[bigNum] = 0xAA; // should error +>typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) + +typedArray[String(bigNum)] = 0xAA; +>typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 1 more) +>bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) + +typedArray["1"] = 0xBB; +>typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) + +typedArray[2] = 0xCC; +>typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) + diff --git a/tests/baselines/reference/bigintIndex.types b/tests/baselines/reference/bigintIndex.types new file mode 100644 index 00000000000..0de1940b77c --- /dev/null +++ b/tests/baselines/reference/bigintIndex.types @@ -0,0 +1,98 @@ +=== tests/cases/compiler/bigintIndex.ts === +interface BigIntIndex { + [index: bigint]: E; // should error +>index : bigint +} + +const arr: number[] = [1, 2, 3]; +>arr : number[] +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +let num: number = arr[1]; +>num : number +>arr[1] : number +>arr : number[] +>1 : 1 + +num = arr["1"]; +>num = arr["1"] : any +>num : number +>arr["1"] : any +>arr : number[] +>"1" : "1" + +num = arr[1n]; // should error +>num = arr[1n] : any +>num : number +>arr[1n] : any +>arr : number[] +>1n : 1n + +let key: keyof any; // should be type "string | number | symbol" +>key : string | number | symbol + +key = 123; +>key = 123 : 123 +>key : string | number | symbol +>123 : 123 + +key = "abc"; +>key = "abc" : "abc" +>key : string | number | symbol +>"abc" : "abc" + +key = Symbol(); +>key = Symbol() : symbol +>key : string | number | symbol +>Symbol() : symbol +>Symbol : SymbolConstructor + +key = 123n; // should error +>key = 123n : 123n +>key : string | number | symbol +>123n : 123n + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +>bigNum : bigint +>0n : 0n + +const typedArray = new Uint8Array(3); +>typedArray : Uint8Array +>new Uint8Array(3) : Uint8Array +>Uint8Array : Uint8ArrayConstructor +>3 : 3 + +typedArray[bigNum] = 0xAA; // should error +>typedArray[bigNum] = 0xAA : 170 +>typedArray[bigNum] : any +>typedArray : Uint8Array +>bigNum : bigint +>0xAA : 170 + +typedArray[String(bigNum)] = 0xAA; +>typedArray[String(bigNum)] = 0xAA : 170 +>typedArray[String(bigNum)] : any +>typedArray : Uint8Array +>String(bigNum) : string +>String : StringConstructor +>bigNum : bigint +>0xAA : 170 + +typedArray["1"] = 0xBB; +>typedArray["1"] = 0xBB : 187 +>typedArray["1"] : any +>typedArray : Uint8Array +>"1" : "1" +>0xBB : 187 + +typedArray[2] = 0xCC; +>typedArray[2] = 0xCC : 204 +>typedArray[2] : number +>typedArray : Uint8Array +>2 : 2 +>0xCC : 204 + diff --git a/tests/baselines/reference/bigintWithLib.errors.txt b/tests/baselines/reference/bigintWithLib.errors.txt new file mode 100644 index 00000000000..a24f6ac4802 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.errors.txt @@ -0,0 +1,77 @@ +tests/cases/compiler/bigintWithLib.ts(4,1): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/bigintWithLib.ts(16,33): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. + Type 'number[]' is not assignable to type 'SharedArrayBuffer'. + Property 'byteLength' is missing in type 'number[]'. +tests/cases/compiler/bigintWithLib.ts(21,13): error TS2540: Cannot assign to 'length' because it is a constant or a read-only property. +tests/cases/compiler/bigintWithLib.ts(28,35): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. + Type 'number[]' is not assignable to type 'SharedArrayBuffer'. +tests/cases/compiler/bigintWithLib.ts(33,13): error TS2540: Cannot assign to 'length' because it is a constant or a read-only property. +tests/cases/compiler/bigintWithLib.ts(40,25): error TS2345: Argument of type '-1' is not assignable to parameter of type 'bigint'. +tests/cases/compiler/bigintWithLib.ts(43,26): error TS2345: Argument of type '123' is not assignable to parameter of type 'bigint'. + + +==== tests/cases/compiler/bigintWithLib.ts (7 errors) ==== + // Test BigInt functions + let bigintVal: bigint = BigInt(123); + bigintVal = BigInt("456"); + new BigInt(123); // should error + ~~~~~~~~~~~~~~~ +!!! error TS2350: Only a void function can be called with the 'new' keyword. + bigintVal = BigInt.asIntN(8, 0xFFFFn); + bigintVal = BigInt.asUintN(8, 0xFFFFn); + bigintVal = bigintVal.valueOf(); + let stringVal: string = bigintVal.toString(); + stringVal = bigintVal.toString(2); + stringVal = bigintVal.toLocaleString(); + + // Test BigInt64Array + let bigIntArray: BigInt64Array = new BigInt64Array(); + bigIntArray = new BigInt64Array(10); + bigIntArray = new BigInt64Array([1n, 2n, 3n]); + bigIntArray = new BigInt64Array([1, 2, 3]); // should error + ~~~~~~~~~ +!!! error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. +!!! error TS2345: Type 'number[]' is not assignable to type 'SharedArrayBuffer'. +!!! error TS2345: Property 'byteLength' is missing in type 'number[]'. + bigIntArray = new BigInt64Array(new ArrayBuffer(80)); + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); + let len: number = bigIntArray.length; + bigIntArray.length = 10; // should error + ~~~~~~ +!!! error TS2540: Cannot assign to 'length' because it is a constant or a read-only property. + let arrayBufferLike: ArrayBufferView = bigIntArray; + + // Test BigUint64Array + let bigUintArray: BigUint64Array = new BigUint64Array(); + bigUintArray = new BigUint64Array(10); + bigUintArray = new BigUint64Array([1n, 2n, 3n]); + bigUintArray = new BigUint64Array([1, 2, 3]); // should error + ~~~~~~~~~ +!!! error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. +!!! error TS2345: Type 'number[]' is not assignable to type 'SharedArrayBuffer'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80)); + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); + len = bigIntArray.length; + bigIntArray.length = 10; // should error + ~~~~~~ +!!! error TS2540: Cannot assign to 'length' because it is a constant or a read-only property. + arrayBufferLike = bigIntArray; + + // Test added DataView methods + const dataView = new DataView(new ArrayBuffer(80)); + dataView.setBigInt64(1, -1n); + dataView.setBigInt64(1, -1n, true); + dataView.setBigInt64(1, -1); // should error + ~~ +!!! error TS2345: Argument of type '-1' is not assignable to parameter of type 'bigint'. + dataView.setBigUint64(2, 123n); + dataView.setBigUint64(2, 123n, true); + dataView.setBigUint64(2, 123); // should error + ~~~ +!!! error TS2345: Argument of type '123' is not assignable to parameter of type 'bigint'. + bigintVal = dataView.getBigInt64(1); + bigintVal = dataView.getBigInt64(1, true); + bigintVal = dataView.getBigUint64(2); + bigintVal = dataView.getBigUint64(2, true); \ No newline at end of file diff --git a/tests/baselines/reference/bigintWithLib.js b/tests/baselines/reference/bigintWithLib.js new file mode 100644 index 00000000000..e25decf9312 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.js @@ -0,0 +1,94 @@ +//// [bigintWithLib.ts] +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); // should error +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); +let stringVal: string = bigintVal.toString(); +stringVal = bigintVal.toString(2); +stringVal = bigintVal.toLocaleString(); + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; // should error +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; // should error +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); // should error +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); // should error +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); + +//// [bigintWithLib.js] +// Test BigInt functions +let bigintVal = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); // should error +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); +let stringVal = bigintVal.toString(); +stringVal = bigintVal.toString(2); +stringVal = bigintVal.toLocaleString(); +// Test BigInt64Array +let bigIntArray = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len = bigIntArray.length; +bigIntArray.length = 10; // should error +let arrayBufferLike = bigIntArray; +// Test BigUint64Array +let bigUintArray = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; // should error +arrayBufferLike = bigIntArray; +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); // should error +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); // should error +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); diff --git a/tests/baselines/reference/bigintWithLib.symbols b/tests/baselines/reference/bigintWithLib.symbols new file mode 100644 index 00000000000..0f313251ab0 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.symbols @@ -0,0 +1,206 @@ +=== tests/cases/compiler/bigintWithLib.ts === +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt("456"); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +new BigInt(123); // should error +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt.asIntN : Symbol(BigIntConstructor.asIntN, Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>asIntN : Symbol(BigIntConstructor.asIntN, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt.asUintN : Symbol(BigIntConstructor.asUintN, Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>asUintN : Symbol(BigIntConstructor.asUintN, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = bigintVal.valueOf(); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>bigintVal.valueOf : Symbol(BigInt.valueOf, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>valueOf : Symbol(BigInt.valueOf, Decl(lib.esnext.bigint.d.ts, --, --)) + +let stringVal: string = bigintVal.toString(); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) + +stringVal = bigintVal.toString(2); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) + +stringVal = bigintVal.toLocaleString(); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toLocaleString : Symbol(BigInt.toLocaleString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toLocaleString : Symbol(BigInt.toLocaleString, Decl(lib.esnext.bigint.d.ts, --, --)) + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array(10); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +let len: number = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithLib.ts, 19, 3)) +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray.length = 10; // should error +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithLib.ts, 21, 3)) +>ArrayBufferView : Symbol(ArrayBufferView, Decl(lib.es5.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array(10); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +len = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithLib.ts, 19, 3)) +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray.length = 10; // should error +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +arrayBufferLike = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>DataView : Symbol(DataView, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigInt64(1, -1); // should error +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123); // should error +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigInt64(1); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigUint64(2); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + diff --git a/tests/baselines/reference/bigintWithLib.types b/tests/baselines/reference/bigintWithLib.types new file mode 100644 index 00000000000..5ba273091b6 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.types @@ -0,0 +1,334 @@ +=== tests/cases/compiler/bigintWithLib.ts === +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : bigint +>BigInt(123) : bigint +>BigInt : BigIntConstructor +>123 : 123 + +bigintVal = BigInt("456"); +>bigintVal = BigInt("456") : bigint +>bigintVal : bigint +>BigInt("456") : bigint +>BigInt : BigIntConstructor +>"456" : "456" + +new BigInt(123); // should error +>new BigInt(123) : any +>BigInt : BigIntConstructor +>123 : 123 + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal = BigInt.asIntN(8, 0xFFFFn) : bigint +>bigintVal : bigint +>BigInt.asIntN(8, 0xFFFFn) : bigint +>BigInt.asIntN : (bits: number, int: bigint) => bigint +>BigInt : BigIntConstructor +>asIntN : (bits: number, int: bigint) => bigint +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal = BigInt.asUintN(8, 0xFFFFn) : bigint +>bigintVal : bigint +>BigInt.asUintN(8, 0xFFFFn) : bigint +>BigInt.asUintN : (bits: number, int: bigint) => bigint +>BigInt : BigIntConstructor +>asUintN : (bits: number, int: bigint) => bigint +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = bigintVal.valueOf(); +>bigintVal = bigintVal.valueOf() : bigint +>bigintVal : bigint +>bigintVal.valueOf() : bigint +>bigintVal.valueOf : () => bigint +>bigintVal : bigint +>valueOf : () => bigint + +let stringVal: string = bigintVal.toString(); +>stringVal : string +>bigintVal.toString() : string +>bigintVal.toString : (radix?: number) => string +>bigintVal : bigint +>toString : (radix?: number) => string + +stringVal = bigintVal.toString(2); +>stringVal = bigintVal.toString(2) : string +>stringVal : string +>bigintVal.toString(2) : string +>bigintVal.toString : (radix?: number) => string +>bigintVal : bigint +>toString : (radix?: number) => string +>2 : 2 + +stringVal = bigintVal.toLocaleString(); +>stringVal = bigintVal.toLocaleString() : string +>stringVal : string +>bigintVal.toLocaleString() : string +>bigintVal.toLocaleString : () => string +>bigintVal : bigint +>toLocaleString : () => string + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : BigInt64Array +>new BigInt64Array() : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor + +bigIntArray = new BigInt64Array(10); +>bigIntArray = new BigInt64Array(10) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(10) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>10 : 10 + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray = new BigInt64Array([1n, 2n, 3n]) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array([1n, 2n, 3n]) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +>bigIntArray = new BigInt64Array([1, 2, 3]) : any +>bigIntArray : BigInt64Array +>new BigInt64Array([1, 2, 3]) : any +>BigInt64Array : BigInt64ArrayConstructor +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80)) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80)) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80), 8) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80), 8, 3) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +let len: number = bigIntArray.length; +>len : number +>bigIntArray.length : number +>bigIntArray : BigInt64Array +>length : number + +bigIntArray.length = 10; // should error +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : BigInt64Array +>length : any +>10 : 10 + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : ArrayBufferView +>bigIntArray : BigInt64Array + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : BigUint64Array +>new BigUint64Array() : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor + +bigUintArray = new BigUint64Array(10); +>bigUintArray = new BigUint64Array(10) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(10) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>10 : 10 + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray = new BigUint64Array([1n, 2n, 3n]) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array([1n, 2n, 3n]) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +>bigUintArray = new BigUint64Array([1, 2, 3]) : any +>bigUintArray : BigUint64Array +>new BigUint64Array([1, 2, 3]) : any +>BigUint64Array : BigUint64ArrayConstructor +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80)) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80)) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80), 8) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80), 8, 3) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +len = bigIntArray.length; +>len = bigIntArray.length : number +>len : number +>bigIntArray.length : number +>bigIntArray : BigInt64Array +>length : number + +bigIntArray.length = 10; // should error +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : BigInt64Array +>length : any +>10 : 10 + +arrayBufferLike = bigIntArray; +>arrayBufferLike = bigIntArray : BigInt64Array +>arrayBufferLike : ArrayBufferView +>bigIntArray : BigInt64Array + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : DataView +>new DataView(new ArrayBuffer(80)) : DataView +>DataView : DataViewConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64(1, -1n) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1n : -1n +>1n : 1n + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64(1, -1n, true) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1n : -1n +>1n : 1n +>true : true + +dataView.setBigInt64(1, -1); // should error +>dataView.setBigInt64(1, -1) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1 : -1 +>1 : 1 + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64(2, 123n) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123n : 123n + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64(2, 123n, true) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123n : 123n +>true : true + +dataView.setBigUint64(2, 123); // should error +>dataView.setBigUint64(2, 123) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123 : 123 + +bigintVal = dataView.getBigInt64(1); +>bigintVal = dataView.getBigInt64(1) : bigint +>bigintVal : bigint +>dataView.getBigInt64(1) : bigint +>dataView.getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>1 : 1 + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal = dataView.getBigInt64(1, true) : bigint +>bigintVal : bigint +>dataView.getBigInt64(1, true) : bigint +>dataView.getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>1 : 1 +>true : true + +bigintVal = dataView.getBigUint64(2); +>bigintVal = dataView.getBigUint64(2) : bigint +>bigintVal : bigint +>dataView.getBigUint64(2) : bigint +>dataView.getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>2 : 2 + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal = dataView.getBigUint64(2, true) : bigint +>bigintVal : bigint +>dataView.getBigUint64(2, true) : bigint +>dataView.getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>2 : 2 +>true : true + diff --git a/tests/baselines/reference/bigintWithoutLib.errors.txt b/tests/baselines/reference/bigintWithoutLib.errors.txt new file mode 100644 index 00000000000..d06e99464cd --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.errors.txt @@ -0,0 +1,155 @@ +tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(9,1): error TS2322: Type 'Object' is not assignable to type 'bigint'. +tests/cases/compiler/bigintWithoutLib.ts(11,13): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/bigintWithoutLib.ts(15,18): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(16,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(17,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(18,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(21,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(27,19): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(27,40): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(28,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(29,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(30,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(40,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(41,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(42,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(46,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(47,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(48,22): error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. + + +==== tests/cases/compiler/bigintWithoutLib.ts (33 errors) ==== + // Every line should error because these builtins are not declared + + // Test BigInt functions + let bigintVal: bigint = BigInt(123); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = BigInt("456"); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + new BigInt(123); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = BigInt.asIntN(8, 0xFFFFn); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = BigInt.asUintN(8, 0xFFFFn); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} + ~~~~~~~~~ +!!! error TS2322: Type 'Object' is not assignable to type 'bigint'. + let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} + stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 0 arguments, but got 1. + stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} + + // Test BigInt64Array + let bigIntArray: BigInt64Array = new BigInt64Array(); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array(10); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array([1n, 2n, 3n]); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array([1, 2, 3]); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array(new ArrayBuffer(80)); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + let len: number = bigIntArray.length; + bigIntArray.length = 10; + let arrayBufferLike: ArrayBufferView = bigIntArray; + + // Test BigUint64Array + let bigUintArray: BigUint64Array = new BigUint64Array(); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(10); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array([1n, 2n, 3n]); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array([1, 2, 3]); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80)); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + len = bigIntArray.length; + bigIntArray.length = 10; + arrayBufferLike = bigIntArray; + + // Test added DataView methods + const dataView = new DataView(new ArrayBuffer(80)); + dataView.setBigInt64(1, -1n); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + dataView.setBigInt64(1, -1n, true); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + dataView.setBigInt64(1, -1); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + dataView.setBigUint64(2, 123n); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + dataView.setBigUint64(2, 123n, true); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + dataView.setBigUint64(2, 123); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + bigintVal = dataView.getBigInt64(1); + ~~~~~~~~~~~ +!!! error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. + bigintVal = dataView.getBigInt64(1, true); + ~~~~~~~~~~~ +!!! error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. + bigintVal = dataView.getBigUint64(2); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. + bigintVal = dataView.getBigUint64(2, true); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. \ No newline at end of file diff --git a/tests/baselines/reference/bigintWithoutLib.js b/tests/baselines/reference/bigintWithoutLib.js new file mode 100644 index 00000000000..67265ca8720 --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.js @@ -0,0 +1,97 @@ +//// [bigintWithoutLib.ts] +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); + +//// [bigintWithoutLib.js] +// Every line should error because these builtins are not declared +// Test BigInt functions +var bigintVal = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +var stringVal = bigintVal.toString(); // should not error - bigintVal inferred as {} +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +// Test BigInt64Array +var bigIntArray = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +var len = bigIntArray.length; +bigIntArray.length = 10; +var arrayBufferLike = bigIntArray; +// Test BigUint64Array +var bigUintArray = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; +arrayBufferLike = bigIntArray; +// Test added DataView methods +var dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); diff --git a/tests/baselines/reference/bigintWithoutLib.symbols b/tests/baselines/reference/bigintWithoutLib.symbols new file mode 100644 index 00000000000..35e69305e18 --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.symbols @@ -0,0 +1,154 @@ +=== tests/cases/compiler/bigintWithoutLib.ts === +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = BigInt("456"); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>bigintVal.valueOf : Symbol(Object.valueOf, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>valueOf : Symbol(Object.valueOf, Decl(lib.es5.d.ts, --, --)) + +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) + +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) + +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toLocaleString : Symbol(Object.toLocaleString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toLocaleString : Symbol(Object.toLocaleString, Decl(lib.es5.d.ts, --, --)) + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array(10); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array([1, 2, 3]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +let len: number = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithoutLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray.length = 10; +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithoutLib.ts, 23, 3)) +>ArrayBufferView : Symbol(ArrayBufferView, Decl(lib.es5.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array(10); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array([1, 2, 3]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +len = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithoutLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray.length = 10; +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +arrayBufferLike = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithoutLib.ts, 23, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) +>DataView : Symbol(DataView, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +dataView.setBigInt64(1, -1n); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigInt64(1, -1n, true); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigInt64(1, -1); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123n); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123n, true); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigInt64(1); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigUint64(2); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + diff --git a/tests/baselines/reference/bigintWithoutLib.types b/tests/baselines/reference/bigintWithoutLib.types new file mode 100644 index 00000000000..6881b53b7da --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.types @@ -0,0 +1,336 @@ +=== tests/cases/compiler/bigintWithoutLib.ts === +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : bigint +>BigInt(123) : any +>BigInt : any +>123 : 123 + +bigintVal = BigInt("456"); +>bigintVal = BigInt("456") : any +>bigintVal : bigint +>BigInt("456") : any +>BigInt : any +>"456" : "456" + +new BigInt(123); +>new BigInt(123) : any +>BigInt : any +>123 : 123 + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal = BigInt.asIntN(8, 0xFFFFn) : any +>bigintVal : bigint +>BigInt.asIntN(8, 0xFFFFn) : any +>BigInt.asIntN : any +>BigInt : any +>asIntN : any +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal = BigInt.asUintN(8, 0xFFFFn) : any +>bigintVal : bigint +>BigInt.asUintN(8, 0xFFFFn) : any +>BigInt.asUintN : any +>BigInt : any +>asUintN : any +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +>bigintVal = bigintVal.valueOf() : Object +>bigintVal : bigint +>bigintVal.valueOf() : Object +>bigintVal.valueOf : () => Object +>bigintVal : bigint +>valueOf : () => Object + +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +>stringVal : string +>bigintVal.toString() : string +>bigintVal.toString : () => string +>bigintVal : bigint +>toString : () => string + +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +>stringVal = bigintVal.toString(2) : any +>stringVal : string +>bigintVal.toString(2) : string +>bigintVal.toString : () => string +>bigintVal : bigint +>toString : () => string +>2 : 2 + +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +>stringVal = bigintVal.toLocaleString() : string +>stringVal : string +>bigintVal.toLocaleString() : string +>bigintVal.toLocaleString : () => string +>bigintVal : bigint +>toLocaleString : () => string + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : any +>new BigInt64Array() : any +>BigInt64Array : any + +bigIntArray = new BigInt64Array(10); +>bigIntArray = new BigInt64Array(10) : any +>bigIntArray : any +>new BigInt64Array(10) : any +>BigInt64Array : any +>10 : 10 + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray = new BigInt64Array([1n, 2n, 3n]) : any +>bigIntArray : any +>new BigInt64Array([1n, 2n, 3n]) : any +>BigInt64Array : any +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigIntArray = new BigInt64Array([1, 2, 3]); +>bigIntArray = new BigInt64Array([1, 2, 3]) : any +>bigIntArray : any +>new BigInt64Array([1, 2, 3]) : any +>BigInt64Array : any +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80)) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80)) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80), 8) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80), 8, 3) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +let len: number = bigIntArray.length; +>len : number +>bigIntArray.length : any +>bigIntArray : any +>length : any + +bigIntArray.length = 10; +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : any +>length : any +>10 : 10 + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : ArrayBufferView +>bigIntArray : any + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : any +>new BigUint64Array() : any +>BigUint64Array : any + +bigUintArray = new BigUint64Array(10); +>bigUintArray = new BigUint64Array(10) : any +>bigUintArray : any +>new BigUint64Array(10) : any +>BigUint64Array : any +>10 : 10 + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray = new BigUint64Array([1n, 2n, 3n]) : any +>bigUintArray : any +>new BigUint64Array([1n, 2n, 3n]) : any +>BigUint64Array : any +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigUintArray = new BigUint64Array([1, 2, 3]); +>bigUintArray = new BigUint64Array([1, 2, 3]) : any +>bigUintArray : any +>new BigUint64Array([1, 2, 3]) : any +>BigUint64Array : any +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80)) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80)) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80), 8) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80), 8, 3) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +len = bigIntArray.length; +>len = bigIntArray.length : any +>len : number +>bigIntArray.length : any +>bigIntArray : any +>length : any + +bigIntArray.length = 10; +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : any +>length : any +>10 : 10 + +arrayBufferLike = bigIntArray; +>arrayBufferLike = bigIntArray : any +>arrayBufferLike : ArrayBufferView +>bigIntArray : any + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : DataView +>new DataView(new ArrayBuffer(80)) : DataView +>DataView : DataViewConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64(1, -1n) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1n : -1n +>1n : 1n + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64(1, -1n, true) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1n : -1n +>1n : 1n +>true : true + +dataView.setBigInt64(1, -1); +>dataView.setBigInt64(1, -1) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1 : -1 +>1 : 1 + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64(2, 123n) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123n : 123n + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64(2, 123n, true) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123n : 123n +>true : true + +dataView.setBigUint64(2, 123); +>dataView.setBigUint64(2, 123) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123 : 123 + +bigintVal = dataView.getBigInt64(1); +>bigintVal = dataView.getBigInt64(1) : any +>bigintVal : bigint +>dataView.getBigInt64(1) : any +>dataView.getBigInt64 : any +>dataView : DataView +>getBigInt64 : any +>1 : 1 + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal = dataView.getBigInt64(1, true) : any +>bigintVal : bigint +>dataView.getBigInt64(1, true) : any +>dataView.getBigInt64 : any +>dataView : DataView +>getBigInt64 : any +>1 : 1 +>true : true + +bigintVal = dataView.getBigUint64(2); +>bigintVal = dataView.getBigUint64(2) : any +>bigintVal : bigint +>dataView.getBigUint64(2) : any +>dataView.getBigUint64 : any +>dataView : DataView +>getBigUint64 : any +>2 : 2 + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal = dataView.getBigUint64(2, true) : any +>bigintVal : bigint +>dataView.getBigUint64(2, true) : any +>dataView.getBigUint64 : any +>dataView : DataView +>getBigUint64 : any +>2 : 2 +>true : true + diff --git a/tests/baselines/reference/numberVsBigIntOperations.errors.txt b/tests/baselines/reference/numberVsBigIntOperations.errors.txt new file mode 100644 index 00000000000..58d19e6f7b9 --- /dev/null +++ b/tests/baselines/reference/numberVsBigIntOperations.errors.txt @@ -0,0 +1,289 @@ +tests/cases/compiler/numberVsBigIntOperations.ts(3,14): error TS2322: Type '2' is not assignable to type 'bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(3,26): error TS2322: Type '1n' is not assignable to type 'number'. +tests/cases/compiler/numberVsBigIntOperations.ts(4,15): error TS2365: Operator '+=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(4,28): error TS2365: Operator '+=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(5,15): error TS2365: Operator '-=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(5,28): error TS2365: Operator '-=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(6,15): error TS2365: Operator '*=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(6,28): error TS2365: Operator '*=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(7,15): error TS2365: Operator '/=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(7,28): error TS2365: Operator '/=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(8,15): error TS2365: Operator '%=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(8,28): error TS2365: Operator '%=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(9,16): error TS2365: Operator '**=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(9,30): error TS2365: Operator '**=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(10,16): error TS2365: Operator '<<=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(10,30): error TS2365: Operator '<<=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(11,16): error TS2365: Operator '>>=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(11,30): error TS2365: Operator '>>=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(12,15): error TS2365: Operator '&=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(12,28): error TS2365: Operator '&=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(13,15): error TS2365: Operator '^=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(13,28): error TS2365: Operator '^=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(14,15): error TS2365: Operator '|=' cannot be applied to types 'bigint' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(14,28): error TS2365: Operator '|=' cannot be applied to types 'number' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(15,32): error TS2365: Operator '+' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(15,40): error TS2365: Operator '+' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(16,32): error TS2365: Operator '-' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(16,40): error TS2365: Operator '-' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(17,32): error TS2365: Operator '*' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(17,40): error TS2365: Operator '*' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(18,32): error TS2365: Operator '/' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(18,40): error TS2365: Operator '/' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(19,32): error TS2365: Operator '%' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(19,40): error TS2365: Operator '%' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(20,34): error TS2365: Operator '**' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(20,43): error TS2365: Operator '**' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(21,32): error TS2365: Operator '&' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(21,40): error TS2365: Operator '&' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(22,32): error TS2365: Operator '|' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(22,40): error TS2365: Operator '|' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(23,32): error TS2365: Operator '^' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(23,40): error TS2365: Operator '^' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(24,34): error TS2365: Operator '<<' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(24,43): error TS2365: Operator '<<' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(25,34): error TS2365: Operator '>>' cannot be applied to types '1' and '2n'. +tests/cases/compiler/numberVsBigIntOperations.ts(25,43): error TS2365: Operator '>>' cannot be applied to types '1n' and '2'. +tests/cases/compiler/numberVsBigIntOperations.ts(38,1): error TS2365: Operator '>>>=' cannot be applied to types 'bigint' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(39,10): error TS2365: Operator '>>>' cannot be applied to types 'bigint' and '1n'. +tests/cases/compiler/numberVsBigIntOperations.ts(40,8): error TS2735: Operator '+' cannot be applied to type 'bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(50,10): error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. +tests/cases/compiler/numberVsBigIntOperations.ts(51,10): error TS2367: This condition will always return 'true' since the types 'bigint' and 'number' have no overlap. +tests/cases/compiler/numberVsBigIntOperations.ts(52,10): error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. +tests/cases/compiler/numberVsBigIntOperations.ts(53,10): error TS2367: This condition will always return 'true' since the types 'bigint' and 'number' have no overlap. +tests/cases/compiler/numberVsBigIntOperations.ts(56,7): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/numberVsBigIntOperations.ts(56,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/numberVsBigIntOperations.ts(57,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/numberVsBigIntOperations.ts(57,1): error TS2365: Operator '&' cannot be applied to types '"3"' and '5n'. +tests/cases/compiler/numberVsBigIntOperations.ts(57,11): error TS2365: Operator '**' cannot be applied to types '2n' and 'false'. +tests/cases/compiler/numberVsBigIntOperations.ts(57,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/numberVsBigIntOperations.ts(60,1): error TS2365: Operator '+' cannot be applied to types 'number | bigint' and 'number | bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(61,1): error TS2365: Operator '<<' cannot be applied to types 'number | bigint' and 'number | bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(70,2): error TS2735: Operator '+' cannot be applied to type 'number | bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(86,7): error TS1155: 'const' declarations must be initialized. +tests/cases/compiler/numberVsBigIntOperations.ts(93,7): error TS1155: 'const' declarations must be initialized. + + +==== tests/cases/compiler/numberVsBigIntOperations.ts (64 errors) ==== + // Cannot mix bigints and numbers + let bigInt = 1n, num = 2; + bigInt = 1n; bigInt = 2; num = 1n; num = 2; + ~~~~~~ +!!! error TS2322: Type '2' is not assignable to type 'bigint'. + ~~~ +!!! error TS2322: Type '1n' is not assignable to type 'number'. + bigInt += 1n; bigInt += 2; num += 1n; num += 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '+=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '+=' cannot be applied to types 'number' and '1n'. + bigInt -= 1n; bigInt -= 2; num -= 1n; num -= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '-=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '-=' cannot be applied to types 'number' and '1n'. + bigInt *= 1n; bigInt *= 2; num *= 1n; num *= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '*=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '*=' cannot be applied to types 'number' and '1n'. + bigInt /= 1n; bigInt /= 2; num /= 1n; num /= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '/=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '/=' cannot be applied to types 'number' and '1n'. + bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '%=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '%=' cannot be applied to types 'number' and '1n'. + bigInt **= 1n; bigInt **= 2; num **= 1n; num **= 2; + ~~~~~~~~~~~~ +!!! error TS2365: Operator '**=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~~ +!!! error TS2365: Operator '**=' cannot be applied to types 'number' and '1n'. + bigInt <<= 1n; bigInt <<= 2; num <<= 1n; num <<= 2; + ~~~~~~~~~~~~ +!!! error TS2365: Operator '<<=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~~ +!!! error TS2365: Operator '<<=' cannot be applied to types 'number' and '1n'. + bigInt >>= 1n; bigInt >>= 2; num >>= 1n; num >>= 2; + ~~~~~~~~~~~~ +!!! error TS2365: Operator '>>=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~~ +!!! error TS2365: Operator '>>=' cannot be applied to types 'number' and '1n'. + bigInt &= 1n; bigInt &= 2; num &= 1n; num &= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '&=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '&=' cannot be applied to types 'number' and '1n'. + bigInt ^= 1n; bigInt ^= 2; num ^= 1n; num ^= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '^=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '^=' cannot be applied to types 'number' and '1n'. + bigInt |= 1n; bigInt |= 2; num |= 1n; num |= 2; + ~~~~~~~~~~~ +!!! error TS2365: Operator '|=' cannot be applied to types 'bigint' and '2'. + ~~~~~~~~~ +!!! error TS2365: Operator '|=' cannot be applied to types 'number' and '1n'. + bigInt = 1n + 2n; num = 1 + 2; 1 + 2n; 1n + 2; + ~~~~~~ +!!! error TS2365: Operator '+' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '+' cannot be applied to types '1n' and '2'. + bigInt = 1n - 2n; num = 1 - 2; 1 - 2n; 1n - 2; + ~~~~~~ +!!! error TS2365: Operator '-' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '-' cannot be applied to types '1n' and '2'. + bigInt = 1n * 2n; num = 1 * 2; 1 * 2n; 1n * 2; + ~~~~~~ +!!! error TS2365: Operator '*' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '*' cannot be applied to types '1n' and '2'. + bigInt = 1n / 2n; num = 1 / 2; 1 / 2n; 1n / 2; + ~~~~~~ +!!! error TS2365: Operator '/' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '/' cannot be applied to types '1n' and '2'. + bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; + ~~~~~~ +!!! error TS2365: Operator '%' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '%' cannot be applied to types '1n' and '2'. + bigInt = 1n ** 2n; num = 1 ** 2; 1 ** 2n; 1n ** 2; + ~~~~~~~ +!!! error TS2365: Operator '**' cannot be applied to types '1' and '2n'. + ~~~~~~~ +!!! error TS2365: Operator '**' cannot be applied to types '1n' and '2'. + bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; 1n & 2; + ~~~~~~ +!!! error TS2365: Operator '&' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '&' cannot be applied to types '1n' and '2'. + bigInt = 1n | 2n; num = 1 | 2; 1 | 2n; 1n | 2; + ~~~~~~ +!!! error TS2365: Operator '|' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '|' cannot be applied to types '1n' and '2'. + bigInt = 1n ^ 2n; num = 1 ^ 2; 1 ^ 2n; 1n ^ 2; + ~~~~~~ +!!! error TS2365: Operator '^' cannot be applied to types '1' and '2n'. + ~~~~~~ +!!! error TS2365: Operator '^' cannot be applied to types '1n' and '2'. + bigInt = 1n << 2n; num = 1 << 2; 1 << 2n; 1n << 2; + ~~~~~~~ +!!! error TS2365: Operator '<<' cannot be applied to types '1' and '2n'. + ~~~~~~~ +!!! error TS2365: Operator '<<' cannot be applied to types '1n' and '2'. + bigInt = 1n >> 2n; num = 1 >> 2; 1 >> 2n; 1n >> 2; + ~~~~~~~ +!!! error TS2365: Operator '>>' cannot be applied to types '1' and '2n'. + ~~~~~~~ +!!! error TS2365: Operator '>>' cannot be applied to types '1n' and '2'. + + // Plus should still coerce to strings + let str: string; + str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; str = 123n + "abc"; + + // Unary operations allowed on bigints and numbers + bigInt = bigInt++; bigInt = ++bigInt; num = num++; num = ++num; + bigInt = bigInt--; bigInt = --bigInt; num = num--; num = --num; + bigInt = -bigInt; num = -num; + bigInt = ~bigInt; num = ~num; + + // Number-only operations + bigInt >>>= 1n; num >>>= 2; + ~~~~~~~~~~~~~~ +!!! error TS2365: Operator '>>>=' cannot be applied to types 'bigint' and '1n'. + bigInt = bigInt >>> 1n; num = num >>> 2; + ~~~~~~~~~~~~~ +!!! error TS2365: Operator '>>>' cannot be applied to types 'bigint' and '1n'. + num = +bigInt; num = +num; num = +"3"; + ~~~~~~ +!!! error TS2735: Operator '+' cannot be applied to type 'bigint'. + + // Comparisons can be mixed + let result: boolean; + result = bigInt > num; + result = bigInt >= num; + result = bigInt < num; + result = bigInt <= num; + + // Trying to compare for equality is likely an error (since 1 == "1" is disallowed) + result = bigInt == num; + ~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. + result = bigInt != num; + ~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types 'bigint' and 'number' have no overlap. + result = bigInt === num; + ~~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. + result = bigInt !== num; + ~~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'true' since the types 'bigint' and 'number' have no overlap. + + // Types of arithmetic operations on other types + num = "3" & 5; num = 2 ** false; // should error, but infer number + ~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. + ~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. + "3" & 5n; 2n ** false; // should error, result in any + ~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. + ~~~~~~~~ +!!! error TS2365: Operator '&' cannot be applied to types '"3"' and '5n'. + ~~~~~~~~~~~ +!!! error TS2365: Operator '**' cannot be applied to types '2n' and 'false'. + ~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. + num = ~"3"; num = -false; // should infer number + let bigIntOrNumber: bigint | number; + bigIntOrNumber + bigIntOrNumber; // should error, result in any + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '+' cannot be applied to types 'number | bigint' and 'number | bigint'. + bigIntOrNumber << bigIntOrNumber; // should error, result in any + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2365: Operator '<<' cannot be applied to types 'number | bigint' and 'number | bigint'. + if (typeof bigIntOrNumber === "bigint") { + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; + } + if (typeof bigIntOrNumber === "number") { + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; + } + +bigIntOrNumber; // should error, result in number + ~~~~~~~~~~~~~~ +!!! error TS2735: Operator '+' cannot be applied to type 'number | bigint'. + ~bigIntOrNumber; // should infer number | bigint + bigIntOrNumber++; // should infer number | bigint + ++bigIntOrNumber; // should infer number | bigint + let anyValue: any; + anyValue + anyValue; // should infer any + anyValue >>> anyValue; // should infer number + anyValue ^ anyValue; // should infer number + +anyValue; // should infer number + -anyValue; // should infer number + anyValue--; // should infer number + --anyValue; // should infer number + + // Distinguishing numbers from bigints with typeof + const isBigInt: (x: 0n | 1n) => bigint = (x: 0n | 1n) => x; + const isNumber: (x: 0 | 1) => number = (x: 0 | 1) => x; + const zeroOrBigOne: 0 | 1n; + ~~~~~~~~~~~~ +!!! error TS1155: 'const' declarations must be initialized. + if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); + else isNumber(zeroOrBigOne); + + // Distinguishing truthy from falsy + const isOne = (x: 1 | 1n) => x; + if (zeroOrBigOne) isOne(zeroOrBigOne); + const bigZeroOrOne: 0n | 1; + ~~~~~~~~~~~~ +!!! error TS1155: 'const' declarations must be initialized. + if (bigZeroOrOne) isOne(bigZeroOrOne); \ No newline at end of file diff --git a/tests/baselines/reference/numberVsBigIntOperations.js b/tests/baselines/reference/numberVsBigIntOperations.js new file mode 100644 index 00000000000..c1d448831dc --- /dev/null +++ b/tests/baselines/reference/numberVsBigIntOperations.js @@ -0,0 +1,274 @@ +//// [numberVsBigIntOperations.ts] +// Cannot mix bigints and numbers +let bigInt = 1n, num = 2; +bigInt = 1n; bigInt = 2; num = 1n; num = 2; +bigInt += 1n; bigInt += 2; num += 1n; num += 2; +bigInt -= 1n; bigInt -= 2; num -= 1n; num -= 2; +bigInt *= 1n; bigInt *= 2; num *= 1n; num *= 2; +bigInt /= 1n; bigInt /= 2; num /= 1n; num /= 2; +bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; +bigInt **= 1n; bigInt **= 2; num **= 1n; num **= 2; +bigInt <<= 1n; bigInt <<= 2; num <<= 1n; num <<= 2; +bigInt >>= 1n; bigInt >>= 2; num >>= 1n; num >>= 2; +bigInt &= 1n; bigInt &= 2; num &= 1n; num &= 2; +bigInt ^= 1n; bigInt ^= 2; num ^= 1n; num ^= 2; +bigInt |= 1n; bigInt |= 2; num |= 1n; num |= 2; +bigInt = 1n + 2n; num = 1 + 2; 1 + 2n; 1n + 2; +bigInt = 1n - 2n; num = 1 - 2; 1 - 2n; 1n - 2; +bigInt = 1n * 2n; num = 1 * 2; 1 * 2n; 1n * 2; +bigInt = 1n / 2n; num = 1 / 2; 1 / 2n; 1n / 2; +bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; +bigInt = 1n ** 2n; num = 1 ** 2; 1 ** 2n; 1n ** 2; +bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; 1n & 2; +bigInt = 1n | 2n; num = 1 | 2; 1 | 2n; 1n | 2; +bigInt = 1n ^ 2n; num = 1 ^ 2; 1 ^ 2n; 1n ^ 2; +bigInt = 1n << 2n; num = 1 << 2; 1 << 2n; 1n << 2; +bigInt = 1n >> 2n; num = 1 >> 2; 1 >> 2n; 1n >> 2; + +// Plus should still coerce to strings +let str: string; +str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; str = 123n + "abc"; + +// Unary operations allowed on bigints and numbers +bigInt = bigInt++; bigInt = ++bigInt; num = num++; num = ++num; +bigInt = bigInt--; bigInt = --bigInt; num = num--; num = --num; +bigInt = -bigInt; num = -num; +bigInt = ~bigInt; num = ~num; + +// Number-only operations +bigInt >>>= 1n; num >>>= 2; +bigInt = bigInt >>> 1n; num = num >>> 2; +num = +bigInt; num = +num; num = +"3"; + +// Comparisons can be mixed +let result: boolean; +result = bigInt > num; +result = bigInt >= num; +result = bigInt < num; +result = bigInt <= num; + +// Trying to compare for equality is likely an error (since 1 == "1" is disallowed) +result = bigInt == num; +result = bigInt != num; +result = bigInt === num; +result = bigInt !== num; + +// Types of arithmetic operations on other types +num = "3" & 5; num = 2 ** false; // should error, but infer number +"3" & 5n; 2n ** false; // should error, result in any +num = ~"3"; num = -false; // should infer number +let bigIntOrNumber: bigint | number; +bigIntOrNumber + bigIntOrNumber; // should error, result in any +bigIntOrNumber << bigIntOrNumber; // should error, result in any +if (typeof bigIntOrNumber === "bigint") { + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} +if (typeof bigIntOrNumber === "number") { + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} ++bigIntOrNumber; // should error, result in number +~bigIntOrNumber; // should infer number | bigint +bigIntOrNumber++; // should infer number | bigint +++bigIntOrNumber; // should infer number | bigint +let anyValue: any; +anyValue + anyValue; // should infer any +anyValue >>> anyValue; // should infer number +anyValue ^ anyValue; // should infer number ++anyValue; // should infer number +-anyValue; // should infer number +anyValue--; // should infer number +--anyValue; // should infer number + +// Distinguishing numbers from bigints with typeof +const isBigInt: (x: 0n | 1n) => bigint = (x: 0n | 1n) => x; +const isNumber: (x: 0 | 1) => number = (x: 0 | 1) => x; +const zeroOrBigOne: 0 | 1n; +if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); +else isNumber(zeroOrBigOne); + +// Distinguishing truthy from falsy +const isOne = (x: 1 | 1n) => x; +if (zeroOrBigOne) isOne(zeroOrBigOne); +const bigZeroOrOne: 0n | 1; +if (bigZeroOrOne) isOne(bigZeroOrOne); + +//// [numberVsBigIntOperations.js] +// Cannot mix bigints and numbers +var bigInt = 1n, num = 2; +bigInt = 1n; +bigInt = 2; +num = 1n; +num = 2; +bigInt += 1n; +bigInt += 2; +num += 1n; +num += 2; +bigInt -= 1n; +bigInt -= 2; +num -= 1n; +num -= 2; +bigInt *= 1n; +bigInt *= 2; +num *= 1n; +num *= 2; +bigInt /= 1n; +bigInt /= 2; +num /= 1n; +num /= 2; +bigInt %= 1n; +bigInt %= 2; +num %= 1n; +num %= 2; +bigInt = Math.pow(bigInt, 1n); +bigInt = Math.pow(bigInt, 2); +num = Math.pow(num, 1n); +num = Math.pow(num, 2); +bigInt <<= 1n; +bigInt <<= 2; +num <<= 1n; +num <<= 2; +bigInt >>= 1n; +bigInt >>= 2; +num >>= 1n; +num >>= 2; +bigInt &= 1n; +bigInt &= 2; +num &= 1n; +num &= 2; +bigInt ^= 1n; +bigInt ^= 2; +num ^= 1n; +num ^= 2; +bigInt |= 1n; +bigInt |= 2; +num |= 1n; +num |= 2; +bigInt = 1n + 2n; +num = 1 + 2; +1 + 2n; +1n + 2; +bigInt = 1n - 2n; +num = 1 - 2; +1 - 2n; +1n - 2; +bigInt = 1n * 2n; +num = 1 * 2; +1 * 2n; +1n * 2; +bigInt = 1n / 2n; +num = 1 / 2; +1 / 2n; +1n / 2; +bigInt = 1n % 2n; +num = 1 % 2; +1 % 2n; +1n % 2; +bigInt = Math.pow(1n, 2n); +num = Math.pow(1, 2); +Math.pow(1, 2n); +Math.pow(1n, 2); +bigInt = 1n & 2n; +num = 1 & 2; +1 & 2n; +1n & 2; +bigInt = 1n | 2n; +num = 1 | 2; +1 | 2n; +1n | 2; +bigInt = 1n ^ 2n; +num = 1 ^ 2; +1 ^ 2n; +1n ^ 2; +bigInt = 1n << 2n; +num = 1 << 2; +1 << 2n; +1n << 2; +bigInt = 1n >> 2n; +num = 1 >> 2; +1 >> 2n; +1n >> 2; +// Plus should still coerce to strings +var str; +str = "abc" + 123; +str = "abc" + 123n; +str = 123 + "abc"; +str = 123n + "abc"; +// Unary operations allowed on bigints and numbers +bigInt = bigInt++; +bigInt = ++bigInt; +num = num++; +num = ++num; +bigInt = bigInt--; +bigInt = --bigInt; +num = num--; +num = --num; +bigInt = -bigInt; +num = -num; +bigInt = ~bigInt; +num = ~num; +// Number-only operations +bigInt >>>= 1n; +num >>>= 2; +bigInt = bigInt >>> 1n; +num = num >>> 2; +num = +bigInt; +num = +num; +num = +"3"; +// Comparisons can be mixed +var result; +result = bigInt > num; +result = bigInt >= num; +result = bigInt < num; +result = bigInt <= num; +// Trying to compare for equality is likely an error (since 1 == "1" is disallowed) +result = bigInt == num; +result = bigInt != num; +result = bigInt === num; +result = bigInt !== num; +// Types of arithmetic operations on other types +num = "3" & 5; +num = Math.pow(2, false); // should error, but infer number +"3" & 5n; +Math.pow(2n, false); // should error, result in any +num = ~"3"; +num = -false; // should infer number +var bigIntOrNumber; +bigIntOrNumber + bigIntOrNumber; // should error, result in any +bigIntOrNumber << bigIntOrNumber; // should error, result in any +if (typeof bigIntOrNumber === "bigint") { + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} +if (typeof bigIntOrNumber === "number") { + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} ++bigIntOrNumber; // should error, result in number +~bigIntOrNumber; // should infer number | bigint +bigIntOrNumber++; // should infer number | bigint +++bigIntOrNumber; // should infer number | bigint +var anyValue; +anyValue + anyValue; // should infer any +anyValue >>> anyValue; // should infer number +anyValue ^ anyValue; // should infer number ++anyValue; // should infer number +-anyValue; // should infer number +anyValue--; // should infer number +--anyValue; // should infer number +// Distinguishing numbers from bigints with typeof +var isBigInt = function (x) { return x; }; +var isNumber = function (x) { return x; }; +var zeroOrBigOne; +if (typeof zeroOrBigOne === "bigint") + isBigInt(zeroOrBigOne); +else + isNumber(zeroOrBigOne); +// Distinguishing truthy from falsy +var isOne = function (x) { return x; }; +if (zeroOrBigOne) + isOne(zeroOrBigOne); +var bigZeroOrOne; +if (bigZeroOrOne) + isOne(bigZeroOrOne); diff --git a/tests/baselines/reference/numberVsBigIntOperations.symbols b/tests/baselines/reference/numberVsBigIntOperations.symbols new file mode 100644 index 00000000000..1b164afb1de --- /dev/null +++ b/tests/baselines/reference/numberVsBigIntOperations.symbols @@ -0,0 +1,350 @@ +=== tests/cases/compiler/numberVsBigIntOperations.ts === +// Cannot mix bigints and numbers +let bigInt = 1n, num = 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n; bigInt = 2; num = 1n; num = 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt += 1n; bigInt += 2; num += 1n; num += 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt -= 1n; bigInt -= 2; num -= 1n; num -= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt *= 1n; bigInt *= 2; num *= 1n; num *= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt /= 1n; bigInt /= 2; num /= 1n; num /= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt **= 1n; bigInt **= 2; num **= 1n; num **= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt <<= 1n; bigInt <<= 2; num <<= 1n; num <<= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt >>= 1n; bigInt >>= 2; num >>= 1n; num >>= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt &= 1n; bigInt &= 2; num &= 1n; num &= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt ^= 1n; bigInt ^= 2; num ^= 1n; num ^= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt |= 1n; bigInt |= 2; num |= 1n; num |= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n + 2n; num = 1 + 2; 1 + 2n; 1n + 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n - 2n; num = 1 - 2; 1 - 2n; 1n - 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n * 2n; num = 1 * 2; 1 * 2n; 1n * 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n / 2n; num = 1 / 2; 1 / 2n; 1n / 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n ** 2n; num = 1 ** 2; 1 ** 2n; 1n ** 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; 1n & 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n | 2n; num = 1 | 2; 1 | 2n; 1n | 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n ^ 2n; num = 1 ^ 2; 1 ^ 2n; 1n ^ 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n << 2n; num = 1 << 2; 1 << 2n; 1n << 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = 1n >> 2n; num = 1 >> 2; 1 >> 2n; 1n >> 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +// Plus should still coerce to strings +let str: string; +>str : Symbol(str, Decl(numberVsBigIntOperations.ts, 27, 3)) + +str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; str = 123n + "abc"; +>str : Symbol(str, Decl(numberVsBigIntOperations.ts, 27, 3)) +>str : Symbol(str, Decl(numberVsBigIntOperations.ts, 27, 3)) +>str : Symbol(str, Decl(numberVsBigIntOperations.ts, 27, 3)) +>str : Symbol(str, Decl(numberVsBigIntOperations.ts, 27, 3)) + +// Unary operations allowed on bigints and numbers +bigInt = bigInt++; bigInt = ++bigInt; num = num++; num = ++num; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = bigInt--; bigInt = --bigInt; num = num--; num = --num; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = -bigInt; num = -num; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = ~bigInt; num = ~num; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +// Number-only operations +bigInt >>>= 1n; num >>>= 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +bigInt = bigInt >>> 1n; num = num >>> 2; +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +num = +bigInt; num = +num; num = +"3"; +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +// Comparisons can be mixed +let result: boolean; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) + +result = bigInt > num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt >= num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt < num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt <= num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +// Trying to compare for equality is likely an error (since 1 == "1" is disallowed) +result = bigInt == num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt != num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt === num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +result = bigInt !== num; +>result : Symbol(result, Decl(numberVsBigIntOperations.ts, 42, 3)) +>bigInt : Symbol(bigInt, Decl(numberVsBigIntOperations.ts, 1, 3)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +// Types of arithmetic operations on other types +num = "3" & 5; num = 2 ** false; // should error, but infer number +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +"3" & 5n; 2n ** false; // should error, result in any +num = ~"3"; num = -false; // should infer number +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) +>num : Symbol(num, Decl(numberVsBigIntOperations.ts, 1, 16)) + +let bigIntOrNumber: bigint | number; +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +bigIntOrNumber + bigIntOrNumber; // should error, result in any +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +bigIntOrNumber << bigIntOrNumber; // should error, result in any +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +if (typeof bigIntOrNumber === "bigint") { +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +} +if (typeof bigIntOrNumber === "number") { +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) +} ++bigIntOrNumber; // should error, result in number +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +~bigIntOrNumber; // should infer number | bigint +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +bigIntOrNumber++; // should infer number | bigint +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +++bigIntOrNumber; // should infer number | bigint +>bigIntOrNumber : Symbol(bigIntOrNumber, Decl(numberVsBigIntOperations.ts, 58, 3)) + +let anyValue: any; +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +anyValue + anyValue; // should infer any +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +anyValue >>> anyValue; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +anyValue ^ anyValue; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + ++anyValue; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +-anyValue; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +anyValue--; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +--anyValue; // should infer number +>anyValue : Symbol(anyValue, Decl(numberVsBigIntOperations.ts, 73, 3)) + +// Distinguishing numbers from bigints with typeof +const isBigInt: (x: 0n | 1n) => bigint = (x: 0n | 1n) => x; +>isBigInt : Symbol(isBigInt, Decl(numberVsBigIntOperations.ts, 83, 5)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 83, 17)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 83, 42)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 83, 42)) + +const isNumber: (x: 0 | 1) => number = (x: 0 | 1) => x; +>isNumber : Symbol(isNumber, Decl(numberVsBigIntOperations.ts, 84, 5)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 84, 17)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 84, 40)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 84, 40)) + +const zeroOrBigOne: 0 | 1n; +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) + +if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) +>isBigInt : Symbol(isBigInt, Decl(numberVsBigIntOperations.ts, 83, 5)) +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) + +else isNumber(zeroOrBigOne); +>isNumber : Symbol(isNumber, Decl(numberVsBigIntOperations.ts, 84, 5)) +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) + +// Distinguishing truthy from falsy +const isOne = (x: 1 | 1n) => x; +>isOne : Symbol(isOne, Decl(numberVsBigIntOperations.ts, 90, 5)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 90, 15)) +>x : Symbol(x, Decl(numberVsBigIntOperations.ts, 90, 15)) + +if (zeroOrBigOne) isOne(zeroOrBigOne); +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) +>isOne : Symbol(isOne, Decl(numberVsBigIntOperations.ts, 90, 5)) +>zeroOrBigOne : Symbol(zeroOrBigOne, Decl(numberVsBigIntOperations.ts, 85, 5)) + +const bigZeroOrOne: 0n | 1; +>bigZeroOrOne : Symbol(bigZeroOrOne, Decl(numberVsBigIntOperations.ts, 92, 5)) + +if (bigZeroOrOne) isOne(bigZeroOrOne); +>bigZeroOrOne : Symbol(bigZeroOrOne, Decl(numberVsBigIntOperations.ts, 92, 5)) +>isOne : Symbol(isOne, Decl(numberVsBigIntOperations.ts, 90, 5)) +>bigZeroOrOne : Symbol(bigZeroOrOne, Decl(numberVsBigIntOperations.ts, 92, 5)) + diff --git a/tests/baselines/reference/numberVsBigIntOperations.types b/tests/baselines/reference/numberVsBigIntOperations.types new file mode 100644 index 00000000000..14ab151a437 --- /dev/null +++ b/tests/baselines/reference/numberVsBigIntOperations.types @@ -0,0 +1,729 @@ +=== tests/cases/compiler/numberVsBigIntOperations.ts === +// Cannot mix bigints and numbers +let bigInt = 1n, num = 2; +>bigInt : bigint +>1n : 1n +>num : number +>2 : 2 + +bigInt = 1n; bigInt = 2; num = 1n; num = 2; +>bigInt = 1n : 1n +>bigInt : bigint +>1n : 1n +>bigInt = 2 : 2 +>bigInt : bigint +>2 : 2 +>num = 1n : 1n +>num : number +>1n : 1n +>num = 2 : 2 +>num : number +>2 : 2 + +bigInt += 1n; bigInt += 2; num += 1n; num += 2; +>bigInt += 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt += 2 : any +>bigInt : bigint +>2 : 2 +>num += 1n : any +>num : number +>1n : 1n +>num += 2 : number +>num : number +>2 : 2 + +bigInt -= 1n; bigInt -= 2; num -= 1n; num -= 2; +>bigInt -= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt -= 2 : any +>bigInt : bigint +>2 : 2 +>num -= 1n : any +>num : number +>1n : 1n +>num -= 2 : number +>num : number +>2 : 2 + +bigInt *= 1n; bigInt *= 2; num *= 1n; num *= 2; +>bigInt *= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt *= 2 : any +>bigInt : bigint +>2 : 2 +>num *= 1n : any +>num : number +>1n : 1n +>num *= 2 : number +>num : number +>2 : 2 + +bigInt /= 1n; bigInt /= 2; num /= 1n; num /= 2; +>bigInt /= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt /= 2 : any +>bigInt : bigint +>2 : 2 +>num /= 1n : any +>num : number +>1n : 1n +>num /= 2 : number +>num : number +>2 : 2 + +bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; +>bigInt %= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt %= 2 : any +>bigInt : bigint +>2 : 2 +>num %= 1n : any +>num : number +>1n : 1n +>num %= 2 : number +>num : number +>2 : 2 + +bigInt **= 1n; bigInt **= 2; num **= 1n; num **= 2; +>bigInt **= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt **= 2 : any +>bigInt : bigint +>2 : 2 +>num **= 1n : any +>num : number +>1n : 1n +>num **= 2 : number +>num : number +>2 : 2 + +bigInt <<= 1n; bigInt <<= 2; num <<= 1n; num <<= 2; +>bigInt <<= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt <<= 2 : any +>bigInt : bigint +>2 : 2 +>num <<= 1n : any +>num : number +>1n : 1n +>num <<= 2 : number +>num : number +>2 : 2 + +bigInt >>= 1n; bigInt >>= 2; num >>= 1n; num >>= 2; +>bigInt >>= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt >>= 2 : any +>bigInt : bigint +>2 : 2 +>num >>= 1n : any +>num : number +>1n : 1n +>num >>= 2 : number +>num : number +>2 : 2 + +bigInt &= 1n; bigInt &= 2; num &= 1n; num &= 2; +>bigInt &= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt &= 2 : any +>bigInt : bigint +>2 : 2 +>num &= 1n : any +>num : number +>1n : 1n +>num &= 2 : number +>num : number +>2 : 2 + +bigInt ^= 1n; bigInt ^= 2; num ^= 1n; num ^= 2; +>bigInt ^= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt ^= 2 : any +>bigInt : bigint +>2 : 2 +>num ^= 1n : any +>num : number +>1n : 1n +>num ^= 2 : number +>num : number +>2 : 2 + +bigInt |= 1n; bigInt |= 2; num |= 1n; num |= 2; +>bigInt |= 1n : bigint +>bigInt : bigint +>1n : 1n +>bigInt |= 2 : any +>bigInt : bigint +>2 : 2 +>num |= 1n : any +>num : number +>1n : 1n +>num |= 2 : number +>num : number +>2 : 2 + +bigInt = 1n + 2n; num = 1 + 2; 1 + 2n; 1n + 2; +>bigInt = 1n + 2n : bigint +>bigInt : bigint +>1n + 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 + 2 : number +>num : number +>1 + 2 : number +>1 : 1 +>2 : 2 +>1 + 2n : any +>1 : 1 +>2n : 2n +>1n + 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n - 2n; num = 1 - 2; 1 - 2n; 1n - 2; +>bigInt = 1n - 2n : bigint +>bigInt : bigint +>1n - 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 - 2 : number +>num : number +>1 - 2 : number +>1 : 1 +>2 : 2 +>1 - 2n : any +>1 : 1 +>2n : 2n +>1n - 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n * 2n; num = 1 * 2; 1 * 2n; 1n * 2; +>bigInt = 1n * 2n : bigint +>bigInt : bigint +>1n * 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 * 2 : number +>num : number +>1 * 2 : number +>1 : 1 +>2 : 2 +>1 * 2n : any +>1 : 1 +>2n : 2n +>1n * 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n / 2n; num = 1 / 2; 1 / 2n; 1n / 2; +>bigInt = 1n / 2n : bigint +>bigInt : bigint +>1n / 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 / 2 : number +>num : number +>1 / 2 : number +>1 : 1 +>2 : 2 +>1 / 2n : any +>1 : 1 +>2n : 2n +>1n / 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; +>bigInt = 1n % 2n : bigint +>bigInt : bigint +>1n % 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 % 2 : number +>num : number +>1 % 2 : number +>1 : 1 +>2 : 2 +>1 % 2n : any +>1 : 1 +>2n : 2n +>1n % 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n ** 2n; num = 1 ** 2; 1 ** 2n; 1n ** 2; +>bigInt = 1n ** 2n : bigint +>bigInt : bigint +>1n ** 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 ** 2 : number +>num : number +>1 ** 2 : number +>1 : 1 +>2 : 2 +>1 ** 2n : any +>1 : 1 +>2n : 2n +>1n ** 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; 1n & 2; +>bigInt = 1n & 2n : bigint +>bigInt : bigint +>1n & 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 & 2 : number +>num : number +>1 & 2 : number +>1 : 1 +>2 : 2 +>1 & 2n : any +>1 : 1 +>2n : 2n +>1n & 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n | 2n; num = 1 | 2; 1 | 2n; 1n | 2; +>bigInt = 1n | 2n : bigint +>bigInt : bigint +>1n | 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 | 2 : number +>num : number +>1 | 2 : number +>1 : 1 +>2 : 2 +>1 | 2n : any +>1 : 1 +>2n : 2n +>1n | 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n ^ 2n; num = 1 ^ 2; 1 ^ 2n; 1n ^ 2; +>bigInt = 1n ^ 2n : bigint +>bigInt : bigint +>1n ^ 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 ^ 2 : number +>num : number +>1 ^ 2 : number +>1 : 1 +>2 : 2 +>1 ^ 2n : any +>1 : 1 +>2n : 2n +>1n ^ 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n << 2n; num = 1 << 2; 1 << 2n; 1n << 2; +>bigInt = 1n << 2n : bigint +>bigInt : bigint +>1n << 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 << 2 : number +>num : number +>1 << 2 : number +>1 : 1 +>2 : 2 +>1 << 2n : any +>1 : 1 +>2n : 2n +>1n << 2 : any +>1n : 1n +>2 : 2 + +bigInt = 1n >> 2n; num = 1 >> 2; 1 >> 2n; 1n >> 2; +>bigInt = 1n >> 2n : bigint +>bigInt : bigint +>1n >> 2n : bigint +>1n : 1n +>2n : 2n +>num = 1 >> 2 : number +>num : number +>1 >> 2 : number +>1 : 1 +>2 : 2 +>1 >> 2n : any +>1 : 1 +>2n : 2n +>1n >> 2 : any +>1n : 1n +>2 : 2 + +// Plus should still coerce to strings +let str: string; +>str : string + +str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; str = 123n + "abc"; +>str = "abc" + 123 : string +>str : string +>"abc" + 123 : string +>"abc" : "abc" +>123 : 123 +>str = "abc" + 123n : string +>str : string +>"abc" + 123n : string +>"abc" : "abc" +>123n : 123n +>str = 123 + "abc" : string +>str : string +>123 + "abc" : string +>123 : 123 +>"abc" : "abc" +>str = 123n + "abc" : string +>str : string +>123n + "abc" : string +>123n : 123n +>"abc" : "abc" + +// Unary operations allowed on bigints and numbers +bigInt = bigInt++; bigInt = ++bigInt; num = num++; num = ++num; +>bigInt = bigInt++ : bigint +>bigInt : bigint +>bigInt++ : bigint +>bigInt : bigint +>bigInt = ++bigInt : bigint +>bigInt : bigint +>++bigInt : bigint +>bigInt : bigint +>num = num++ : number +>num : number +>num++ : number +>num : number +>num = ++num : number +>num : number +>++num : number +>num : number + +bigInt = bigInt--; bigInt = --bigInt; num = num--; num = --num; +>bigInt = bigInt-- : bigint +>bigInt : bigint +>bigInt-- : bigint +>bigInt : bigint +>bigInt = --bigInt : bigint +>bigInt : bigint +>--bigInt : bigint +>bigInt : bigint +>num = num-- : number +>num : number +>num-- : number +>num : number +>num = --num : number +>num : number +>--num : number +>num : number + +bigInt = -bigInt; num = -num; +>bigInt = -bigInt : bigint +>bigInt : bigint +>-bigInt : bigint +>bigInt : bigint +>num = -num : number +>num : number +>-num : number +>num : number + +bigInt = ~bigInt; num = ~num; +>bigInt = ~bigInt : bigint +>bigInt : bigint +>~bigInt : bigint +>bigInt : bigint +>num = ~num : number +>num : number +>~num : number +>num : number + +// Number-only operations +bigInt >>>= 1n; num >>>= 2; +>bigInt >>>= 1n : bigint +>bigInt : bigint +>1n : 1n +>num >>>= 2 : number +>num : number +>2 : 2 + +bigInt = bigInt >>> 1n; num = num >>> 2; +>bigInt = bigInt >>> 1n : bigint +>bigInt : bigint +>bigInt >>> 1n : bigint +>bigInt : bigint +>1n : 1n +>num = num >>> 2 : number +>num : number +>num >>> 2 : number +>num : number +>2 : 2 + +num = +bigInt; num = +num; num = +"3"; +>num = +bigInt : number +>num : number +>+bigInt : number +>bigInt : bigint +>num = +num : number +>num : number +>+num : number +>num : number +>num = +"3" : number +>num : number +>+"3" : number +>"3" : "3" + +// Comparisons can be mixed +let result: boolean; +>result : boolean + +result = bigInt > num; +>result = bigInt > num : boolean +>result : boolean +>bigInt > num : boolean +>bigInt : bigint +>num : number + +result = bigInt >= num; +>result = bigInt >= num : boolean +>result : boolean +>bigInt >= num : boolean +>bigInt : bigint +>num : number + +result = bigInt < num; +>result = bigInt < num : boolean +>result : boolean +>bigInt < num : boolean +>bigInt : bigint +>num : number + +result = bigInt <= num; +>result = bigInt <= num : boolean +>result : boolean +>bigInt <= num : boolean +>bigInt : bigint +>num : number + +// Trying to compare for equality is likely an error (since 1 == "1" is disallowed) +result = bigInt == num; +>result = bigInt == num : boolean +>result : boolean +>bigInt == num : boolean +>bigInt : bigint +>num : number + +result = bigInt != num; +>result = bigInt != num : boolean +>result : boolean +>bigInt != num : boolean +>bigInt : bigint +>num : number + +result = bigInt === num; +>result = bigInt === num : boolean +>result : boolean +>bigInt === num : boolean +>bigInt : bigint +>num : number + +result = bigInt !== num; +>result = bigInt !== num : boolean +>result : boolean +>bigInt !== num : boolean +>bigInt : bigint +>num : number + +// Types of arithmetic operations on other types +num = "3" & 5; num = 2 ** false; // should error, but infer number +>num = "3" & 5 : number +>num : number +>"3" & 5 : number +>"3" : "3" +>5 : 5 +>num = 2 ** false : number +>num : number +>2 ** false : number +>2 : 2 +>false : false + +"3" & 5n; 2n ** false; // should error, result in any +>"3" & 5n : any +>"3" : "3" +>5n : 5n +>2n ** false : any +>2n : 2n +>false : false + +num = ~"3"; num = -false; // should infer number +>num = ~"3" : number +>num : number +>~"3" : number +>"3" : "3" +>num = -false : number +>num : number +>-false : number +>false : false + +let bigIntOrNumber: bigint | number; +>bigIntOrNumber : number | bigint + +bigIntOrNumber + bigIntOrNumber; // should error, result in any +>bigIntOrNumber + bigIntOrNumber : any +>bigIntOrNumber : number | bigint +>bigIntOrNumber : number | bigint + +bigIntOrNumber << bigIntOrNumber; // should error, result in any +>bigIntOrNumber << bigIntOrNumber : any +>bigIntOrNumber : number | bigint +>bigIntOrNumber : number | bigint + +if (typeof bigIntOrNumber === "bigint") { +>typeof bigIntOrNumber === "bigint" : boolean +>typeof bigIntOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>bigIntOrNumber : number | bigint +>"bigint" : "bigint" + + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +>bigIntOrNumber = bigIntOrNumber << bigIntOrNumber : bigint +>bigIntOrNumber : number | bigint +>bigIntOrNumber << bigIntOrNumber : bigint +>bigIntOrNumber : bigint +>bigIntOrNumber : bigint +} +if (typeof bigIntOrNumber === "number") { +>typeof bigIntOrNumber === "number" : boolean +>typeof bigIntOrNumber : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>bigIntOrNumber : number | bigint +>"number" : "number" + + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +>bigIntOrNumber = bigIntOrNumber << bigIntOrNumber : number +>bigIntOrNumber : number | bigint +>bigIntOrNumber << bigIntOrNumber : number +>bigIntOrNumber : number +>bigIntOrNumber : number +} ++bigIntOrNumber; // should error, result in number +>+bigIntOrNumber : number +>bigIntOrNumber : number | bigint + +~bigIntOrNumber; // should infer number | bigint +>~bigIntOrNumber : number | bigint +>bigIntOrNumber : number | bigint + +bigIntOrNumber++; // should infer number | bigint +>bigIntOrNumber++ : number | bigint +>bigIntOrNumber : number | bigint + +++bigIntOrNumber; // should infer number | bigint +>++bigIntOrNumber : number | bigint +>bigIntOrNumber : number | bigint + +let anyValue: any; +>anyValue : any + +anyValue + anyValue; // should infer any +>anyValue + anyValue : any +>anyValue : any +>anyValue : any + +anyValue >>> anyValue; // should infer number +>anyValue >>> anyValue : number +>anyValue : any +>anyValue : any + +anyValue ^ anyValue; // should infer number +>anyValue ^ anyValue : number +>anyValue : any +>anyValue : any + ++anyValue; // should infer number +>+anyValue : number +>anyValue : any + +-anyValue; // should infer number +>-anyValue : number +>anyValue : any + +anyValue--; // should infer number +>anyValue-- : number +>anyValue : any + +--anyValue; // should infer number +>--anyValue : number +>anyValue : any + +// Distinguishing numbers from bigints with typeof +const isBigInt: (x: 0n | 1n) => bigint = (x: 0n | 1n) => x; +>isBigInt : (x: 0n | 1n) => bigint +>x : 0n | 1n +>(x: 0n | 1n) => x : (x: 0n | 1n) => 0n | 1n +>x : 0n | 1n +>x : 0n | 1n + +const isNumber: (x: 0 | 1) => number = (x: 0 | 1) => x; +>isNumber : (x: 0 | 1) => number +>x : 0 | 1 +>(x: 0 | 1) => x : (x: 0 | 1) => 0 | 1 +>x : 0 | 1 +>x : 0 | 1 + +const zeroOrBigOne: 0 | 1n; +>zeroOrBigOne : 0 | 1n + +if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); +>typeof zeroOrBigOne === "bigint" : boolean +>typeof zeroOrBigOne : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>zeroOrBigOne : 0 | 1n +>"bigint" : "bigint" +>isBigInt(zeroOrBigOne) : bigint +>isBigInt : (x: 0n | 1n) => bigint +>zeroOrBigOne : 1n + +else isNumber(zeroOrBigOne); +>isNumber(zeroOrBigOne) : number +>isNumber : (x: 0 | 1) => number +>zeroOrBigOne : 0 + +// Distinguishing truthy from falsy +const isOne = (x: 1 | 1n) => x; +>isOne : (x: 1n | 1) => 1n | 1 +>(x: 1 | 1n) => x : (x: 1n | 1) => 1n | 1 +>x : 1n | 1 +>x : 1n | 1 + +if (zeroOrBigOne) isOne(zeroOrBigOne); +>zeroOrBigOne : 0 | 1n +>isOne(zeroOrBigOne) : 1n | 1 +>isOne : (x: 1n | 1) => 1n | 1 +>zeroOrBigOne : 1n + +const bigZeroOrOne: 0n | 1; +>bigZeroOrOne : 0n | 1 + +if (bigZeroOrOne) isOne(bigZeroOrOne); +>bigZeroOrOne : 0n | 1 +>isOne(bigZeroOrOne) : 1n | 1 +>isOne : (x: 1n | 1) => 1n | 1 +>bigZeroOrOne : 1 + diff --git a/tests/baselines/reference/parseBigInt.errors.txt b/tests/baselines/reference/parseBigInt.errors.txt new file mode 100644 index 00000000000..ea4ca01f5e1 --- /dev/null +++ b/tests/baselines/reference/parseBigInt.errors.txt @@ -0,0 +1,124 @@ +tests/cases/compiler/parseBigInt.ts(51,20): error TS2735: Operator '+' cannot be applied to type '123n'. +tests/cases/compiler/parseBigInt.ts(52,23): error TS2735: Operator '+' cannot be applied to type '291n'. +tests/cases/compiler/parseBigInt.ts(56,25): error TS1005: ',' expected. +tests/cases/compiler/parseBigInt.ts(57,25): error TS1005: ',' expected. +tests/cases/compiler/parseBigInt.ts(58,22): error TS1005: ',' expected. +tests/cases/compiler/parseBigInt.ts(59,28): error TS1005: ',' expected. +tests/cases/compiler/parseBigInt.ts(60,23): error TS1177: Binary digit expected. +tests/cases/compiler/parseBigInt.ts(61,20): error TS1178: Octal digit expected. +tests/cases/compiler/parseBigInt.ts(62,20): error TS1125: Hexadecimal digit expected. +tests/cases/compiler/parseBigInt.ts(63,26): error TS2304: Cannot find name '_123n'. +tests/cases/compiler/parseBigInt.ts(64,30): error TS6188: Numeric separators are not allowed here. +tests/cases/compiler/parseBigInt.ts(65,33): error TS6189: Multiple consecutive numeric separators are not permitted. +tests/cases/compiler/parseBigInt.ts(69,15): error TS2345: Argument of type '0n' is not assignable to parameter of type '1n | 3n | 2n'. +tests/cases/compiler/parseBigInt.ts(70,15): error TS2345: Argument of type '0' is not assignable to parameter of type '1n | 3n | 2n'. +tests/cases/compiler/parseBigInt.ts(70,34): error TS2345: Argument of type '1' is not assignable to parameter of type '1n | 3n | 2n'. +tests/cases/compiler/parseBigInt.ts(70,53): error TS2345: Argument of type '2' is not assignable to parameter of type '1n | 3n | 2n'. +tests/cases/compiler/parseBigInt.ts(70,72): error TS2345: Argument of type '3' is not assignable to parameter of type '1n | 3n | 2n'. + + +==== tests/cases/compiler/parseBigInt.ts (17 errors) ==== + // All bases should allow "n" suffix + const bin = 0b101, binBig = 0b101n; // 5, 5n + const oct = 0o567, octBig = 0o567n; // 375, 375n + const hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n + const dec = 123, decBig = 123n; + + // Test literals whose values overflow a 53-bit integer + // These should be represented exactly in the emitted JS + const largeBin = 0b10101010101010101010101010101010101010101010101010101010101n; // 384307168202282325n + const largeOct = 0o123456712345671234567n; // 1505852261029722487n + const largeDec = 12345678091234567890n; + const largeHex = 0x1234567890abcdefn; // 1311768467294899695n + + // Test literals with separators + const separatedBin = 0b010_10_1n; // 21n + const separatedOct = 0o1234_567n; // 342391n + const separatedDec = 123_456_789n; + const separatedHex = 0x0_abcdefn; // 11259375n + + // Test parsing literals of different bit sizes + // to ensure that parsePseudoBigInt() allocates enough space + const zero = 0b0n; + const oneBit = 0b1n; + const twoBit = 0b11n; // 3n + const threeBit = 0b111n; // 7n + const fourBit = 0b1111n; // 15n + const fiveBit = 0b11111n; // 31n + const sixBit = 0b111111n; // 63n + const sevenBit = 0b1111111n; // 127n + const eightBit = 0b11111111n; // 255n + const nineBit = 0b111111111n; // 511n + const tenBit = 0b1111111111n; // 1023n + const elevenBit = 0b11111111111n; // 2047n + const twelveBit = 0b111111111111n; // 4095n + const thirteenBit = 0b1111111111111n; // 8191n + const fourteenBit = 0b11111111111111n; // 16383n + const fifteenBit = 0b111111111111111n; // 32767n + const sixteenBit = 0b1111111111111111n; // 65535n + const seventeenBit = 0b11111111111111111n; // 131071n + + // Test negative literals + const neg = -123n; + const negHex: -16n = -0x10n; + + // Test normalization of bigints -- all of these should succeed + const negZero: 0n = -0n; + const baseChange: 255n = 0xFFn; + const leadingZeros: 0xFFn = 0x000000FFn; + + // Plus not allowed on literals + const unaryPlus = +123n; + ~~~~ +!!! error TS2735: Operator '+' cannot be applied to type '123n'. + const unaryPlusHex = +0x123n; + ~~~~~~ +!!! error TS2735: Operator '+' cannot be applied to type '291n'. + + // Parsing errors + // In separate blocks because they each declare an "n" variable + { const legacyOct = 0123n; } + ~ +!!! error TS1005: ',' expected. + { const scientific = 1e2n; } + ~ +!!! error TS1005: ',' expected. + { const decimal = 4.1n; } + ~ +!!! error TS1005: ',' expected. + { const leadingDecimal = .1n; } + ~ +!!! error TS1005: ',' expected. + const emptyBinary = 0bn; // should error but infer 0n + +!!! error TS1177: Binary digit expected. + const emptyOct = 0on; // should error but infer 0n + +!!! error TS1178: Octal digit expected. + const emptyHex = 0xn; // should error but infer 0n + +!!! error TS1125: Hexadecimal digit expected. + const leadingSeparator = _123n; + ~~~~~ +!!! error TS2304: Cannot find name '_123n'. + const trailingSeparator = 123_n; + ~ +!!! error TS6188: Numeric separators are not allowed here. + const doubleSeparator = 123_456__789n; + ~ +!!! error TS6189: Multiple consecutive numeric separators are not permitted. + + // Using literals as types + const oneTwoOrThree = (x: 1n | 2n | 3n): bigint => x ** 2n; + oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); oneTwoOrThree(3n); + ~~ +!!! error TS2345: Argument of type '0n' is not assignable to parameter of type '1n | 3n | 2n'. + oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); + ~ +!!! error TS2345: Argument of type '0' is not assignable to parameter of type '1n | 3n | 2n'. + ~ +!!! error TS2345: Argument of type '1' is not assignable to parameter of type '1n | 3n | 2n'. + ~ +!!! error TS2345: Argument of type '2' is not assignable to parameter of type '1n | 3n | 2n'. + ~ +!!! error TS2345: Argument of type '3' is not assignable to parameter of type '1n | 3n | 2n'. \ No newline at end of file diff --git a/tests/baselines/reference/parseBigInt.js b/tests/baselines/reference/parseBigInt.js new file mode 100644 index 00000000000..ccfa3089f0f --- /dev/null +++ b/tests/baselines/reference/parseBigInt.js @@ -0,0 +1,149 @@ +//// [parseBigInt.ts] +// All bases should allow "n" suffix +const bin = 0b101, binBig = 0b101n; // 5, 5n +const oct = 0o567, octBig = 0o567n; // 375, 375n +const hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n +const dec = 123, decBig = 123n; + +// Test literals whose values overflow a 53-bit integer +// These should be represented exactly in the emitted JS +const largeBin = 0b10101010101010101010101010101010101010101010101010101010101n; // 384307168202282325n +const largeOct = 0o123456712345671234567n; // 1505852261029722487n +const largeDec = 12345678091234567890n; +const largeHex = 0x1234567890abcdefn; // 1311768467294899695n + +// Test literals with separators +const separatedBin = 0b010_10_1n; // 21n +const separatedOct = 0o1234_567n; // 342391n +const separatedDec = 123_456_789n; +const separatedHex = 0x0_abcdefn; // 11259375n + +// Test parsing literals of different bit sizes +// to ensure that parsePseudoBigInt() allocates enough space +const zero = 0b0n; +const oneBit = 0b1n; +const twoBit = 0b11n; // 3n +const threeBit = 0b111n; // 7n +const fourBit = 0b1111n; // 15n +const fiveBit = 0b11111n; // 31n +const sixBit = 0b111111n; // 63n +const sevenBit = 0b1111111n; // 127n +const eightBit = 0b11111111n; // 255n +const nineBit = 0b111111111n; // 511n +const tenBit = 0b1111111111n; // 1023n +const elevenBit = 0b11111111111n; // 2047n +const twelveBit = 0b111111111111n; // 4095n +const thirteenBit = 0b1111111111111n; // 8191n +const fourteenBit = 0b11111111111111n; // 16383n +const fifteenBit = 0b111111111111111n; // 32767n +const sixteenBit = 0b1111111111111111n; // 65535n +const seventeenBit = 0b11111111111111111n; // 131071n + +// Test negative literals +const neg = -123n; +const negHex: -16n = -0x10n; + +// Test normalization of bigints -- all of these should succeed +const negZero: 0n = -0n; +const baseChange: 255n = 0xFFn; +const leadingZeros: 0xFFn = 0x000000FFn; + +// Plus not allowed on literals +const unaryPlus = +123n; +const unaryPlusHex = +0x123n; + +// Parsing errors +// In separate blocks because they each declare an "n" variable +{ const legacyOct = 0123n; } +{ const scientific = 1e2n; } +{ const decimal = 4.1n; } +{ const leadingDecimal = .1n; } +const emptyBinary = 0bn; // should error but infer 0n +const emptyOct = 0on; // should error but infer 0n +const emptyHex = 0xn; // should error but infer 0n +const leadingSeparator = _123n; +const trailingSeparator = 123_n; +const doubleSeparator = 123_456__789n; + +// Using literals as types +const oneTwoOrThree = (x: 1n | 2n | 3n): bigint => x ** 2n; +oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); oneTwoOrThree(3n); +oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); + +//// [parseBigInt.js] +// All bases should allow "n" suffix +var bin = 5, binBig = 5n; // 5, 5n +var oct = 375, octBig = 375n; // 375, 375n +var hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n +var dec = 123, decBig = 123n; +// Test literals whose values overflow a 53-bit integer +// These should be represented exactly in the emitted JS +var largeBin = 384307168202282325n; // 384307168202282325n +var largeOct = 1505852261029722487n; // 1505852261029722487n +var largeDec = 12345678091234567890n; +var largeHex = 0x1234567890abcdefn; // 1311768467294899695n +// Test literals with separators +var separatedBin = 21n; // 21n +var separatedOct = 342391n; // 342391n +var separatedDec = 123456789n; +var separatedHex = 0x0abcdefn; // 11259375n +// Test parsing literals of different bit sizes +// to ensure that parsePseudoBigInt() allocates enough space +var zero = 0n; +var oneBit = 1n; +var twoBit = 3n; // 3n +var threeBit = 7n; // 7n +var fourBit = 15n; // 15n +var fiveBit = 31n; // 31n +var sixBit = 63n; // 63n +var sevenBit = 127n; // 127n +var eightBit = 255n; // 255n +var nineBit = 511n; // 511n +var tenBit = 1023n; // 1023n +var elevenBit = 2047n; // 2047n +var twelveBit = 4095n; // 4095n +var thirteenBit = 8191n; // 8191n +var fourteenBit = 16383n; // 16383n +var fifteenBit = 32767n; // 32767n +var sixteenBit = 65535n; // 65535n +var seventeenBit = 131071n; // 131071n +// Test negative literals +var neg = -123n; +var negHex = -0x10n; +// Test normalization of bigints -- all of these should succeed +var negZero = -0n; +var baseChange = 0xFFn; +var leadingZeros = 0x000000FFn; +// Plus not allowed on literals +var unaryPlus = +123n; +var unaryPlusHex = +0x123n; +// Parsing errors +// In separate blocks because they each declare an "n" variable +{ + var legacyOct = 0123, n; +} +{ + var scientific = 1e2, n; +} +{ + var decimal = 4.1, n; +} +{ + var leadingDecimal = .1, n; +} +var emptyBinary = 0n; // should error but infer 0n +var emptyOct = 0n; // should error but infer 0n +var emptyHex = 0xn; // should error but infer 0n +var leadingSeparator = _123n; +var trailingSeparator = 123n; +var doubleSeparator = 123456789n; +// Using literals as types +var oneTwoOrThree = function (x) { return Math.pow(x, 2n); }; +oneTwoOrThree(0n); +oneTwoOrThree(1n); +oneTwoOrThree(2n); +oneTwoOrThree(3n); +oneTwoOrThree(0); +oneTwoOrThree(1); +oneTwoOrThree(2); +oneTwoOrThree(3); diff --git a/tests/baselines/reference/parseBigInt.symbols b/tests/baselines/reference/parseBigInt.symbols new file mode 100644 index 00000000000..4649d7d678a --- /dev/null +++ b/tests/baselines/reference/parseBigInt.symbols @@ -0,0 +1,179 @@ +=== tests/cases/compiler/parseBigInt.ts === +// All bases should allow "n" suffix +const bin = 0b101, binBig = 0b101n; // 5, 5n +>bin : Symbol(bin, Decl(parseBigInt.ts, 1, 5)) +>binBig : Symbol(binBig, Decl(parseBigInt.ts, 1, 18)) + +const oct = 0o567, octBig = 0o567n; // 375, 375n +>oct : Symbol(oct, Decl(parseBigInt.ts, 2, 5)) +>octBig : Symbol(octBig, Decl(parseBigInt.ts, 2, 18)) + +const hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n +>hex : Symbol(hex, Decl(parseBigInt.ts, 3, 5)) +>hexBig : Symbol(hexBig, Decl(parseBigInt.ts, 3, 18)) + +const dec = 123, decBig = 123n; +>dec : Symbol(dec, Decl(parseBigInt.ts, 4, 5)) +>decBig : Symbol(decBig, Decl(parseBigInt.ts, 4, 16)) + +// Test literals whose values overflow a 53-bit integer +// These should be represented exactly in the emitted JS +const largeBin = 0b10101010101010101010101010101010101010101010101010101010101n; // 384307168202282325n +>largeBin : Symbol(largeBin, Decl(parseBigInt.ts, 8, 5)) + +const largeOct = 0o123456712345671234567n; // 1505852261029722487n +>largeOct : Symbol(largeOct, Decl(parseBigInt.ts, 9, 5)) + +const largeDec = 12345678091234567890n; +>largeDec : Symbol(largeDec, Decl(parseBigInt.ts, 10, 5)) + +const largeHex = 0x1234567890abcdefn; // 1311768467294899695n +>largeHex : Symbol(largeHex, Decl(parseBigInt.ts, 11, 5)) + +// Test literals with separators +const separatedBin = 0b010_10_1n; // 21n +>separatedBin : Symbol(separatedBin, Decl(parseBigInt.ts, 14, 5)) + +const separatedOct = 0o1234_567n; // 342391n +>separatedOct : Symbol(separatedOct, Decl(parseBigInt.ts, 15, 5)) + +const separatedDec = 123_456_789n; +>separatedDec : Symbol(separatedDec, Decl(parseBigInt.ts, 16, 5)) + +const separatedHex = 0x0_abcdefn; // 11259375n +>separatedHex : Symbol(separatedHex, Decl(parseBigInt.ts, 17, 5)) + +// Test parsing literals of different bit sizes +// to ensure that parsePseudoBigInt() allocates enough space +const zero = 0b0n; +>zero : Symbol(zero, Decl(parseBigInt.ts, 21, 5)) + +const oneBit = 0b1n; +>oneBit : Symbol(oneBit, Decl(parseBigInt.ts, 22, 5)) + +const twoBit = 0b11n; // 3n +>twoBit : Symbol(twoBit, Decl(parseBigInt.ts, 23, 5)) + +const threeBit = 0b111n; // 7n +>threeBit : Symbol(threeBit, Decl(parseBigInt.ts, 24, 5)) + +const fourBit = 0b1111n; // 15n +>fourBit : Symbol(fourBit, Decl(parseBigInt.ts, 25, 5)) + +const fiveBit = 0b11111n; // 31n +>fiveBit : Symbol(fiveBit, Decl(parseBigInt.ts, 26, 5)) + +const sixBit = 0b111111n; // 63n +>sixBit : Symbol(sixBit, Decl(parseBigInt.ts, 27, 5)) + +const sevenBit = 0b1111111n; // 127n +>sevenBit : Symbol(sevenBit, Decl(parseBigInt.ts, 28, 5)) + +const eightBit = 0b11111111n; // 255n +>eightBit : Symbol(eightBit, Decl(parseBigInt.ts, 29, 5)) + +const nineBit = 0b111111111n; // 511n +>nineBit : Symbol(nineBit, Decl(parseBigInt.ts, 30, 5)) + +const tenBit = 0b1111111111n; // 1023n +>tenBit : Symbol(tenBit, Decl(parseBigInt.ts, 31, 5)) + +const elevenBit = 0b11111111111n; // 2047n +>elevenBit : Symbol(elevenBit, Decl(parseBigInt.ts, 32, 5)) + +const twelveBit = 0b111111111111n; // 4095n +>twelveBit : Symbol(twelveBit, Decl(parseBigInt.ts, 33, 5)) + +const thirteenBit = 0b1111111111111n; // 8191n +>thirteenBit : Symbol(thirteenBit, Decl(parseBigInt.ts, 34, 5)) + +const fourteenBit = 0b11111111111111n; // 16383n +>fourteenBit : Symbol(fourteenBit, Decl(parseBigInt.ts, 35, 5)) + +const fifteenBit = 0b111111111111111n; // 32767n +>fifteenBit : Symbol(fifteenBit, Decl(parseBigInt.ts, 36, 5)) + +const sixteenBit = 0b1111111111111111n; // 65535n +>sixteenBit : Symbol(sixteenBit, Decl(parseBigInt.ts, 37, 5)) + +const seventeenBit = 0b11111111111111111n; // 131071n +>seventeenBit : Symbol(seventeenBit, Decl(parseBigInt.ts, 38, 5)) + +// Test negative literals +const neg = -123n; +>neg : Symbol(neg, Decl(parseBigInt.ts, 41, 5)) + +const negHex: -16n = -0x10n; +>negHex : Symbol(negHex, Decl(parseBigInt.ts, 42, 5)) + +// Test normalization of bigints -- all of these should succeed +const negZero: 0n = -0n; +>negZero : Symbol(negZero, Decl(parseBigInt.ts, 45, 5)) + +const baseChange: 255n = 0xFFn; +>baseChange : Symbol(baseChange, Decl(parseBigInt.ts, 46, 5)) + +const leadingZeros: 0xFFn = 0x000000FFn; +>leadingZeros : Symbol(leadingZeros, Decl(parseBigInt.ts, 47, 5)) + +// Plus not allowed on literals +const unaryPlus = +123n; +>unaryPlus : Symbol(unaryPlus, Decl(parseBigInt.ts, 50, 5)) + +const unaryPlusHex = +0x123n; +>unaryPlusHex : Symbol(unaryPlusHex, Decl(parseBigInt.ts, 51, 5)) + +// Parsing errors +// In separate blocks because they each declare an "n" variable +{ const legacyOct = 0123n; } +>legacyOct : Symbol(legacyOct, Decl(parseBigInt.ts, 55, 7)) +>n : Symbol(n, Decl(parseBigInt.ts, 55, 24)) + +{ const scientific = 1e2n; } +>scientific : Symbol(scientific, Decl(parseBigInt.ts, 56, 7)) +>n : Symbol(n, Decl(parseBigInt.ts, 56, 24)) + +{ const decimal = 4.1n; } +>decimal : Symbol(decimal, Decl(parseBigInt.ts, 57, 7)) +>n : Symbol(n, Decl(parseBigInt.ts, 57, 21)) + +{ const leadingDecimal = .1n; } +>leadingDecimal : Symbol(leadingDecimal, Decl(parseBigInt.ts, 58, 7)) +>n : Symbol(n, Decl(parseBigInt.ts, 58, 27)) + +const emptyBinary = 0bn; // should error but infer 0n +>emptyBinary : Symbol(emptyBinary, Decl(parseBigInt.ts, 59, 5)) + +const emptyOct = 0on; // should error but infer 0n +>emptyOct : Symbol(emptyOct, Decl(parseBigInt.ts, 60, 5)) + +const emptyHex = 0xn; // should error but infer 0n +>emptyHex : Symbol(emptyHex, Decl(parseBigInt.ts, 61, 5)) + +const leadingSeparator = _123n; +>leadingSeparator : Symbol(leadingSeparator, Decl(parseBigInt.ts, 62, 5)) + +const trailingSeparator = 123_n; +>trailingSeparator : Symbol(trailingSeparator, Decl(parseBigInt.ts, 63, 5)) + +const doubleSeparator = 123_456__789n; +>doubleSeparator : Symbol(doubleSeparator, Decl(parseBigInt.ts, 64, 5)) + +// Using literals as types +const oneTwoOrThree = (x: 1n | 2n | 3n): bigint => x ** 2n; +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>x : Symbol(x, Decl(parseBigInt.ts, 67, 23)) +>x : Symbol(x, Decl(parseBigInt.ts, 67, 23)) + +oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); oneTwoOrThree(3n); +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) + +oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) +>oneTwoOrThree : Symbol(oneTwoOrThree, Decl(parseBigInt.ts, 67, 5)) + diff --git a/tests/baselines/reference/parseBigInt.types b/tests/baselines/reference/parseBigInt.types new file mode 100644 index 00000000000..9e9025b6221 --- /dev/null +++ b/tests/baselines/reference/parseBigInt.types @@ -0,0 +1,256 @@ +=== tests/cases/compiler/parseBigInt.ts === +// All bases should allow "n" suffix +const bin = 0b101, binBig = 0b101n; // 5, 5n +>bin : 5 +>0b101 : 5 +>binBig : 5n +>0b101n : 5n + +const oct = 0o567, octBig = 0o567n; // 375, 375n +>oct : 375 +>0o567 : 375 +>octBig : 375n +>0o567n : 375n + +const hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n +>hex : 3083 +>0xC0B : 3083 +>hexBig : 3083n +>0xC0Bn : 3083n + +const dec = 123, decBig = 123n; +>dec : 123 +>123 : 123 +>decBig : 123n +>123n : 123n + +// Test literals whose values overflow a 53-bit integer +// These should be represented exactly in the emitted JS +const largeBin = 0b10101010101010101010101010101010101010101010101010101010101n; // 384307168202282325n +>largeBin : 384307168202282325n +>0b10101010101010101010101010101010101010101010101010101010101n : 384307168202282325n + +const largeOct = 0o123456712345671234567n; // 1505852261029722487n +>largeOct : 1505852261029722487n +>0o123456712345671234567n : 1505852261029722487n + +const largeDec = 12345678091234567890n; +>largeDec : 12345678091234567890n +>12345678091234567890n : 12345678091234567890n + +const largeHex = 0x1234567890abcdefn; // 1311768467294899695n +>largeHex : 1311768467294899695n +>0x1234567890abcdefn : 1311768467294899695n + +// Test literals with separators +const separatedBin = 0b010_10_1n; // 21n +>separatedBin : 21n +>0b010_10_1n : 21n + +const separatedOct = 0o1234_567n; // 342391n +>separatedOct : 342391n +>0o1234_567n : 342391n + +const separatedDec = 123_456_789n; +>separatedDec : 123456789n +>123_456_789n : 123456789n + +const separatedHex = 0x0_abcdefn; // 11259375n +>separatedHex : 11259375n +>0x0_abcdefn : 11259375n + +// Test parsing literals of different bit sizes +// to ensure that parsePseudoBigInt() allocates enough space +const zero = 0b0n; +>zero : 0n +>0b0n : 0n + +const oneBit = 0b1n; +>oneBit : 1n +>0b1n : 1n + +const twoBit = 0b11n; // 3n +>twoBit : 3n +>0b11n : 3n + +const threeBit = 0b111n; // 7n +>threeBit : 7n +>0b111n : 7n + +const fourBit = 0b1111n; // 15n +>fourBit : 15n +>0b1111n : 15n + +const fiveBit = 0b11111n; // 31n +>fiveBit : 31n +>0b11111n : 31n + +const sixBit = 0b111111n; // 63n +>sixBit : 63n +>0b111111n : 63n + +const sevenBit = 0b1111111n; // 127n +>sevenBit : 127n +>0b1111111n : 127n + +const eightBit = 0b11111111n; // 255n +>eightBit : 255n +>0b11111111n : 255n + +const nineBit = 0b111111111n; // 511n +>nineBit : 511n +>0b111111111n : 511n + +const tenBit = 0b1111111111n; // 1023n +>tenBit : 1023n +>0b1111111111n : 1023n + +const elevenBit = 0b11111111111n; // 2047n +>elevenBit : 2047n +>0b11111111111n : 2047n + +const twelveBit = 0b111111111111n; // 4095n +>twelveBit : 4095n +>0b111111111111n : 4095n + +const thirteenBit = 0b1111111111111n; // 8191n +>thirteenBit : 8191n +>0b1111111111111n : 8191n + +const fourteenBit = 0b11111111111111n; // 16383n +>fourteenBit : 16383n +>0b11111111111111n : 16383n + +const fifteenBit = 0b111111111111111n; // 32767n +>fifteenBit : 32767n +>0b111111111111111n : 32767n + +const sixteenBit = 0b1111111111111111n; // 65535n +>sixteenBit : 65535n +>0b1111111111111111n : 65535n + +const seventeenBit = 0b11111111111111111n; // 131071n +>seventeenBit : 131071n +>0b11111111111111111n : 131071n + +// Test negative literals +const neg = -123n; +>neg : -123n +>-123n : -123n +>123n : 123n + +const negHex: -16n = -0x10n; +>negHex : -16n +>-16n : -16n +>16n : 16n +>-0x10n : -16n +>0x10n : 16n + +// Test normalization of bigints -- all of these should succeed +const negZero: 0n = -0n; +>negZero : 0n +>-0n : 0n +>0n : 0n + +const baseChange: 255n = 0xFFn; +>baseChange : 255n +>0xFFn : 255n + +const leadingZeros: 0xFFn = 0x000000FFn; +>leadingZeros : 255n +>0x000000FFn : 255n + +// Plus not allowed on literals +const unaryPlus = +123n; +>unaryPlus : 123n +>+123n : 123n +>123n : 123n + +const unaryPlusHex = +0x123n; +>unaryPlusHex : 291n +>+0x123n : 291n +>0x123n : 291n + +// Parsing errors +// In separate blocks because they each declare an "n" variable +{ const legacyOct = 0123n; } +>legacyOct : 123 +>0123 : 123 +>n : any + +{ const scientific = 1e2n; } +>scientific : 100 +>1e2 : 100 +>n : any + +{ const decimal = 4.1n; } +>decimal : 4.1 +>4.1 : 4.1 +>n : any + +{ const leadingDecimal = .1n; } +>leadingDecimal : 0.1 +>.1 : 0.1 +>n : any + +const emptyBinary = 0bn; // should error but infer 0n +>emptyBinary : 0n +>0bn : 0n + +const emptyOct = 0on; // should error but infer 0n +>emptyOct : 0n +>0on : 0n + +const emptyHex = 0xn; // should error but infer 0n +>emptyHex : 0n +>0xn : 0n + +const leadingSeparator = _123n; +>leadingSeparator : any +>_123n : any + +const trailingSeparator = 123_n; +>trailingSeparator : 123n +>123_n : 123n + +const doubleSeparator = 123_456__789n; +>doubleSeparator : 123456789n +>123_456__789n : 123456789n + +// Using literals as types +const oneTwoOrThree = (x: 1n | 2n | 3n): bigint => x ** 2n; +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>(x: 1n | 2n | 3n): bigint => x ** 2n : (x: 1n | 3n | 2n) => bigint +>x : 1n | 3n | 2n +>x ** 2n : bigint +>x : 1n | 3n | 2n +>2n : 2n + +oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); oneTwoOrThree(3n); +>oneTwoOrThree(0n) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>0n : 0n +>oneTwoOrThree(1n) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>1n : 1n +>oneTwoOrThree(2n) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>2n : 2n +>oneTwoOrThree(3n) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>3n : 3n + +oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); +>oneTwoOrThree(0) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>0 : 0 +>oneTwoOrThree(1) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>1 : 1 +>oneTwoOrThree(2) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>2 : 2 +>oneTwoOrThree(3) : bigint +>oneTwoOrThree : (x: 1n | 3n | 2n) => bigint +>3 : 3 + diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt index 8a1207f4510..6df7ea6e0a2 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt @@ -1,17 +1,22 @@ -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,22): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,29): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,39): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(2,48): error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(3,24): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,22): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,29): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,39): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,48): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -==== tests/cases/compiler/warnExperimentalBigIntLiteral.ts (4 errors) ==== +==== tests/cases/compiler/warnExperimentalBigIntLiteral.ts (5 errors) ==== const normalNumber = 123; // should not error + let bigintType: bigint; // should not error + let bigintLiteralType: 123n; // should error when used as type + ~~~~ +!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error ~~~~ -!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. ~~~~~~~ -!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. ~~~~~~ -!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. ~~~~~ -!!! error TS1350: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. \ No newline at end of file +!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. \ No newline at end of file diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.js b/tests/baselines/reference/warnExperimentalBigIntLiteral.js index 3f856417130..7f31a794ec2 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.js +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.js @@ -1,7 +1,11 @@ //// [warnExperimentalBigIntLiteral.ts] const normalNumber = 123; // should not error +let bigintType: bigint; // should not error +let bigintLiteralType: 123n; // should error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error //// [warnExperimentalBigIntLiteral.js] var normalNumber = 123; // should not error +var bigintType; // should not error +var bigintLiteralType; // should error when used as type var bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols index a54991a7bd5..782e7edcac6 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols @@ -2,6 +2,12 @@ const normalNumber = 123; // should not error >normalNumber : Symbol(normalNumber, Decl(warnExperimentalBigIntLiteral.ts, 0, 5)) -const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error ->bigintNumber : Symbol(bigintNumber, Decl(warnExperimentalBigIntLiteral.ts, 1, 5)) +let bigintType: bigint; // should not error +>bigintType : Symbol(bigintType, Decl(warnExperimentalBigIntLiteral.ts, 1, 3)) + +let bigintLiteralType: 123n; // should error when used as type +>bigintLiteralType : Symbol(bigintLiteralType, Decl(warnExperimentalBigIntLiteral.ts, 2, 3)) + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : Symbol(bigintNumber, Decl(warnExperimentalBigIntLiteral.ts, 3, 5)) diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.types b/tests/baselines/reference/warnExperimentalBigIntLiteral.types index 1a15f5d5dae..a3f01b31294 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.types +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.types @@ -3,6 +3,12 @@ const normalNumber = 123; // should not error >normalNumber : 123 >123 : 123 +let bigintType: bigint; // should not error +>bigintType : bigint + +let bigintLiteralType: 123n; // should error when used as type +>bigintLiteralType : 123n + const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error >bigintNumber : bigint >123n * 0b1111n + 0o444n * 0x7fn : bigint diff --git a/tests/cases/compiler/bigintIndex.ts b/tests/cases/compiler/bigintIndex.ts new file mode 100644 index 00000000000..ca467d58c0e --- /dev/null +++ b/tests/cases/compiler/bigintIndex.ts @@ -0,0 +1,25 @@ +// @target: es2015 +// @experimentalBigInt: true + +interface BigIntIndex { + [index: bigint]: E; // should error +} + +const arr: number[] = [1, 2, 3]; +let num: number = arr[1]; +num = arr["1"]; +num = arr[1n]; // should error + +let key: keyof any; // should be type "string | number | symbol" +key = 123; +key = "abc"; +key = Symbol(); +key = 123n; // should error + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +const typedArray = new Uint8Array(3); +typedArray[bigNum] = 0xAA; // should error +typedArray[String(bigNum)] = 0xAA; +typedArray["1"] = 0xBB; +typedArray[2] = 0xCC; \ No newline at end of file diff --git a/tests/cases/compiler/bigintWithLib.ts b/tests/cases/compiler/bigintWithLib.ts new file mode 100644 index 00000000000..3299b1ecc83 --- /dev/null +++ b/tests/cases/compiler/bigintWithLib.ts @@ -0,0 +1,50 @@ +// @experimentalBigInt: true +// @target: esnext + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); // should error +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); +let stringVal: string = bigintVal.toString(); +stringVal = bigintVal.toString(2); +stringVal = bigintVal.toLocaleString(); + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; // should error +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; // should error +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); // should error +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); // should error +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); \ No newline at end of file diff --git a/tests/cases/compiler/bigintWithoutLib.ts b/tests/cases/compiler/bigintWithoutLib.ts new file mode 100644 index 00000000000..94d77ffa6f4 --- /dev/null +++ b/tests/cases/compiler/bigintWithoutLib.ts @@ -0,0 +1,52 @@ +// @experimentalBigInt: true +// @target: es5 + +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); \ No newline at end of file diff --git a/tests/cases/compiler/numberVsBigIntOperations.ts b/tests/cases/compiler/numberVsBigIntOperations.ts new file mode 100644 index 00000000000..b2f337b00b9 --- /dev/null +++ b/tests/cases/compiler/numberVsBigIntOperations.ts @@ -0,0 +1,96 @@ +// @experimentalBigInt: true + +// Cannot mix bigints and numbers +let bigInt = 1n, num = 2; +bigInt = 1n; bigInt = 2; num = 1n; num = 2; +bigInt += 1n; bigInt += 2; num += 1n; num += 2; +bigInt -= 1n; bigInt -= 2; num -= 1n; num -= 2; +bigInt *= 1n; bigInt *= 2; num *= 1n; num *= 2; +bigInt /= 1n; bigInt /= 2; num /= 1n; num /= 2; +bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; +bigInt **= 1n; bigInt **= 2; num **= 1n; num **= 2; +bigInt <<= 1n; bigInt <<= 2; num <<= 1n; num <<= 2; +bigInt >>= 1n; bigInt >>= 2; num >>= 1n; num >>= 2; +bigInt &= 1n; bigInt &= 2; num &= 1n; num &= 2; +bigInt ^= 1n; bigInt ^= 2; num ^= 1n; num ^= 2; +bigInt |= 1n; bigInt |= 2; num |= 1n; num |= 2; +bigInt = 1n + 2n; num = 1 + 2; 1 + 2n; 1n + 2; +bigInt = 1n - 2n; num = 1 - 2; 1 - 2n; 1n - 2; +bigInt = 1n * 2n; num = 1 * 2; 1 * 2n; 1n * 2; +bigInt = 1n / 2n; num = 1 / 2; 1 / 2n; 1n / 2; +bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; +bigInt = 1n ** 2n; num = 1 ** 2; 1 ** 2n; 1n ** 2; +bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; 1n & 2; +bigInt = 1n | 2n; num = 1 | 2; 1 | 2n; 1n | 2; +bigInt = 1n ^ 2n; num = 1 ^ 2; 1 ^ 2n; 1n ^ 2; +bigInt = 1n << 2n; num = 1 << 2; 1 << 2n; 1n << 2; +bigInt = 1n >> 2n; num = 1 >> 2; 1 >> 2n; 1n >> 2; + +// Plus should still coerce to strings +let str: string; +str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; str = 123n + "abc"; + +// Unary operations allowed on bigints and numbers +bigInt = bigInt++; bigInt = ++bigInt; num = num++; num = ++num; +bigInt = bigInt--; bigInt = --bigInt; num = num--; num = --num; +bigInt = -bigInt; num = -num; +bigInt = ~bigInt; num = ~num; + +// Number-only operations +bigInt >>>= 1n; num >>>= 2; +bigInt = bigInt >>> 1n; num = num >>> 2; +num = +bigInt; num = +num; num = +"3"; + +// Comparisons can be mixed +let result: boolean; +result = bigInt > num; +result = bigInt >= num; +result = bigInt < num; +result = bigInt <= num; + +// Trying to compare for equality is likely an error (since 1 == "1" is disallowed) +result = bigInt == num; +result = bigInt != num; +result = bigInt === num; +result = bigInt !== num; + +// Types of arithmetic operations on other types +num = "3" & 5; num = 2 ** false; // should error, but infer number +"3" & 5n; 2n ** false; // should error, result in any +num = ~"3"; num = -false; // should infer number +let bigIntOrNumber: bigint | number; +bigIntOrNumber + bigIntOrNumber; // should error, result in any +bigIntOrNumber << bigIntOrNumber; // should error, result in any +if (typeof bigIntOrNumber === "bigint") { + // Allowed, as type is narrowed to bigint + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} +if (typeof bigIntOrNumber === "number") { + // Allowed, as type is narrowed to number + bigIntOrNumber = bigIntOrNumber << bigIntOrNumber; +} ++bigIntOrNumber; // should error, result in number +~bigIntOrNumber; // should infer number | bigint +bigIntOrNumber++; // should infer number | bigint +++bigIntOrNumber; // should infer number | bigint +let anyValue: any; +anyValue + anyValue; // should infer any +anyValue >>> anyValue; // should infer number +anyValue ^ anyValue; // should infer number ++anyValue; // should infer number +-anyValue; // should infer number +anyValue--; // should infer number +--anyValue; // should infer number + +// Distinguishing numbers from bigints with typeof +const isBigInt: (x: 0n | 1n) => bigint = (x: 0n | 1n) => x; +const isNumber: (x: 0 | 1) => number = (x: 0 | 1) => x; +const zeroOrBigOne: 0 | 1n; +if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); +else isNumber(zeroOrBigOne); + +// Distinguishing truthy from falsy +const isOne = (x: 1 | 1n) => x; +if (zeroOrBigOne) isOne(zeroOrBigOne); +const bigZeroOrOne: 0n | 1; +if (bigZeroOrOne) isOne(bigZeroOrOne); \ No newline at end of file diff --git a/tests/cases/compiler/parseBigInt.ts b/tests/cases/compiler/parseBigInt.ts new file mode 100644 index 00000000000..35cc13151ad --- /dev/null +++ b/tests/cases/compiler/parseBigInt.ts @@ -0,0 +1,72 @@ +// @experimentalBigInt: true + +// All bases should allow "n" suffix +const bin = 0b101, binBig = 0b101n; // 5, 5n +const oct = 0o567, octBig = 0o567n; // 375, 375n +const hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n +const dec = 123, decBig = 123n; + +// Test literals whose values overflow a 53-bit integer +// These should be represented exactly in the emitted JS +const largeBin = 0b10101010101010101010101010101010101010101010101010101010101n; // 384307168202282325n +const largeOct = 0o123456712345671234567n; // 1505852261029722487n +const largeDec = 12345678091234567890n; +const largeHex = 0x1234567890abcdefn; // 1311768467294899695n + +// Test literals with separators +const separatedBin = 0b010_10_1n; // 21n +const separatedOct = 0o1234_567n; // 342391n +const separatedDec = 123_456_789n; +const separatedHex = 0x0_abcdefn; // 11259375n + +// Test parsing literals of different bit sizes +// to ensure that parsePseudoBigInt() allocates enough space +const zero = 0b0n; +const oneBit = 0b1n; +const twoBit = 0b11n; // 3n +const threeBit = 0b111n; // 7n +const fourBit = 0b1111n; // 15n +const fiveBit = 0b11111n; // 31n +const sixBit = 0b111111n; // 63n +const sevenBit = 0b1111111n; // 127n +const eightBit = 0b11111111n; // 255n +const nineBit = 0b111111111n; // 511n +const tenBit = 0b1111111111n; // 1023n +const elevenBit = 0b11111111111n; // 2047n +const twelveBit = 0b111111111111n; // 4095n +const thirteenBit = 0b1111111111111n; // 8191n +const fourteenBit = 0b11111111111111n; // 16383n +const fifteenBit = 0b111111111111111n; // 32767n +const sixteenBit = 0b1111111111111111n; // 65535n +const seventeenBit = 0b11111111111111111n; // 131071n + +// Test negative literals +const neg = -123n; +const negHex: -16n = -0x10n; + +// Test normalization of bigints -- all of these should succeed +const negZero: 0n = -0n; +const baseChange: 255n = 0xFFn; +const leadingZeros: 0xFFn = 0x000000FFn; + +// Plus not allowed on literals +const unaryPlus = +123n; +const unaryPlusHex = +0x123n; + +// Parsing errors +// In separate blocks because they each declare an "n" variable +{ const legacyOct = 0123n; } +{ const scientific = 1e2n; } +{ const decimal = 4.1n; } +{ const leadingDecimal = .1n; } +const emptyBinary = 0bn; // should error but infer 0n +const emptyOct = 0on; // should error but infer 0n +const emptyHex = 0xn; // should error but infer 0n +const leadingSeparator = _123n; +const trailingSeparator = 123_n; +const doubleSeparator = 123_456__789n; + +// Using literals as types +const oneTwoOrThree = (x: 1n | 2n | 3n): bigint => x ** 2n; +oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); oneTwoOrThree(3n); +oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); \ No newline at end of file diff --git a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts index f837a17f7a1..2b4954bef3d 100644 --- a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts +++ b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts @@ -1,2 +1,4 @@ const normalNumber = 123; // should not error +let bigintType: bigint; // should not error +let bigintLiteralType: 123n; // should error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error \ No newline at end of file From 28e9ec497c961057339248497289bbcefe5f9203 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Tue, 30 Oct 2018 16:56:05 -0700 Subject: [PATCH 216/262] Address review comments --- src/compiler/binder.ts | 10 +- src/compiler/checker.ts | 74 +- src/compiler/commandLineParser.ts | 2 +- src/compiler/diagnosticMessages.json | 6 +- src/compiler/emitter.ts | 6 +- src/compiler/factory.ts | 11 +- src/compiler/parser.ts | 15 +- src/compiler/scanner.ts | 35 +- src/compiler/transformers/ts.ts | 22 +- src/compiler/types.ts | 8 +- src/compiler/utilities.ts | 22 +- src/harness/fourslash.ts | 2 + src/services/classifier.ts | 8 + src/services/formatting/rules.ts | 4 +- src/services/types.ts | 3 + src/services/utilities.ts | 1 + .../reference/api/tsserverlibrary.d.ts | 671 +++++++++--------- tests/baselines/reference/api/typescript.d.ts | 671 +++++++++--------- tests/baselines/reference/bigintIndex.symbols | 6 +- tests/baselines/reference/bigintWithLib.js | 4 +- .../reference/bigintWithoutLib.errors.txt | 38 +- tests/baselines/reference/bigintWithoutLib.js | 4 +- .../reference/numberVsBigIntOperations.js | 40 +- tests/baselines/reference/parseBigInt.js | 96 +-- tests/baselines/reference/parseBigInt.types | 8 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../warnExperimentalBigIntLiteral.js | 8 +- tests/cases/compiler/bigintIndex.ts | 2 +- .../compiler/numberVsBigIntOperations.ts | 1 + tests/cases/compiler/parseBigInt.ts | 1 + .../compiler/warnExperimentalBigIntLiteral.ts | 2 + 39 files changed, 961 insertions(+), 838 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 0d6a91def8c..eae59db1bc6 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -3697,13 +3697,13 @@ namespace ts { break; case SyntaxKind.NumericLiteral: - const flags = (node).numericLiteralFlags; - if (flags & TokenFlags.BinaryOrOctalSpecifier) { + if ((node).numericLiteralFlags & TokenFlags.BinaryOrOctalSpecifier) { transformFlags |= TransformFlags.AssertES2015; } - if (flags & TokenFlags.BigInt) { - transformFlags |= TransformFlags.AssertESNext; - } + break; + + case SyntaxKind.BigIntLiteral: + transformFlags |= TransformFlags.AssertESNext; break; case SyntaxKind.ForOfStatement: diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0353b21869d..a16cab1443c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9268,18 +9268,11 @@ namespace ts { type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); } - function getNumericLiteralValue(node: NumericLiteral): number | PseudoBigInt { - if (node.numericLiteralFlags & TokenFlags.BigInt) { - if (!compilerOptions.experimentalBigInt) { - error(node, Diagnostics.Experimental_support_for_BigInt_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalBigInt_option_to_remove_this_warning); - } - return { negative: false, base10Value: parsePseudoBigInt(node.text) }; - } - return +node.text; - } - - function getNumericLiteralType(node: NumericLiteral): LiteralType { - return getLiteralType(getNumericLiteralValue(node)); + function getBigIntLiteralType(node: BigIntLiteral): LiteralType { + return getLiteralType({ + negative: false, + base10Value: parsePseudoBigInt(node.text) + }); } function getLiteralTypeFromPropertyName(prop: Symbol, include: TypeFlags) { @@ -9287,8 +9280,8 @@ namespace ts { let type = getLateBoundSymbol(prop).nameType; if (!type && !isKnownSymbol(prop)) { const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration); - type = name && isNumericLiteral(name) ? getNumericLiteralType(name) : - name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getNumericLiteralType(name.expression) : + type = name && isNumericLiteral(name) ? getLiteralType(+name.text) : + name && name.kind === SyntaxKind.ComputedPropertyName && isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : getLiteralType(symbolName(prop)); } if (type && type.flags & include) { @@ -17077,6 +17070,7 @@ namespace ts { switch (node.kind) { case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: @@ -21503,22 +21497,22 @@ namespace ts { if (operandType === silentNeverType) { return silentNeverType; } - if (node.operand.kind === SyntaxKind.NumericLiteral) { - if (node.operator === SyntaxKind.MinusToken) { - const value = getNumericLiteralValue(node.operand as NumericLiteral); - return getFreshTypeOfLiteralType(getLiteralType( - // Keep number as number, bigint as bigint - typeof value === "number" - ? -value - : { negative: !value.negative, base10Value: value.base10Value } - )); - } - else if (node.operator === SyntaxKind.PlusToken) { - if (isTypeAssignableToKind(operandType, TypeFlags.BigIntLike)) { - error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(operandType)); + switch (node.operand.kind) { + case SyntaxKind.NumericLiteral: + switch (node.operator) { + case SyntaxKind.MinusToken: + return getFreshTypeOfLiteralType(getLiteralType(-(node.operand as NumericLiteral).text)); + case SyntaxKind.PlusToken: + return getFreshTypeOfLiteralType(getLiteralType(+(node.operand as NumericLiteral).text)); + } + break; + case SyntaxKind.BigIntLiteral: + if (node.operator === SyntaxKind.MinusToken) { + return getFreshTypeOfLiteralType(getLiteralType({ + negative: true, + base10Value: parsePseudoBigInt((node.operand as BigIntLiteral).text) + })); } - return getFreshTypeOfLiteralType(getNumericLiteralType(node.operand as NumericLiteral)); - } } switch (node.operator) { case SyntaxKind.PlusToken: @@ -21860,6 +21854,7 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: @@ -22002,7 +21997,6 @@ namespace ts { } return resultType; } - case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: if (leftType === silentNeverType || rightType === silentNeverType) { @@ -22558,7 +22552,10 @@ namespace ts { return getFreshTypeOfLiteralType(getLiteralType((node as StringLiteralLike).text)); case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(node as NumericLiteral); - return getFreshTypeOfLiteralType(getNumericLiteralType(node as NumericLiteral)); + return getFreshTypeOfLiteralType(getLiteralType(+(node as NumericLiteral).text)); + case SyntaxKind.BigIntLiteral: + checkGrammarBigIntLiteral(node as BigIntLiteral); + return getFreshTypeOfLiteralType(getBigIntLiteralType(node as BigIntLiteral)); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: @@ -26595,8 +26592,7 @@ namespace ts { return (expr).text; case SyntaxKind.NumericLiteral: checkGrammarNumericLiteral(expr); - const literalValue = getNumericLiteralValue(expr); - return typeof literalValue === "number" ? literalValue : undefined; // don't evaluate bigint + return +(expr).text; case SyntaxKind.ParenthesizedExpression: return evaluate((expr).expression); case SyntaxKind.Identifier: @@ -30462,6 +30458,18 @@ namespace ts { return false; } + function checkGrammarBigIntLiteral(node: BigIntLiteral): boolean { + if (languageVersion < ScriptTarget.ESNext) { + if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targetting_lower_than_ESNext)) { + return true; + } + } + if (!compilerOptions.experimentalBigInt) { + return grammarErrorOnNode(node, Diagnostics.Experimental_support_for_BigInt_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalBigInt_option_to_remove_this_warning); + } + return false; + } + function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 9c333f2cadf..3947ef51844 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -588,7 +588,7 @@ namespace ts { name: "experimentalBigInt", type: "boolean", category: Diagnostics.Experimental_Options, - description: Diagnostics.Enables_experimental_support_for_ESNext_BigInt_expressions + description: Diagnostics.Enables_experimental_support_for_ESNext_BigInt_literals }, // Advanced diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index a1cab6bfaff..49f682c4d58 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2505,6 +2505,10 @@ "category": "Error", "code": 2736 }, + "BigInt literals are not available when targetting lower than ESNext.": { + "category": "Error", + "code": 2737 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -3913,7 +3917,7 @@ "category": "Error", "code": 6370 }, - "Enables experimental support for ESNext BigInt expressions.": { + "Enables experimental support for ESNext BigInt literals.": { "category": "Message", "code": 6371 }, diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 50644552efe..2443f72d591 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -905,7 +905,8 @@ namespace ts { switch (node.kind) { // Literals case SyntaxKind.NumericLiteral: - return emitNumericLiteral(node); + case SyntaxKind.BigIntLiteral: + return emitNumericOrBigIntLiteral(node); case SyntaxKind.StringLiteral: case SyntaxKind.RegularExpressionLiteral: @@ -1068,7 +1069,8 @@ namespace ts { // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node: NumericLiteral) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node: NumericLiteral | BigIntLiteral) { emitLiteral(node); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 39d3d5c3c83..160376c39b2 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -76,9 +76,7 @@ namespace ts { return createNumericLiteral(value + ""); } if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt - const literal = createNumericLiteral(pseudoBigIntToString(value) + "n"); - literal.numericLiteralFlags |= TokenFlags.BigInt; - return literal; + return createBigIntLiteral(pseudoBigIntToString(value) + "n"); } if (typeof value === "boolean") { return value ? createTrue() : createFalse(); @@ -98,6 +96,12 @@ namespace ts { return node; } + export function createBigIntLiteral(value: string): BigIntLiteral { + const node = createSynthesizedNode(SyntaxKind.BigIntLiteral); + node.text = value; + return node; + } + export function createStringLiteral(text: string): StringLiteral { const node = createSynthesizedNode(SyntaxKind.StringLiteral); node.text = text; @@ -3472,6 +3476,7 @@ namespace ts { return cacheIdentifiers; case SyntaxKind.ThisKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: return false; case SyntaxKind.ArrayLiteralExpression: diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 376afe43d2c..6831d27db9c 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2891,8 +2891,9 @@ namespace ts { return finishNode(node); } - function nextTokenIsNumericLiteral() { - return nextToken() === SyntaxKind.NumericLiteral; + function nextTokenIsNumericOrBigIntLiteral() { + nextToken(); + return token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral; } function parseNonArrayType(): TypeNode { @@ -2922,11 +2923,12 @@ namespace ts { case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return parseLiteralTypeNode(); case SyntaxKind.MinusToken: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); case SyntaxKind.VoidKeyword: case SyntaxKind.NullKeyword: return parseTokenNode(); @@ -2978,6 +2980,7 @@ namespace ts { case SyntaxKind.NewKeyword: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ObjectKeyword: @@ -2991,7 +2994,7 @@ namespace ts { case SyntaxKind.FunctionKeyword: return !inStartOfParameter; case SyntaxKind.MinusToken: - return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); + return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); case SyntaxKind.OpenParenToken: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. @@ -3216,6 +3219,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: @@ -4625,6 +4629,7 @@ namespace ts { function parsePrimaryExpression(): PrimaryExpression { switch (token()) { case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: return parseLiteralNode(); @@ -5140,7 +5145,7 @@ namespace ts { function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak(); + return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak(); } function isDeclaration(): boolean { diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 22b90df6799..b8d4d248077 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -920,7 +920,7 @@ namespace ts { return result + text.substring(start, pos); } - function scanNumber(): string { + function scanNumber(): {type: SyntaxKind, value: string} { const start = pos; const mainFragment = scanNumberFragment(); let decimalFragment: string | undefined; @@ -957,13 +957,16 @@ namespace ts { else { result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } - if (decimalFragment === undefined && !(tokenFlags & TokenFlags.Scientific)) { - tokenValue = result; - checkBigIntSuffix(); // if value is an integer, check whether it is a bigint - return tokenValue; + if (decimalFragment !== undefined || tokenFlags & TokenFlags.Scientific) { + return { + type: SyntaxKind.NumericLiteral, + value: "" + +result // if value is not an integer, it can be safely coerced to a number + }; } else { - return "" + +result; // if value is not an integer, it can be safely coerced to a number + tokenValue = result; + const type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + return { type, value: tokenValue }; } } @@ -1354,15 +1357,15 @@ namespace ts { return value; } - function checkBigIntSuffix(): void { + function checkBigIntSuffix(): SyntaxKind { if (text.charCodeAt(pos) === CharacterCodes.n) { - tokenFlags |= TokenFlags.BigInt; tokenValue += "n"; // Use base 10 instead of base 2 or base 8 for shorter literals if (tokenFlags & TokenFlags.BinaryOrOctalSpecifier) { tokenValue = parsePseudoBigInt(tokenValue) + "n"; } pos++; + return SyntaxKind.BigIntLiteral; } else { // not a bigint, so can convert to number in simplified form // Number() may not support 0b or 0o, so use parseInt() instead @@ -1372,6 +1375,7 @@ namespace ts { ? parseInt(tokenValue.slice(2), 8) // skip "0o" : +tokenValue; tokenValue = "" + numericValue; + return SyntaxKind.NumericLiteral; } } @@ -1523,7 +1527,7 @@ namespace ts { return token = SyntaxKind.MinusToken; case CharacterCodes.dot: if (isDigit(text.charCodeAt(pos + 1))) { - tokenValue = scanNumber(); + tokenValue = scanNumber().value; return token = SyntaxKind.NumericLiteral; } if (text.charCodeAt(pos + 1) === CharacterCodes.dot && text.charCodeAt(pos + 2) === CharacterCodes.dot) { @@ -1606,8 +1610,7 @@ namespace ts { } tokenValue = "0x" + tokenValue; tokenFlags |= TokenFlags.HexSpecifier; - checkBigIntSuffix(); - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.B || text.charCodeAt(pos + 1) === CharacterCodes.b)) { pos += 2; @@ -1618,8 +1621,7 @@ namespace ts { } tokenValue = "0b" + tokenValue; tokenFlags |= TokenFlags.BinarySpecifier; - checkBigIntSuffix(); - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.O || text.charCodeAt(pos + 1) === CharacterCodes.o)) { pos += 2; @@ -1630,8 +1632,7 @@ namespace ts { } tokenValue = "0o" + tokenValue; tokenFlags |= TokenFlags.OctalSpecifier; - checkBigIntSuffix(); - return token = SyntaxKind.NumericLiteral; + return token = checkBigIntSuffix(); } // Try to parse as an octal if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) { @@ -1652,8 +1653,8 @@ namespace ts { case CharacterCodes._7: case CharacterCodes._8: case CharacterCodes._9: - tokenValue = scanNumber(); - return token = SyntaxKind.NumericLiteral; + ({ type: token, value: tokenValue } = scanNumber()); + return token; case CharacterCodes.colon: pos++; return token = SyntaxKind.ColonToken; diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 057dfc97a74..5917a365ddf 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1901,6 +1901,9 @@ namespace ts { case SyntaxKind.NumericLiteral: return createIdentifier("Number"); + case SyntaxKind.BigIntLiteral: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return createIdentifier("Boolean"); @@ -1912,6 +1915,9 @@ namespace ts { case SyntaxKind.NumberKeyword: return createIdentifier("Number"); + case SyntaxKind.BigIntKeyword: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.SymbolKeyword: return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() @@ -2007,7 +2013,7 @@ namespace ts { return createVoidZero(); case TypeReferenceSerializationKind.BigIntLikeType: - return createIdentifier("BigInt"); + return getGlobalBigIntNameWithFallback(); case TypeReferenceSerializationKind.BooleanType: return createIdentifier("Boolean"); @@ -2118,6 +2124,20 @@ namespace ts { ); } + /** + * Gets an expression that points to the global "BigInt" constructor at runtime if it is + * available. + */ + function getGlobalBigIntNameWithFallback(): SerializedTypeNode { + return languageVersion < ScriptTarget.ESNext + ? createConditional( + createTypeCheck(createIdentifier("BigInt"), "function"), + createIdentifier("BigInt"), + createIdentifier("Object") + ) + : createIdentifier("BigInt"); + } + /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 9607b95b8e3..46a5ed91275 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -129,6 +129,7 @@ namespace ts { ConflictMarkerTrivia, // Literals NumericLiteral, + BigIntLiteral, StringLiteral, JsxText, JsxTextAllWhiteSpaces, @@ -1661,9 +1662,8 @@ namespace ts { BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` OctalSpecifier = 1 << 8, // e.g. `0o777` ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` - BigInt = 1 << 10, // e.g. `123n` BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier, - NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator | BigInt + NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator } export interface NumericLiteral extends LiteralExpression { @@ -1672,6 +1672,10 @@ namespace ts { numericLiteralFlags: TokenFlags; } + export interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } + export interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 87795492a11..8813c705eb5 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -527,7 +527,10 @@ namespace ts { export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, neverAsciiEscape: boolean | undefined) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. - if (!nodeIsSynthesized(node) && node.parent && !(isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator)) { + if (!nodeIsSynthesized(node) && node.parent && !( + (isNumericLiteral(node) && node.numericLiteralFlags & TokenFlags.ContainsSeparator) || + isBigIntLiteral(node) + )) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } @@ -554,6 +557,7 @@ namespace ts { case SyntaxKind.TemplateTail: return "}" + escapeText(node.text, CharacterCodes.backtick) + "`"; case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.RegularExpressionLiteral: return node.text; } @@ -1600,6 +1604,7 @@ namespace ts { } // falls through case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ThisKeyword: return isInExpressionContext(node); @@ -2906,6 +2911,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ObjectLiteralExpression: @@ -5272,6 +5278,10 @@ namespace ts { return node.kind === SyntaxKind.NumericLiteral; } + export function isBigIntLiteral(node: Node): node is BigIntLiteral { + return node.kind === SyntaxKind.BigIntLiteral; + } + export function isStringLiteral(node: Node): node is StringLiteral { return node.kind === SyntaxKind.StringLiteral; } @@ -6398,6 +6408,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateExpression: @@ -8430,20 +8441,11 @@ namespace ts { } } - // TODO: remove once tslint allows tsconfig.json to include lib "esnext.bigint" - /* @internal */ - declare const BigInt: ((value: string) => number) | undefined; - /** * Converts a bigint literal string, e.g. `0x1234n`, * to its decimal string representation, e.g. `4660`. */ export function parsePseudoBigInt(stringValue: string): string { - // Use native BigInt if available - if (typeof BigInt !== "undefined") { - return "" + BigInt(stringValue.slice(0, -1)); // omit trailing "n" - } - let log2Base: number; switch (stringValue.charCodeAt(1)) { // "x" in "0x123" case CharacterCodes.b: diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index aeb2920ce3d..e4908d3612f 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -4663,6 +4663,7 @@ namespace FourSlashInterface { "unknown", "from", "global", + "bigint", "of", ]; @@ -4838,6 +4839,7 @@ namespace FourSlashInterface { "unknown", "from", "global", + "bigint", "of", ]; diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 5c18eae4aa1..26d77ffc602 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -182,6 +182,7 @@ namespace ts { SyntaxKind.Identifier, SyntaxKind.StringLiteral, SyntaxKind.NumericLiteral, + SyntaxKind.BigIntLiteral, SyntaxKind.RegularExpressionLiteral, SyntaxKind.ThisKeyword, SyntaxKind.PlusPlusToken, @@ -286,6 +287,7 @@ namespace ts { case ClassificationType.comment: return TokenClass.Comment; case ClassificationType.keyword: return TokenClass.Keyword; case ClassificationType.numericLiteral: return TokenClass.NumberLiteral; + case ClassificationType.bigintLiteral: return TokenClass.BigIntLiteral; case ClassificationType.operator: return TokenClass.Operator; case ClassificationType.stringLiteral: return TokenClass.StringLiteral; case ClassificationType.whiteSpace: return TokenClass.Whitespace; @@ -422,6 +424,8 @@ namespace ts { switch (token) { case SyntaxKind.NumericLiteral: return ClassificationType.numericLiteral; + case SyntaxKind.BigIntLiteral: + return ClassificationType.bigintLiteral; case SyntaxKind.StringLiteral: return ClassificationType.stringLiteral; case SyntaxKind.RegularExpressionLiteral: @@ -542,6 +546,7 @@ namespace ts { case ClassificationType.identifier: return ClassificationTypeNames.identifier; case ClassificationType.keyword: return ClassificationTypeNames.keyword; case ClassificationType.numericLiteral: return ClassificationTypeNames.numericLiteral; + case ClassificationType.bigintLiteral: return ClassificationTypeNames.bigintLiteral; case ClassificationType.operator: return ClassificationTypeNames.operator; case ClassificationType.stringLiteral: return ClassificationTypeNames.stringLiteral; case ClassificationType.whiteSpace: return ClassificationTypeNames.whiteSpace; @@ -886,6 +891,9 @@ namespace ts { else if (tokenKind === SyntaxKind.NumericLiteral) { return ClassificationType.numericLiteral; } + else if (tokenKind === SyntaxKind.BigIntLiteral) { + return ClassificationType.bigintLiteral; + } else if (tokenKind === SyntaxKind.StringLiteral) { // TODO: GH#18217 return token!.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral; diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 5e64119fcb1..b2dac950323 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -22,8 +22,8 @@ namespace ts.formatting { const binaryKeywordOperators = [SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]; const unaryPrefixOperators = [SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]; const unaryPrefixExpressions = [ - SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, - SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; + SyntaxKind.NumericLiteral, SyntaxKind.BigIntLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, + SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; const unaryPreincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; const unaryPostincrementExpressions = [SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]; const unaryPredecrementExpressions = [SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]; diff --git a/src/services/types.ts b/src/services/types.ts index d517c61906a..b856d15f61a 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -978,6 +978,7 @@ namespace ts { Whitespace, Identifier, NumberLiteral, + BigIntLiteral, StringLiteral, RegExpLiteral, } @@ -1141,6 +1142,7 @@ namespace ts { identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -1189,5 +1191,6 @@ namespace ts { jsxAttribute = 22, jsxText = 23, jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25, } } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 30c45620c1f..61f6e6e6087 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1028,6 +1028,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 68113b99ca1..a6b826326cf 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -85,338 +85,339 @@ declare namespace ts { ShebangTrivia = 6, ConflictMarkerTrivia = 7, NumericLiteral = 8, - StringLiteral = 9, - JsxText = 10, - JsxTextAllWhiteSpaces = 11, - RegularExpressionLiteral = 12, - NoSubstitutionTemplateLiteral = 13, - TemplateHead = 14, - TemplateMiddle = 15, - TemplateTail = 16, - OpenBraceToken = 17, - CloseBraceToken = 18, - OpenParenToken = 19, - CloseParenToken = 20, - OpenBracketToken = 21, - CloseBracketToken = 22, - DotToken = 23, - DotDotDotToken = 24, - SemicolonToken = 25, - CommaToken = 26, - LessThanToken = 27, - LessThanSlashToken = 28, - GreaterThanToken = 29, - LessThanEqualsToken = 30, - GreaterThanEqualsToken = 31, - EqualsEqualsToken = 32, - ExclamationEqualsToken = 33, - EqualsEqualsEqualsToken = 34, - ExclamationEqualsEqualsToken = 35, - EqualsGreaterThanToken = 36, - PlusToken = 37, - MinusToken = 38, - AsteriskToken = 39, - AsteriskAsteriskToken = 40, - SlashToken = 41, - PercentToken = 42, - PlusPlusToken = 43, - MinusMinusToken = 44, - LessThanLessThanToken = 45, - GreaterThanGreaterThanToken = 46, - GreaterThanGreaterThanGreaterThanToken = 47, - AmpersandToken = 48, - BarToken = 49, - CaretToken = 50, - ExclamationToken = 51, - TildeToken = 52, - AmpersandAmpersandToken = 53, - BarBarToken = 54, - QuestionToken = 55, - ColonToken = 56, - AtToken = 57, - EqualsToken = 58, - PlusEqualsToken = 59, - MinusEqualsToken = 60, - AsteriskEqualsToken = 61, - AsteriskAsteriskEqualsToken = 62, - SlashEqualsToken = 63, - PercentEqualsToken = 64, - LessThanLessThanEqualsToken = 65, - GreaterThanGreaterThanEqualsToken = 66, - GreaterThanGreaterThanGreaterThanEqualsToken = 67, - AmpersandEqualsToken = 68, - BarEqualsToken = 69, - CaretEqualsToken = 70, - Identifier = 71, - BreakKeyword = 72, - CaseKeyword = 73, - CatchKeyword = 74, - ClassKeyword = 75, - ConstKeyword = 76, - ContinueKeyword = 77, - DebuggerKeyword = 78, - DefaultKeyword = 79, - DeleteKeyword = 80, - DoKeyword = 81, - ElseKeyword = 82, - EnumKeyword = 83, - ExportKeyword = 84, - ExtendsKeyword = 85, - FalseKeyword = 86, - FinallyKeyword = 87, - ForKeyword = 88, - FunctionKeyword = 89, - IfKeyword = 90, - ImportKeyword = 91, - InKeyword = 92, - InstanceOfKeyword = 93, - NewKeyword = 94, - NullKeyword = 95, - ReturnKeyword = 96, - SuperKeyword = 97, - SwitchKeyword = 98, - ThisKeyword = 99, - ThrowKeyword = 100, - TrueKeyword = 101, - TryKeyword = 102, - TypeOfKeyword = 103, - VarKeyword = 104, - VoidKeyword = 105, - WhileKeyword = 106, - WithKeyword = 107, - ImplementsKeyword = 108, - InterfaceKeyword = 109, - LetKeyword = 110, - PackageKeyword = 111, - PrivateKeyword = 112, - ProtectedKeyword = 113, - PublicKeyword = 114, - StaticKeyword = 115, - YieldKeyword = 116, - AbstractKeyword = 117, - AsKeyword = 118, - AnyKeyword = 119, - AsyncKeyword = 120, - AwaitKeyword = 121, - BooleanKeyword = 122, - ConstructorKeyword = 123, - DeclareKeyword = 124, - GetKeyword = 125, - InferKeyword = 126, - IsKeyword = 127, - KeyOfKeyword = 128, - ModuleKeyword = 129, - NamespaceKeyword = 130, - NeverKeyword = 131, - ReadonlyKeyword = 132, - RequireKeyword = 133, - NumberKeyword = 134, - ObjectKeyword = 135, - SetKeyword = 136, - StringKeyword = 137, - SymbolKeyword = 138, - TypeKeyword = 139, - UndefinedKeyword = 140, - UniqueKeyword = 141, - UnknownKeyword = 142, - FromKeyword = 143, - GlobalKeyword = 144, - BigIntKeyword = 145, - OfKeyword = 146, - QualifiedName = 147, - ComputedPropertyName = 148, - TypeParameter = 149, - Parameter = 150, - Decorator = 151, - PropertySignature = 152, - PropertyDeclaration = 153, - MethodSignature = 154, - MethodDeclaration = 155, - Constructor = 156, - GetAccessor = 157, - SetAccessor = 158, - CallSignature = 159, - ConstructSignature = 160, - IndexSignature = 161, - TypePredicate = 162, - TypeReference = 163, - FunctionType = 164, - ConstructorType = 165, - TypeQuery = 166, - TypeLiteral = 167, - ArrayType = 168, - TupleType = 169, - OptionalType = 170, - RestType = 171, - UnionType = 172, - IntersectionType = 173, - ConditionalType = 174, - InferType = 175, - ParenthesizedType = 176, - ThisType = 177, - TypeOperator = 178, - IndexedAccessType = 179, - MappedType = 180, - LiteralType = 181, - ImportType = 182, - ObjectBindingPattern = 183, - ArrayBindingPattern = 184, - BindingElement = 185, - ArrayLiteralExpression = 186, - ObjectLiteralExpression = 187, - PropertyAccessExpression = 188, - ElementAccessExpression = 189, - CallExpression = 190, - NewExpression = 191, - TaggedTemplateExpression = 192, - TypeAssertionExpression = 193, - ParenthesizedExpression = 194, - FunctionExpression = 195, - ArrowFunction = 196, - DeleteExpression = 197, - TypeOfExpression = 198, - VoidExpression = 199, - AwaitExpression = 200, - PrefixUnaryExpression = 201, - PostfixUnaryExpression = 202, - BinaryExpression = 203, - ConditionalExpression = 204, - TemplateExpression = 205, - YieldExpression = 206, - SpreadElement = 207, - ClassExpression = 208, - OmittedExpression = 209, - ExpressionWithTypeArguments = 210, - AsExpression = 211, - NonNullExpression = 212, - MetaProperty = 213, - SyntheticExpression = 214, - TemplateSpan = 215, - SemicolonClassElement = 216, - Block = 217, - VariableStatement = 218, - EmptyStatement = 219, - ExpressionStatement = 220, - IfStatement = 221, - DoStatement = 222, - WhileStatement = 223, - ForStatement = 224, - ForInStatement = 225, - ForOfStatement = 226, - ContinueStatement = 227, - BreakStatement = 228, - ReturnStatement = 229, - WithStatement = 230, - SwitchStatement = 231, - LabeledStatement = 232, - ThrowStatement = 233, - TryStatement = 234, - DebuggerStatement = 235, - VariableDeclaration = 236, - VariableDeclarationList = 237, - FunctionDeclaration = 238, - ClassDeclaration = 239, - InterfaceDeclaration = 240, - TypeAliasDeclaration = 241, - EnumDeclaration = 242, - ModuleDeclaration = 243, - ModuleBlock = 244, - CaseBlock = 245, - NamespaceExportDeclaration = 246, - ImportEqualsDeclaration = 247, - ImportDeclaration = 248, - ImportClause = 249, - NamespaceImport = 250, - NamedImports = 251, - ImportSpecifier = 252, - ExportAssignment = 253, - ExportDeclaration = 254, - NamedExports = 255, - ExportSpecifier = 256, - MissingDeclaration = 257, - ExternalModuleReference = 258, - JsxElement = 259, - JsxSelfClosingElement = 260, - JsxOpeningElement = 261, - JsxClosingElement = 262, - JsxFragment = 263, - JsxOpeningFragment = 264, - JsxClosingFragment = 265, - JsxAttribute = 266, - JsxAttributes = 267, - JsxSpreadAttribute = 268, - JsxExpression = 269, - CaseClause = 270, - DefaultClause = 271, - HeritageClause = 272, - CatchClause = 273, - PropertyAssignment = 274, - ShorthandPropertyAssignment = 275, - SpreadAssignment = 276, - EnumMember = 277, - SourceFile = 278, - Bundle = 279, - UnparsedSource = 280, - InputFiles = 281, - JSDocTypeExpression = 282, - JSDocAllType = 283, - JSDocUnknownType = 284, - JSDocNullableType = 285, - JSDocNonNullableType = 286, - JSDocOptionalType = 287, - JSDocFunctionType = 288, - JSDocVariadicType = 289, - JSDocComment = 290, - JSDocTypeLiteral = 291, - JSDocSignature = 292, - JSDocTag = 293, - JSDocAugmentsTag = 294, - JSDocClassTag = 295, - JSDocCallbackTag = 296, - JSDocEnumTag = 297, - JSDocParameterTag = 298, - JSDocReturnTag = 299, - JSDocThisTag = 300, - JSDocTypeTag = 301, - JSDocTemplateTag = 302, - JSDocTypedefTag = 303, - JSDocPropertyTag = 304, - SyntaxList = 305, - NotEmittedStatement = 306, - PartiallyEmittedExpression = 307, - CommaListExpression = 308, - MergeDeclarationMarker = 309, - EndOfDeclarationMarker = 310, - Count = 311, - FirstAssignment = 58, - LastAssignment = 70, - FirstCompoundAssignment = 59, - LastCompoundAssignment = 70, - FirstReservedWord = 72, - LastReservedWord = 107, - FirstKeyword = 72, - LastKeyword = 146, - FirstFutureReservedWord = 108, - LastFutureReservedWord = 116, - FirstTypeNode = 162, - LastTypeNode = 182, - FirstPunctuation = 17, - LastPunctuation = 70, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, FirstToken = 0, - LastToken = 146, + LastToken = 147, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 13, - FirstTemplateToken = 13, - LastTemplateToken = 16, - FirstBinaryOperator = 27, - LastBinaryOperator = 70, - FirstNode = 147, - FirstJSDocNode = 282, - LastJSDocNode = 304, - FirstJSDocTagNode = 293, - LastJSDocTagNode = 304 + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 } enum NodeFlags { None = 0, @@ -1000,6 +1001,9 @@ declare namespace ts { interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -3308,6 +3312,7 @@ declare namespace ts { } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; @@ -3669,6 +3674,7 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; @@ -5269,8 +5275,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5395,6 +5402,7 @@ declare namespace ts { identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -5439,7 +5447,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index fee1057fd2d..ec80d7722e2 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -85,338 +85,339 @@ declare namespace ts { ShebangTrivia = 6, ConflictMarkerTrivia = 7, NumericLiteral = 8, - StringLiteral = 9, - JsxText = 10, - JsxTextAllWhiteSpaces = 11, - RegularExpressionLiteral = 12, - NoSubstitutionTemplateLiteral = 13, - TemplateHead = 14, - TemplateMiddle = 15, - TemplateTail = 16, - OpenBraceToken = 17, - CloseBraceToken = 18, - OpenParenToken = 19, - CloseParenToken = 20, - OpenBracketToken = 21, - CloseBracketToken = 22, - DotToken = 23, - DotDotDotToken = 24, - SemicolonToken = 25, - CommaToken = 26, - LessThanToken = 27, - LessThanSlashToken = 28, - GreaterThanToken = 29, - LessThanEqualsToken = 30, - GreaterThanEqualsToken = 31, - EqualsEqualsToken = 32, - ExclamationEqualsToken = 33, - EqualsEqualsEqualsToken = 34, - ExclamationEqualsEqualsToken = 35, - EqualsGreaterThanToken = 36, - PlusToken = 37, - MinusToken = 38, - AsteriskToken = 39, - AsteriskAsteriskToken = 40, - SlashToken = 41, - PercentToken = 42, - PlusPlusToken = 43, - MinusMinusToken = 44, - LessThanLessThanToken = 45, - GreaterThanGreaterThanToken = 46, - GreaterThanGreaterThanGreaterThanToken = 47, - AmpersandToken = 48, - BarToken = 49, - CaretToken = 50, - ExclamationToken = 51, - TildeToken = 52, - AmpersandAmpersandToken = 53, - BarBarToken = 54, - QuestionToken = 55, - ColonToken = 56, - AtToken = 57, - EqualsToken = 58, - PlusEqualsToken = 59, - MinusEqualsToken = 60, - AsteriskEqualsToken = 61, - AsteriskAsteriskEqualsToken = 62, - SlashEqualsToken = 63, - PercentEqualsToken = 64, - LessThanLessThanEqualsToken = 65, - GreaterThanGreaterThanEqualsToken = 66, - GreaterThanGreaterThanGreaterThanEqualsToken = 67, - AmpersandEqualsToken = 68, - BarEqualsToken = 69, - CaretEqualsToken = 70, - Identifier = 71, - BreakKeyword = 72, - CaseKeyword = 73, - CatchKeyword = 74, - ClassKeyword = 75, - ConstKeyword = 76, - ContinueKeyword = 77, - DebuggerKeyword = 78, - DefaultKeyword = 79, - DeleteKeyword = 80, - DoKeyword = 81, - ElseKeyword = 82, - EnumKeyword = 83, - ExportKeyword = 84, - ExtendsKeyword = 85, - FalseKeyword = 86, - FinallyKeyword = 87, - ForKeyword = 88, - FunctionKeyword = 89, - IfKeyword = 90, - ImportKeyword = 91, - InKeyword = 92, - InstanceOfKeyword = 93, - NewKeyword = 94, - NullKeyword = 95, - ReturnKeyword = 96, - SuperKeyword = 97, - SwitchKeyword = 98, - ThisKeyword = 99, - ThrowKeyword = 100, - TrueKeyword = 101, - TryKeyword = 102, - TypeOfKeyword = 103, - VarKeyword = 104, - VoidKeyword = 105, - WhileKeyword = 106, - WithKeyword = 107, - ImplementsKeyword = 108, - InterfaceKeyword = 109, - LetKeyword = 110, - PackageKeyword = 111, - PrivateKeyword = 112, - ProtectedKeyword = 113, - PublicKeyword = 114, - StaticKeyword = 115, - YieldKeyword = 116, - AbstractKeyword = 117, - AsKeyword = 118, - AnyKeyword = 119, - AsyncKeyword = 120, - AwaitKeyword = 121, - BooleanKeyword = 122, - ConstructorKeyword = 123, - DeclareKeyword = 124, - GetKeyword = 125, - InferKeyword = 126, - IsKeyword = 127, - KeyOfKeyword = 128, - ModuleKeyword = 129, - NamespaceKeyword = 130, - NeverKeyword = 131, - ReadonlyKeyword = 132, - RequireKeyword = 133, - NumberKeyword = 134, - ObjectKeyword = 135, - SetKeyword = 136, - StringKeyword = 137, - SymbolKeyword = 138, - TypeKeyword = 139, - UndefinedKeyword = 140, - UniqueKeyword = 141, - UnknownKeyword = 142, - FromKeyword = 143, - GlobalKeyword = 144, - BigIntKeyword = 145, - OfKeyword = 146, - QualifiedName = 147, - ComputedPropertyName = 148, - TypeParameter = 149, - Parameter = 150, - Decorator = 151, - PropertySignature = 152, - PropertyDeclaration = 153, - MethodSignature = 154, - MethodDeclaration = 155, - Constructor = 156, - GetAccessor = 157, - SetAccessor = 158, - CallSignature = 159, - ConstructSignature = 160, - IndexSignature = 161, - TypePredicate = 162, - TypeReference = 163, - FunctionType = 164, - ConstructorType = 165, - TypeQuery = 166, - TypeLiteral = 167, - ArrayType = 168, - TupleType = 169, - OptionalType = 170, - RestType = 171, - UnionType = 172, - IntersectionType = 173, - ConditionalType = 174, - InferType = 175, - ParenthesizedType = 176, - ThisType = 177, - TypeOperator = 178, - IndexedAccessType = 179, - MappedType = 180, - LiteralType = 181, - ImportType = 182, - ObjectBindingPattern = 183, - ArrayBindingPattern = 184, - BindingElement = 185, - ArrayLiteralExpression = 186, - ObjectLiteralExpression = 187, - PropertyAccessExpression = 188, - ElementAccessExpression = 189, - CallExpression = 190, - NewExpression = 191, - TaggedTemplateExpression = 192, - TypeAssertionExpression = 193, - ParenthesizedExpression = 194, - FunctionExpression = 195, - ArrowFunction = 196, - DeleteExpression = 197, - TypeOfExpression = 198, - VoidExpression = 199, - AwaitExpression = 200, - PrefixUnaryExpression = 201, - PostfixUnaryExpression = 202, - BinaryExpression = 203, - ConditionalExpression = 204, - TemplateExpression = 205, - YieldExpression = 206, - SpreadElement = 207, - ClassExpression = 208, - OmittedExpression = 209, - ExpressionWithTypeArguments = 210, - AsExpression = 211, - NonNullExpression = 212, - MetaProperty = 213, - SyntheticExpression = 214, - TemplateSpan = 215, - SemicolonClassElement = 216, - Block = 217, - VariableStatement = 218, - EmptyStatement = 219, - ExpressionStatement = 220, - IfStatement = 221, - DoStatement = 222, - WhileStatement = 223, - ForStatement = 224, - ForInStatement = 225, - ForOfStatement = 226, - ContinueStatement = 227, - BreakStatement = 228, - ReturnStatement = 229, - WithStatement = 230, - SwitchStatement = 231, - LabeledStatement = 232, - ThrowStatement = 233, - TryStatement = 234, - DebuggerStatement = 235, - VariableDeclaration = 236, - VariableDeclarationList = 237, - FunctionDeclaration = 238, - ClassDeclaration = 239, - InterfaceDeclaration = 240, - TypeAliasDeclaration = 241, - EnumDeclaration = 242, - ModuleDeclaration = 243, - ModuleBlock = 244, - CaseBlock = 245, - NamespaceExportDeclaration = 246, - ImportEqualsDeclaration = 247, - ImportDeclaration = 248, - ImportClause = 249, - NamespaceImport = 250, - NamedImports = 251, - ImportSpecifier = 252, - ExportAssignment = 253, - ExportDeclaration = 254, - NamedExports = 255, - ExportSpecifier = 256, - MissingDeclaration = 257, - ExternalModuleReference = 258, - JsxElement = 259, - JsxSelfClosingElement = 260, - JsxOpeningElement = 261, - JsxClosingElement = 262, - JsxFragment = 263, - JsxOpeningFragment = 264, - JsxClosingFragment = 265, - JsxAttribute = 266, - JsxAttributes = 267, - JsxSpreadAttribute = 268, - JsxExpression = 269, - CaseClause = 270, - DefaultClause = 271, - HeritageClause = 272, - CatchClause = 273, - PropertyAssignment = 274, - ShorthandPropertyAssignment = 275, - SpreadAssignment = 276, - EnumMember = 277, - SourceFile = 278, - Bundle = 279, - UnparsedSource = 280, - InputFiles = 281, - JSDocTypeExpression = 282, - JSDocAllType = 283, - JSDocUnknownType = 284, - JSDocNullableType = 285, - JSDocNonNullableType = 286, - JSDocOptionalType = 287, - JSDocFunctionType = 288, - JSDocVariadicType = 289, - JSDocComment = 290, - JSDocTypeLiteral = 291, - JSDocSignature = 292, - JSDocTag = 293, - JSDocAugmentsTag = 294, - JSDocClassTag = 295, - JSDocCallbackTag = 296, - JSDocEnumTag = 297, - JSDocParameterTag = 298, - JSDocReturnTag = 299, - JSDocThisTag = 300, - JSDocTypeTag = 301, - JSDocTemplateTag = 302, - JSDocTypedefTag = 303, - JSDocPropertyTag = 304, - SyntaxList = 305, - NotEmittedStatement = 306, - PartiallyEmittedExpression = 307, - CommaListExpression = 308, - MergeDeclarationMarker = 309, - EndOfDeclarationMarker = 310, - Count = 311, - FirstAssignment = 58, - LastAssignment = 70, - FirstCompoundAssignment = 59, - LastCompoundAssignment = 70, - FirstReservedWord = 72, - LastReservedWord = 107, - FirstKeyword = 72, - LastKeyword = 146, - FirstFutureReservedWord = 108, - LastFutureReservedWord = 116, - FirstTypeNode = 162, - LastTypeNode = 182, - FirstPunctuation = 17, - LastPunctuation = 70, + BigIntLiteral = 9, + StringLiteral = 10, + JsxText = 11, + JsxTextAllWhiteSpaces = 12, + RegularExpressionLiteral = 13, + NoSubstitutionTemplateLiteral = 14, + TemplateHead = 15, + TemplateMiddle = 16, + TemplateTail = 17, + OpenBraceToken = 18, + CloseBraceToken = 19, + OpenParenToken = 20, + CloseParenToken = 21, + OpenBracketToken = 22, + CloseBracketToken = 23, + DotToken = 24, + DotDotDotToken = 25, + SemicolonToken = 26, + CommaToken = 27, + LessThanToken = 28, + LessThanSlashToken = 29, + GreaterThanToken = 30, + LessThanEqualsToken = 31, + GreaterThanEqualsToken = 32, + EqualsEqualsToken = 33, + ExclamationEqualsToken = 34, + EqualsEqualsEqualsToken = 35, + ExclamationEqualsEqualsToken = 36, + EqualsGreaterThanToken = 37, + PlusToken = 38, + MinusToken = 39, + AsteriskToken = 40, + AsteriskAsteriskToken = 41, + SlashToken = 42, + PercentToken = 43, + PlusPlusToken = 44, + MinusMinusToken = 45, + LessThanLessThanToken = 46, + GreaterThanGreaterThanToken = 47, + GreaterThanGreaterThanGreaterThanToken = 48, + AmpersandToken = 49, + BarToken = 50, + CaretToken = 51, + ExclamationToken = 52, + TildeToken = 53, + AmpersandAmpersandToken = 54, + BarBarToken = 55, + QuestionToken = 56, + ColonToken = 57, + AtToken = 58, + EqualsToken = 59, + PlusEqualsToken = 60, + MinusEqualsToken = 61, + AsteriskEqualsToken = 62, + AsteriskAsteriskEqualsToken = 63, + SlashEqualsToken = 64, + PercentEqualsToken = 65, + LessThanLessThanEqualsToken = 66, + GreaterThanGreaterThanEqualsToken = 67, + GreaterThanGreaterThanGreaterThanEqualsToken = 68, + AmpersandEqualsToken = 69, + BarEqualsToken = 70, + CaretEqualsToken = 71, + Identifier = 72, + BreakKeyword = 73, + CaseKeyword = 74, + CatchKeyword = 75, + ClassKeyword = 76, + ConstKeyword = 77, + ContinueKeyword = 78, + DebuggerKeyword = 79, + DefaultKeyword = 80, + DeleteKeyword = 81, + DoKeyword = 82, + ElseKeyword = 83, + EnumKeyword = 84, + ExportKeyword = 85, + ExtendsKeyword = 86, + FalseKeyword = 87, + FinallyKeyword = 88, + ForKeyword = 89, + FunctionKeyword = 90, + IfKeyword = 91, + ImportKeyword = 92, + InKeyword = 93, + InstanceOfKeyword = 94, + NewKeyword = 95, + NullKeyword = 96, + ReturnKeyword = 97, + SuperKeyword = 98, + SwitchKeyword = 99, + ThisKeyword = 100, + ThrowKeyword = 101, + TrueKeyword = 102, + TryKeyword = 103, + TypeOfKeyword = 104, + VarKeyword = 105, + VoidKeyword = 106, + WhileKeyword = 107, + WithKeyword = 108, + ImplementsKeyword = 109, + InterfaceKeyword = 110, + LetKeyword = 111, + PackageKeyword = 112, + PrivateKeyword = 113, + ProtectedKeyword = 114, + PublicKeyword = 115, + StaticKeyword = 116, + YieldKeyword = 117, + AbstractKeyword = 118, + AsKeyword = 119, + AnyKeyword = 120, + AsyncKeyword = 121, + AwaitKeyword = 122, + BooleanKeyword = 123, + ConstructorKeyword = 124, + DeclareKeyword = 125, + GetKeyword = 126, + InferKeyword = 127, + IsKeyword = 128, + KeyOfKeyword = 129, + ModuleKeyword = 130, + NamespaceKeyword = 131, + NeverKeyword = 132, + ReadonlyKeyword = 133, + RequireKeyword = 134, + NumberKeyword = 135, + ObjectKeyword = 136, + SetKeyword = 137, + StringKeyword = 138, + SymbolKeyword = 139, + TypeKeyword = 140, + UndefinedKeyword = 141, + UniqueKeyword = 142, + UnknownKeyword = 143, + FromKeyword = 144, + GlobalKeyword = 145, + BigIntKeyword = 146, + OfKeyword = 147, + QualifiedName = 148, + ComputedPropertyName = 149, + TypeParameter = 150, + Parameter = 151, + Decorator = 152, + PropertySignature = 153, + PropertyDeclaration = 154, + MethodSignature = 155, + MethodDeclaration = 156, + Constructor = 157, + GetAccessor = 158, + SetAccessor = 159, + CallSignature = 160, + ConstructSignature = 161, + IndexSignature = 162, + TypePredicate = 163, + TypeReference = 164, + FunctionType = 165, + ConstructorType = 166, + TypeQuery = 167, + TypeLiteral = 168, + ArrayType = 169, + TupleType = 170, + OptionalType = 171, + RestType = 172, + UnionType = 173, + IntersectionType = 174, + ConditionalType = 175, + InferType = 176, + ParenthesizedType = 177, + ThisType = 178, + TypeOperator = 179, + IndexedAccessType = 180, + MappedType = 181, + LiteralType = 182, + ImportType = 183, + ObjectBindingPattern = 184, + ArrayBindingPattern = 185, + BindingElement = 186, + ArrayLiteralExpression = 187, + ObjectLiteralExpression = 188, + PropertyAccessExpression = 189, + ElementAccessExpression = 190, + CallExpression = 191, + NewExpression = 192, + TaggedTemplateExpression = 193, + TypeAssertionExpression = 194, + ParenthesizedExpression = 195, + FunctionExpression = 196, + ArrowFunction = 197, + DeleteExpression = 198, + TypeOfExpression = 199, + VoidExpression = 200, + AwaitExpression = 201, + PrefixUnaryExpression = 202, + PostfixUnaryExpression = 203, + BinaryExpression = 204, + ConditionalExpression = 205, + TemplateExpression = 206, + YieldExpression = 207, + SpreadElement = 208, + ClassExpression = 209, + OmittedExpression = 210, + ExpressionWithTypeArguments = 211, + AsExpression = 212, + NonNullExpression = 213, + MetaProperty = 214, + SyntheticExpression = 215, + TemplateSpan = 216, + SemicolonClassElement = 217, + Block = 218, + VariableStatement = 219, + EmptyStatement = 220, + ExpressionStatement = 221, + IfStatement = 222, + DoStatement = 223, + WhileStatement = 224, + ForStatement = 225, + ForInStatement = 226, + ForOfStatement = 227, + ContinueStatement = 228, + BreakStatement = 229, + ReturnStatement = 230, + WithStatement = 231, + SwitchStatement = 232, + LabeledStatement = 233, + ThrowStatement = 234, + TryStatement = 235, + DebuggerStatement = 236, + VariableDeclaration = 237, + VariableDeclarationList = 238, + FunctionDeclaration = 239, + ClassDeclaration = 240, + InterfaceDeclaration = 241, + TypeAliasDeclaration = 242, + EnumDeclaration = 243, + ModuleDeclaration = 244, + ModuleBlock = 245, + CaseBlock = 246, + NamespaceExportDeclaration = 247, + ImportEqualsDeclaration = 248, + ImportDeclaration = 249, + ImportClause = 250, + NamespaceImport = 251, + NamedImports = 252, + ImportSpecifier = 253, + ExportAssignment = 254, + ExportDeclaration = 255, + NamedExports = 256, + ExportSpecifier = 257, + MissingDeclaration = 258, + ExternalModuleReference = 259, + JsxElement = 260, + JsxSelfClosingElement = 261, + JsxOpeningElement = 262, + JsxClosingElement = 263, + JsxFragment = 264, + JsxOpeningFragment = 265, + JsxClosingFragment = 266, + JsxAttribute = 267, + JsxAttributes = 268, + JsxSpreadAttribute = 269, + JsxExpression = 270, + CaseClause = 271, + DefaultClause = 272, + HeritageClause = 273, + CatchClause = 274, + PropertyAssignment = 275, + ShorthandPropertyAssignment = 276, + SpreadAssignment = 277, + EnumMember = 278, + SourceFile = 279, + Bundle = 280, + UnparsedSource = 281, + InputFiles = 282, + JSDocTypeExpression = 283, + JSDocAllType = 284, + JSDocUnknownType = 285, + JSDocNullableType = 286, + JSDocNonNullableType = 287, + JSDocOptionalType = 288, + JSDocFunctionType = 289, + JSDocVariadicType = 290, + JSDocComment = 291, + JSDocTypeLiteral = 292, + JSDocSignature = 293, + JSDocTag = 294, + JSDocAugmentsTag = 295, + JSDocClassTag = 296, + JSDocCallbackTag = 297, + JSDocEnumTag = 298, + JSDocParameterTag = 299, + JSDocReturnTag = 300, + JSDocThisTag = 301, + JSDocTypeTag = 302, + JSDocTemplateTag = 303, + JSDocTypedefTag = 304, + JSDocPropertyTag = 305, + SyntaxList = 306, + NotEmittedStatement = 307, + PartiallyEmittedExpression = 308, + CommaListExpression = 309, + MergeDeclarationMarker = 310, + EndOfDeclarationMarker = 311, + Count = 312, + FirstAssignment = 59, + LastAssignment = 71, + FirstCompoundAssignment = 60, + LastCompoundAssignment = 71, + FirstReservedWord = 73, + LastReservedWord = 108, + FirstKeyword = 73, + LastKeyword = 147, + FirstFutureReservedWord = 109, + LastFutureReservedWord = 117, + FirstTypeNode = 163, + LastTypeNode = 183, + FirstPunctuation = 18, + LastPunctuation = 71, FirstToken = 0, - LastToken = 146, + LastToken = 147, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, - LastLiteralToken = 13, - FirstTemplateToken = 13, - LastTemplateToken = 16, - FirstBinaryOperator = 27, - LastBinaryOperator = 70, - FirstNode = 147, - FirstJSDocNode = 282, - LastJSDocNode = 304, - FirstJSDocTagNode = 293, - LastJSDocTagNode = 304 + LastLiteralToken = 14, + FirstTemplateToken = 14, + LastTemplateToken = 17, + FirstBinaryOperator = 28, + LastBinaryOperator = 71, + FirstNode = 148, + FirstJSDocNode = 283, + LastJSDocNode = 305, + FirstJSDocTagNode = 294, + LastJSDocTagNode = 305 } enum NodeFlags { None = 0, @@ -1000,6 +1001,9 @@ declare namespace ts { interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } + interface BigIntLiteral extends LiteralExpression { + kind: SyntaxKind.BigIntLiteral; + } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; parent: TemplateExpression; @@ -3308,6 +3312,7 @@ declare namespace ts { } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; + function isBigIntLiteral(node: Node): node is BigIntLiteral; function isStringLiteral(node: Node): node is StringLiteral; function isJsxText(node: Node): node is JsxText; function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; @@ -3669,6 +3674,7 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; @@ -5269,8 +5275,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5395,6 +5402,7 @@ declare namespace ts { identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -5439,7 +5447,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols index 94187845fc3..cddcd961338 100644 --- a/tests/baselines/reference/bigintIndex.symbols +++ b/tests/baselines/reference/bigintIndex.symbols @@ -34,7 +34,7 @@ key = "abc"; key = Symbol(); >key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) key = 123n; // should error >key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) @@ -45,7 +45,7 @@ const bigNum: bigint = 0n; const typedArray = new Uint8Array(3); >typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) ->Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --)) typedArray[bigNum] = 0xAA; // should error >typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) @@ -53,7 +53,7 @@ typedArray[bigNum] = 0xAA; // should error typedArray[String(bigNum)] = 0xAA; >typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) ->String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 1 more) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 2 more) >bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) typedArray["1"] = 0xBB; diff --git a/tests/baselines/reference/bigintWithLib.js b/tests/baselines/reference/bigintWithLib.js index e25decf9312..979e0d2b129 100644 --- a/tests/baselines/reference/bigintWithLib.js +++ b/tests/baselines/reference/bigintWithLib.js @@ -52,8 +52,8 @@ bigintVal = dataView.getBigUint64(2, true); let bigintVal = BigInt(123); bigintVal = BigInt("456"); new BigInt(123); // should error -bigintVal = BigInt.asIntN(8, 0xFFFFn); -bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = BigInt.asIntN(8, 0xffffn); +bigintVal = BigInt.asUintN(8, 0xffffn); bigintVal = bigintVal.valueOf(); let stringVal = bigintVal.toString(); stringVal = bigintVal.toString(2); diff --git a/tests/baselines/reference/bigintWithoutLib.errors.txt b/tests/baselines/reference/bigintWithoutLib.errors.txt index d06e99464cd..90a0fdcc31b 100644 --- a/tests/baselines/reference/bigintWithoutLib.errors.txt +++ b/tests/baselines/reference/bigintWithoutLib.errors.txt @@ -2,13 +2,18 @@ tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2304: Cannot find name ' tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2304: Cannot find name 'BigInt'. tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2304: Cannot find name 'BigInt'. tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(7,30): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(8,31): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(9,1): error TS2322: Type 'Object' is not assignable to type 'bigint'. tests/cases/compiler/bigintWithoutLib.ts(11,13): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/bigintWithoutLib.ts(15,18): error TS2304: Cannot find name 'BigInt64Array'. tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(16,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(17,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(17,34): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,38): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,42): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(18,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2304: Cannot find name 'BigInt64Array'. tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2304: Cannot find name 'BigInt64Array'. @@ -17,15 +22,22 @@ tests/cases/compiler/bigintWithoutLib.ts(27,19): error TS2304: Cannot find name tests/cases/compiler/bigintWithoutLib.ts(27,40): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(28,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(29,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(29,36): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,40): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,44): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(30,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(40,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(40,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(41,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(41,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(42,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(43,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(44,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(46,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(47,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. @@ -33,7 +45,7 @@ tests/cases/compiler/bigintWithoutLib.ts(48,22): error TS2339: Property 'getBigU tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. -==== tests/cases/compiler/bigintWithoutLib.ts (33 errors) ==== +==== tests/cases/compiler/bigintWithoutLib.ts (45 errors) ==== // Every line should error because these builtins are not declared // Test BigInt functions @@ -49,9 +61,13 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU bigintVal = BigInt.asIntN(8, 0xFFFFn); ~~~~~~ !!! error TS2304: Cannot find name 'BigInt'. + ~~~~~~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. bigintVal = BigInt.asUintN(8, 0xFFFFn); ~~~~~~ !!! error TS2304: Cannot find name 'BigInt'. + ~~~~~~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} ~~~~~~~~~ !!! error TS2322: Type 'Object' is not assignable to type 'bigint'. @@ -76,6 +92,12 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU ~~~~~~~~~~~~~ !!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? !!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. bigIntArray = new BigInt64Array([1, 2, 3]); ~~~~~~~~~~~~~ !!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? @@ -105,6 +127,12 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU bigUintArray = new BigUint64Array([1n, 2n, 3n]); ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'BigUint64Array'. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. bigUintArray = new BigUint64Array([1, 2, 3]); ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'BigUint64Array'. @@ -126,18 +154,26 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU dataView.setBigInt64(1, -1n); ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. dataView.setBigInt64(1, -1n, true); ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + ~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. dataView.setBigInt64(1, -1); ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. dataView.setBigUint64(2, 123n); ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + ~~~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. dataView.setBigUint64(2, 123n, true); ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + ~~~~ +!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. dataView.setBigUint64(2, 123); ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. diff --git a/tests/baselines/reference/bigintWithoutLib.js b/tests/baselines/reference/bigintWithoutLib.js index 67265ca8720..31a59fcbaf0 100644 --- a/tests/baselines/reference/bigintWithoutLib.js +++ b/tests/baselines/reference/bigintWithoutLib.js @@ -55,8 +55,8 @@ bigintVal = dataView.getBigUint64(2, true); var bigintVal = BigInt(123); bigintVal = BigInt("456"); new BigInt(123); -bigintVal = BigInt.asIntN(8, 0xFFFFn); -bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = BigInt.asIntN(8, 0xffffn); +bigintVal = BigInt.asUintN(8, 0xffffn); bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} var stringVal = bigintVal.toString(); // should not error - bigintVal inferred as {} stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} diff --git a/tests/baselines/reference/numberVsBigIntOperations.js b/tests/baselines/reference/numberVsBigIntOperations.js index c1d448831dc..9d8a4920d0d 100644 --- a/tests/baselines/reference/numberVsBigIntOperations.js +++ b/tests/baselines/reference/numberVsBigIntOperations.js @@ -96,7 +96,7 @@ if (bigZeroOrOne) isOne(bigZeroOrOne); //// [numberVsBigIntOperations.js] // Cannot mix bigints and numbers -var bigInt = 1n, num = 2; +let bigInt = 1n, num = 2; bigInt = 1n; bigInt = 2; num = 1n; @@ -121,10 +121,10 @@ bigInt %= 1n; bigInt %= 2; num %= 1n; num %= 2; -bigInt = Math.pow(bigInt, 1n); -bigInt = Math.pow(bigInt, 2); -num = Math.pow(num, 1n); -num = Math.pow(num, 2); +bigInt **= 1n; +bigInt **= 2; +num **= 1n; +num **= 2; bigInt <<= 1n; bigInt <<= 2; num <<= 1n; @@ -165,10 +165,10 @@ bigInt = 1n % 2n; num = 1 % 2; 1 % 2n; 1n % 2; -bigInt = Math.pow(1n, 2n); -num = Math.pow(1, 2); -Math.pow(1, 2n); -Math.pow(1n, 2); +bigInt = 1n ** 2n; +num = 1 ** 2; +1 ** 2n; +1n ** 2; bigInt = 1n & 2n; num = 1 & 2; 1 & 2n; @@ -190,7 +190,7 @@ num = 1 >> 2; 1 >> 2n; 1n >> 2; // Plus should still coerce to strings -var str; +let str; str = "abc" + 123; str = "abc" + 123n; str = 123 + "abc"; @@ -217,7 +217,7 @@ num = +bigInt; num = +num; num = +"3"; // Comparisons can be mixed -var result; +let result; result = bigInt > num; result = bigInt >= num; result = bigInt < num; @@ -229,12 +229,12 @@ result = bigInt === num; result = bigInt !== num; // Types of arithmetic operations on other types num = "3" & 5; -num = Math.pow(2, false); // should error, but infer number +num = 2 ** false; // should error, but infer number "3" & 5n; -Math.pow(2n, false); // should error, result in any +2n ** false; // should error, result in any num = ~"3"; num = -false; // should infer number -var bigIntOrNumber; +let bigIntOrNumber; bigIntOrNumber + bigIntOrNumber; // should error, result in any bigIntOrNumber << bigIntOrNumber; // should error, result in any if (typeof bigIntOrNumber === "bigint") { @@ -249,7 +249,7 @@ if (typeof bigIntOrNumber === "number") { ~bigIntOrNumber; // should infer number | bigint bigIntOrNumber++; // should infer number | bigint ++bigIntOrNumber; // should infer number | bigint -var anyValue; +let anyValue; anyValue + anyValue; // should infer any anyValue >>> anyValue; // should infer number anyValue ^ anyValue; // should infer number @@ -258,17 +258,17 @@ anyValue ^ anyValue; // should infer number anyValue--; // should infer number --anyValue; // should infer number // Distinguishing numbers from bigints with typeof -var isBigInt = function (x) { return x; }; -var isNumber = function (x) { return x; }; -var zeroOrBigOne; +const isBigInt = (x) => x; +const isNumber = (x) => x; +const zeroOrBigOne; if (typeof zeroOrBigOne === "bigint") isBigInt(zeroOrBigOne); else isNumber(zeroOrBigOne); // Distinguishing truthy from falsy -var isOne = function (x) { return x; }; +const isOne = (x) => x; if (zeroOrBigOne) isOne(zeroOrBigOne); -var bigZeroOrOne; +const bigZeroOrOne; if (bigZeroOrOne) isOne(bigZeroOrOne); diff --git a/tests/baselines/reference/parseBigInt.js b/tests/baselines/reference/parseBigInt.js index ccfa3089f0f..1e8b06743d5 100644 --- a/tests/baselines/reference/parseBigInt.js +++ b/tests/baselines/reference/parseBigInt.js @@ -72,73 +72,73 @@ oneTwoOrThree(0); oneTwoOrThree(1); oneTwoOrThree(2); oneTwoOrThree(3); //// [parseBigInt.js] // All bases should allow "n" suffix -var bin = 5, binBig = 5n; // 5, 5n -var oct = 375, octBig = 375n; // 375, 375n -var hex = 0xC0B, hexBig = 0xC0Bn; // 3083, 3083n -var dec = 123, decBig = 123n; +const bin = 0b101, binBig = 5n; // 5, 5n +const oct = 0o567, octBig = 375n; // 375, 375n +const hex = 0xC0B, hexBig = 0xc0bn; // 3083, 3083n +const dec = 123, decBig = 123n; // Test literals whose values overflow a 53-bit integer // These should be represented exactly in the emitted JS -var largeBin = 384307168202282325n; // 384307168202282325n -var largeOct = 1505852261029722487n; // 1505852261029722487n -var largeDec = 12345678091234567890n; -var largeHex = 0x1234567890abcdefn; // 1311768467294899695n +const largeBin = 384307168202282325n; // 384307168202282325n +const largeOct = 1505852261029722487n; // 1505852261029722487n +const largeDec = 12345678091234567890n; +const largeHex = 0x1234567890abcdefn; // 1311768467294899695n // Test literals with separators -var separatedBin = 21n; // 21n -var separatedOct = 342391n; // 342391n -var separatedDec = 123456789n; -var separatedHex = 0x0abcdefn; // 11259375n +const separatedBin = 21n; // 21n +const separatedOct = 342391n; // 342391n +const separatedDec = 123456789n; +const separatedHex = 0x0abcdefn; // 11259375n // Test parsing literals of different bit sizes // to ensure that parsePseudoBigInt() allocates enough space -var zero = 0n; -var oneBit = 1n; -var twoBit = 3n; // 3n -var threeBit = 7n; // 7n -var fourBit = 15n; // 15n -var fiveBit = 31n; // 31n -var sixBit = 63n; // 63n -var sevenBit = 127n; // 127n -var eightBit = 255n; // 255n -var nineBit = 511n; // 511n -var tenBit = 1023n; // 1023n -var elevenBit = 2047n; // 2047n -var twelveBit = 4095n; // 4095n -var thirteenBit = 8191n; // 8191n -var fourteenBit = 16383n; // 16383n -var fifteenBit = 32767n; // 32767n -var sixteenBit = 65535n; // 65535n -var seventeenBit = 131071n; // 131071n +const zero = 0n; +const oneBit = 1n; +const twoBit = 3n; // 3n +const threeBit = 7n; // 7n +const fourBit = 15n; // 15n +const fiveBit = 31n; // 31n +const sixBit = 63n; // 63n +const sevenBit = 127n; // 127n +const eightBit = 255n; // 255n +const nineBit = 511n; // 511n +const tenBit = 1023n; // 1023n +const elevenBit = 2047n; // 2047n +const twelveBit = 4095n; // 4095n +const thirteenBit = 8191n; // 8191n +const fourteenBit = 16383n; // 16383n +const fifteenBit = 32767n; // 32767n +const sixteenBit = 65535n; // 65535n +const seventeenBit = 131071n; // 131071n // Test negative literals -var neg = -123n; -var negHex = -0x10n; +const neg = -123n; +const negHex = -0x10n; // Test normalization of bigints -- all of these should succeed -var negZero = -0n; -var baseChange = 0xFFn; -var leadingZeros = 0x000000FFn; +const negZero = -0n; +const baseChange = 0xffn; +const leadingZeros = 0x000000ffn; // Plus not allowed on literals -var unaryPlus = +123n; -var unaryPlusHex = +0x123n; +const unaryPlus = +123n; +const unaryPlusHex = +0x123n; // Parsing errors // In separate blocks because they each declare an "n" variable { - var legacyOct = 0123, n; + const legacyOct = 0123, n; } { - var scientific = 1e2, n; + const scientific = 1e2, n; } { - var decimal = 4.1, n; + const decimal = 4.1, n; } { - var leadingDecimal = .1, n; + const leadingDecimal = .1, n; } -var emptyBinary = 0n; // should error but infer 0n -var emptyOct = 0n; // should error but infer 0n -var emptyHex = 0xn; // should error but infer 0n -var leadingSeparator = _123n; -var trailingSeparator = 123n; -var doubleSeparator = 123456789n; +const emptyBinary = 0n; // should error but infer 0n +const emptyOct = 0n; // should error but infer 0n +const emptyHex = 0x0n; // should error but infer 0n +const leadingSeparator = _123n; +const trailingSeparator = 123n; +const doubleSeparator = 123456789n; // Using literals as types -var oneTwoOrThree = function (x) { return Math.pow(x, 2n); }; +const oneTwoOrThree = (x) => x ** 2n; oneTwoOrThree(0n); oneTwoOrThree(1n); oneTwoOrThree(2n); diff --git a/tests/baselines/reference/parseBigInt.types b/tests/baselines/reference/parseBigInt.types index 9e9025b6221..cbf80b69db0 100644 --- a/tests/baselines/reference/parseBigInt.types +++ b/tests/baselines/reference/parseBigInt.types @@ -162,13 +162,13 @@ const leadingZeros: 0xFFn = 0x000000FFn; // Plus not allowed on literals const unaryPlus = +123n; ->unaryPlus : 123n ->+123n : 123n +>unaryPlus : number +>+123n : number >123n : 123n const unaryPlusHex = +0x123n; ->unaryPlusHex : 291n ->+0x123n : 291n +>unaryPlusHex : number +>+0x123n : number >0x123n : 291n // Parsing errors diff --git a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json index 778fb9572f4..7d444ecc45f 100644 --- a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json index 16462f9d660..43836a779ad 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json @@ -56,7 +56,7 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ /* Advanced Options */ "noErrorTruncation": true, /* Do not truncate error messages. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json index fa8e2c70a66..73e0564f2ad 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json index 2d2d84b100c..51fd4e44cf9 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json index 68329ceecb5..dd8f183c32e 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json @@ -56,7 +56,7 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ }, "files": [ "file0.st", diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json index eb13052b37c..de16ddfba0c 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json index 778fb9572f4..7d444ecc45f 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json index c9afe008935..587d9941a70 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json index 37444c9a5de..75621cafebc 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json @@ -56,6 +56,6 @@ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt expressions. */ + // "experimentalBigInt": true, /* Enables experimental support for ESNext BigInt literals. */ } } \ No newline at end of file diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.js b/tests/baselines/reference/warnExperimentalBigIntLiteral.js index 7f31a794ec2..8516350ddbf 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.js +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.js @@ -5,7 +5,7 @@ let bigintLiteralType: 123n; // should error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error //// [warnExperimentalBigIntLiteral.js] -var normalNumber = 123; // should not error -var bigintType; // should not error -var bigintLiteralType; // should error when used as type -var bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error +const normalNumber = 123; // should not error +let bigintType; // should not error +let bigintLiteralType; // should error when used as type +const bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error diff --git a/tests/cases/compiler/bigintIndex.ts b/tests/cases/compiler/bigintIndex.ts index ca467d58c0e..17a4db01778 100644 --- a/tests/cases/compiler/bigintIndex.ts +++ b/tests/cases/compiler/bigintIndex.ts @@ -1,4 +1,4 @@ -// @target: es2015 +// @target: esnext // @experimentalBigInt: true interface BigIntIndex { diff --git a/tests/cases/compiler/numberVsBigIntOperations.ts b/tests/cases/compiler/numberVsBigIntOperations.ts index b2f337b00b9..e6b87e57e13 100644 --- a/tests/cases/compiler/numberVsBigIntOperations.ts +++ b/tests/cases/compiler/numberVsBigIntOperations.ts @@ -1,4 +1,5 @@ // @experimentalBigInt: true +// @target: esnext // Cannot mix bigints and numbers let bigInt = 1n, num = 2; diff --git a/tests/cases/compiler/parseBigInt.ts b/tests/cases/compiler/parseBigInt.ts index 35cc13151ad..05ee6bfd7ac 100644 --- a/tests/cases/compiler/parseBigInt.ts +++ b/tests/cases/compiler/parseBigInt.ts @@ -1,4 +1,5 @@ // @experimentalBigInt: true +// @target: esnext // All bases should allow "n" suffix const bin = 0b101, binBig = 0b101n; // 5, 5n diff --git a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts index 2b4954bef3d..c9f94fcc992 100644 --- a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts +++ b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts @@ -1,3 +1,5 @@ +// @target: esnext + const normalNumber = 123; // should not error let bigintType: bigint; // should not error let bigintLiteralType: 123n; // should error when used as type From 6f97fb5f022980651a187cf5dd048f674584c164 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Fri, 2 Nov 2018 18:29:52 -0700 Subject: [PATCH 217/262] Fix error numbers --- .../reference/bigintWithoutLib.errors.txt | 48 +++++++++---------- .../numberVsBigIntOperations.errors.txt | 8 ++-- .../reference/parseBigInt.errors.txt | 8 ++-- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/baselines/reference/bigintWithoutLib.errors.txt b/tests/baselines/reference/bigintWithoutLib.errors.txt index 90a0fdcc31b..2647a06634f 100644 --- a/tests/baselines/reference/bigintWithoutLib.errors.txt +++ b/tests/baselines/reference/bigintWithoutLib.errors.txt @@ -2,18 +2,18 @@ tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2304: Cannot find name ' tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2304: Cannot find name 'BigInt'. tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2304: Cannot find name 'BigInt'. tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2304: Cannot find name 'BigInt'. -tests/cases/compiler/bigintWithoutLib.ts(7,30): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(7,30): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2304: Cannot find name 'BigInt'. -tests/cases/compiler/bigintWithoutLib.ts(8,31): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(8,31): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(9,1): error TS2322: Type 'Object' is not assignable to type 'bigint'. tests/cases/compiler/bigintWithoutLib.ts(11,13): error TS2554: Expected 0 arguments, but got 1. tests/cases/compiler/bigintWithoutLib.ts(15,18): error TS2304: Cannot find name 'BigInt64Array'. tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(16,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(17,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? -tests/cases/compiler/bigintWithoutLib.ts(17,34): error TS2736: BigInt literals are not available when targetting lower than ESNext. -tests/cases/compiler/bigintWithoutLib.ts(17,38): error TS2736: BigInt literals are not available when targetting lower than ESNext. -tests/cases/compiler/bigintWithoutLib.ts(17,42): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,34): error TS2737: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,38): error TS2737: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,42): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(18,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2304: Cannot find name 'BigInt64Array'. tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2304: Cannot find name 'BigInt64Array'. @@ -22,22 +22,22 @@ tests/cases/compiler/bigintWithoutLib.ts(27,19): error TS2304: Cannot find name tests/cases/compiler/bigintWithoutLib.ts(27,40): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(28,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(29,20): error TS2304: Cannot find name 'BigUint64Array'. -tests/cases/compiler/bigintWithoutLib.ts(29,36): error TS2736: BigInt literals are not available when targetting lower than ESNext. -tests/cases/compiler/bigintWithoutLib.ts(29,40): error TS2736: BigInt literals are not available when targetting lower than ESNext. -tests/cases/compiler/bigintWithoutLib.ts(29,44): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,36): error TS2737: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,40): error TS2737: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,44): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(30,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2304: Cannot find name 'BigUint64Array'. tests/cases/compiler/bigintWithoutLib.ts(40,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. -tests/cases/compiler/bigintWithoutLib.ts(40,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(40,26): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(41,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. -tests/cases/compiler/bigintWithoutLib.ts(41,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(41,26): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(42,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. -tests/cases/compiler/bigintWithoutLib.ts(43,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(43,26): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. -tests/cases/compiler/bigintWithoutLib.ts(44,26): error TS2736: BigInt literals are not available when targetting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(44,26): error TS2737: BigInt literals are not available when targetting lower than ESNext. tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(46,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. tests/cases/compiler/bigintWithoutLib.ts(47,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. @@ -62,12 +62,12 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU ~~~~~~ !!! error TS2304: Cannot find name 'BigInt'. ~~~~~~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. bigintVal = BigInt.asUintN(8, 0xFFFFn); ~~~~~~ !!! error TS2304: Cannot find name 'BigInt'. ~~~~~~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} ~~~~~~~~~ !!! error TS2322: Type 'Object' is not assignable to type 'bigint'. @@ -93,11 +93,11 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU !!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? !!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. bigIntArray = new BigInt64Array([1, 2, 3]); ~~~~~~~~~~~~~ !!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? @@ -128,11 +128,11 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'BigUint64Array'. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. bigUintArray = new BigUint64Array([1, 2, 3]); ~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'BigUint64Array'. @@ -155,12 +155,12 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. dataView.setBigInt64(1, -1n, true); ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. ~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. dataView.setBigInt64(1, -1); ~~~~~~~~~~~ !!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. @@ -168,12 +168,12 @@ tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigU ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. ~~~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. dataView.setBigUint64(2, 123n, true); ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. ~~~~ -!!! error TS2736: BigInt literals are not available when targetting lower than ESNext. +!!! error TS2737: BigInt literals are not available when targetting lower than ESNext. dataView.setBigUint64(2, 123); ~~~~~~~~~~~~ !!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. diff --git a/tests/baselines/reference/numberVsBigIntOperations.errors.txt b/tests/baselines/reference/numberVsBigIntOperations.errors.txt index 58d19e6f7b9..fbd49ddd091 100644 --- a/tests/baselines/reference/numberVsBigIntOperations.errors.txt +++ b/tests/baselines/reference/numberVsBigIntOperations.errors.txt @@ -46,7 +46,7 @@ tests/cases/compiler/numberVsBigIntOperations.ts(25,34): error TS2365: Operator tests/cases/compiler/numberVsBigIntOperations.ts(25,43): error TS2365: Operator '>>' cannot be applied to types '1n' and '2'. tests/cases/compiler/numberVsBigIntOperations.ts(38,1): error TS2365: Operator '>>>=' cannot be applied to types 'bigint' and '1n'. tests/cases/compiler/numberVsBigIntOperations.ts(39,10): error TS2365: Operator '>>>' cannot be applied to types 'bigint' and '1n'. -tests/cases/compiler/numberVsBigIntOperations.ts(40,8): error TS2735: Operator '+' cannot be applied to type 'bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(40,8): error TS2736: Operator '+' cannot be applied to type 'bigint'. tests/cases/compiler/numberVsBigIntOperations.ts(50,10): error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. tests/cases/compiler/numberVsBigIntOperations.ts(51,10): error TS2367: This condition will always return 'true' since the types 'bigint' and 'number' have no overlap. tests/cases/compiler/numberVsBigIntOperations.ts(52,10): error TS2367: This condition will always return 'false' since the types 'bigint' and 'number' have no overlap. @@ -59,7 +59,7 @@ tests/cases/compiler/numberVsBigIntOperations.ts(57,11): error TS2365: Operator tests/cases/compiler/numberVsBigIntOperations.ts(57,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/numberVsBigIntOperations.ts(60,1): error TS2365: Operator '+' cannot be applied to types 'number | bigint' and 'number | bigint'. tests/cases/compiler/numberVsBigIntOperations.ts(61,1): error TS2365: Operator '<<' cannot be applied to types 'number | bigint' and 'number | bigint'. -tests/cases/compiler/numberVsBigIntOperations.ts(70,2): error TS2735: Operator '+' cannot be applied to type 'number | bigint'. +tests/cases/compiler/numberVsBigIntOperations.ts(70,2): error TS2736: Operator '+' cannot be applied to type 'number | bigint'. tests/cases/compiler/numberVsBigIntOperations.ts(86,7): error TS1155: 'const' declarations must be initialized. tests/cases/compiler/numberVsBigIntOperations.ts(93,7): error TS1155: 'const' declarations must be initialized. @@ -202,7 +202,7 @@ tests/cases/compiler/numberVsBigIntOperations.ts(93,7): error TS1155: 'const' de !!! error TS2365: Operator '>>>' cannot be applied to types 'bigint' and '1n'. num = +bigInt; num = +num; num = +"3"; ~~~~~~ -!!! error TS2735: Operator '+' cannot be applied to type 'bigint'. +!!! error TS2736: Operator '+' cannot be applied to type 'bigint'. // Comparisons can be mixed let result: boolean; @@ -258,7 +258,7 @@ tests/cases/compiler/numberVsBigIntOperations.ts(93,7): error TS1155: 'const' de } +bigIntOrNumber; // should error, result in number ~~~~~~~~~~~~~~ -!!! error TS2735: Operator '+' cannot be applied to type 'number | bigint'. +!!! error TS2736: Operator '+' cannot be applied to type 'number | bigint'. ~bigIntOrNumber; // should infer number | bigint bigIntOrNumber++; // should infer number | bigint ++bigIntOrNumber; // should infer number | bigint diff --git a/tests/baselines/reference/parseBigInt.errors.txt b/tests/baselines/reference/parseBigInt.errors.txt index ea4ca01f5e1..9c273542c0b 100644 --- a/tests/baselines/reference/parseBigInt.errors.txt +++ b/tests/baselines/reference/parseBigInt.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/parseBigInt.ts(51,20): error TS2735: Operator '+' cannot be applied to type '123n'. -tests/cases/compiler/parseBigInt.ts(52,23): error TS2735: Operator '+' cannot be applied to type '291n'. +tests/cases/compiler/parseBigInt.ts(51,20): error TS2736: Operator '+' cannot be applied to type '123n'. +tests/cases/compiler/parseBigInt.ts(52,23): error TS2736: Operator '+' cannot be applied to type '291n'. tests/cases/compiler/parseBigInt.ts(56,25): error TS1005: ',' expected. tests/cases/compiler/parseBigInt.ts(57,25): error TS1005: ',' expected. tests/cases/compiler/parseBigInt.ts(58,22): error TS1005: ',' expected. @@ -70,10 +70,10 @@ tests/cases/compiler/parseBigInt.ts(70,72): error TS2345: Argument of type '3' i // Plus not allowed on literals const unaryPlus = +123n; ~~~~ -!!! error TS2735: Operator '+' cannot be applied to type '123n'. +!!! error TS2736: Operator '+' cannot be applied to type '123n'. const unaryPlusHex = +0x123n; ~~~~~~ -!!! error TS2735: Operator '+' cannot be applied to type '291n'. +!!! error TS2736: Operator '+' cannot be applied to type '291n'. // Parsing errors // In separate blocks because they each declare an "n" variable From ecd12453f42cd95503bfd0a56a67b732a0ea83d4 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Fri, 2 Nov 2018 21:32:43 -0700 Subject: [PATCH 218/262] Add test for bigint property --- .../reference/bigintIndex.errors.txt | 34 ++++++++-- tests/baselines/reference/bigintIndex.js | 24 ++++++- tests/baselines/reference/bigintIndex.symbols | 65 ++++++++++++------- tests/baselines/reference/bigintIndex.types | 25 ++++++- tests/cases/compiler/bigintIndex.ts | 10 ++- 5 files changed, 122 insertions(+), 36 deletions(-) diff --git a/tests/baselines/reference/bigintIndex.errors.txt b/tests/baselines/reference/bigintIndex.errors.txt index a862f44e658..50e360a1905 100644 --- a/tests/baselines/reference/bigintIndex.errors.txt +++ b/tests/baselines/reference/bigintIndex.errors.txt @@ -1,10 +1,15 @@ -tests/cases/compiler/bigintIndex.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/bigintIndex.ts(8,11): error TS2538: Type '1n' cannot be used as an index type. -tests/cases/compiler/bigintIndex.ts(14,1): error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. -tests/cases/compiler/bigintIndex.ts(19,12): error TS2538: Type 'bigint' cannot be used as an index type. +tests/cases/compiler/a.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/a.ts(8,11): error TS2538: Type '1n' cannot be used as an index type. +tests/cases/compiler/a.ts(14,1): error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. +tests/cases/compiler/a.ts(19,12): error TS2538: Type 'bigint' cannot be used as an index type. +tests/cases/compiler/b.ts(2,12): error TS1136: Property assignment expected. +tests/cases/compiler/b.ts(2,14): error TS1005: ';' expected. +tests/cases/compiler/b.ts(2,19): error TS1128: Declaration or statement expected. +tests/cases/compiler/b.ts(3,12): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/b.ts(4,12): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. -==== tests/cases/compiler/bigintIndex.ts (4 errors) ==== +==== tests/cases/compiler/a.ts (4 errors) ==== interface BigIntIndex { [index: bigint]: E; // should error ~~~~~ @@ -34,4 +39,21 @@ tests/cases/compiler/bigintIndex.ts(19,12): error TS2538: Type 'bigint' cannot b !!! error TS2538: Type 'bigint' cannot be used as an index type. typedArray[String(bigNum)] = 0xAA; typedArray["1"] = 0xBB; - typedArray[2] = 0xCC; \ No newline at end of file + typedArray[2] = 0xCC; + + // {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +==== tests/cases/compiler/b.ts (5 errors) ==== + // BigInt cannot be used as an object literal property + const a = {1n: 123}; + ~~ +!!! error TS1136: Property assignment expected. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + const b = {[1n]: 456}; + ~~~~ +!!! error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. + const c = {[bigNum]: 789}; + ~~~~~~~~ +!!! error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. \ No newline at end of file diff --git a/tests/baselines/reference/bigintIndex.js b/tests/baselines/reference/bigintIndex.js index 9f87ad8a8aa..abf2159996e 100644 --- a/tests/baselines/reference/bigintIndex.js +++ b/tests/baselines/reference/bigintIndex.js @@ -1,4 +1,6 @@ -//// [bigintIndex.ts] +//// [tests/cases/compiler/bigintIndex.ts] //// + +//// [a.ts] interface BigIntIndex { [index: bigint]: E; // should error } @@ -20,9 +22,16 @@ const typedArray = new Uint8Array(3); typedArray[bigNum] = 0xAA; // should error typedArray[String(bigNum)] = 0xAA; typedArray["1"] = 0xBB; -typedArray[2] = 0xCC; +typedArray[2] = 0xCC; + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +//// [b.ts] +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +const b = {[1n]: 456}; +const c = {[bigNum]: 789}; -//// [bigintIndex.js] +//// [a.js] const arr = [1, 2, 3]; let num = arr[1]; num = arr["1"]; @@ -39,3 +48,12 @@ typedArray[bigNum] = 0xAA; // should error typedArray[String(bigNum)] = 0xAA; typedArray["1"] = 0xBB; typedArray[2] = 0xCC; +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +//// [b.js] +// BigInt cannot be used as an object literal property +const a = {}; +1n; +123; +; +const b = { [1n]: 456 }; +const c = { [bigNum]: 789 }; diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols index cddcd961338..c115a0f9daf 100644 --- a/tests/baselines/reference/bigintIndex.symbols +++ b/tests/baselines/reference/bigintIndex.symbols @@ -1,64 +1,79 @@ -=== tests/cases/compiler/bigintIndex.ts === +=== tests/cases/compiler/a.ts === interface BigIntIndex { ->BigIntIndex : Symbol(BigIntIndex, Decl(bigintIndex.ts, 0, 0)) ->E : Symbol(E, Decl(bigintIndex.ts, 0, 22)) +>BigIntIndex : Symbol(BigIntIndex, Decl(a.ts, 0, 0)) +>E : Symbol(E, Decl(a.ts, 0, 22)) [index: bigint]: E; // should error ->index : Symbol(index, Decl(bigintIndex.ts, 1, 5)) ->E : Symbol(E, Decl(bigintIndex.ts, 0, 22)) +>index : Symbol(index, Decl(a.ts, 1, 5)) +>E : Symbol(E, Decl(a.ts, 0, 22)) } const arr: number[] = [1, 2, 3]; ->arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) let num: number = arr[1]; ->num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) ->arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) num = arr["1"]; ->num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) ->arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) num = arr[1n]; // should error ->num : Symbol(num, Decl(bigintIndex.ts, 5, 3)) ->arr : Symbol(arr, Decl(bigintIndex.ts, 4, 5)) +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) let key: keyof any; // should be type "string | number | symbol" ->key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>key : Symbol(key, Decl(a.ts, 9, 3)) key = 123; ->key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>key : Symbol(key, Decl(a.ts, 9, 3)) key = "abc"; ->key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>key : Symbol(key, Decl(a.ts, 9, 3)) key = Symbol(); ->key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>key : Symbol(key, Decl(a.ts, 9, 3)) >Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) key = 123n; // should error ->key : Symbol(key, Decl(bigintIndex.ts, 9, 3)) +>key : Symbol(key, Decl(a.ts, 9, 3)) // Show correct usage of bigint index: explicitly convert to string const bigNum: bigint = 0n; ->bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) const typedArray = new Uint8Array(3); ->typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) >Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --)) typedArray[bigNum] = 0xAA; // should error ->typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) ->bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) typedArray[String(bigNum)] = 0xAA; ->typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) >String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 2 more) ->bigNum : Symbol(bigNum, Decl(bigintIndex.ts, 16, 5)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) typedArray["1"] = 0xBB; ->typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) typedArray[2] = 0xCC; ->typedArray : Symbol(typedArray, Decl(bigintIndex.ts, 17, 5)) +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +=== tests/cases/compiler/b.ts === +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +>a : Symbol(a, Decl(b.ts, 1, 5)) + +const b = {[1n]: 456}; +>b : Symbol(b, Decl(b.ts, 2, 5)) +>[1n] : Symbol([1n], Decl(b.ts, 2, 11)) + +const c = {[bigNum]: 789}; +>c : Symbol(c, Decl(b.ts, 3, 5)) +>[bigNum] : Symbol([bigNum], Decl(b.ts, 3, 11)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) diff --git a/tests/baselines/reference/bigintIndex.types b/tests/baselines/reference/bigintIndex.types index 0de1940b77c..a70c1f9aec5 100644 --- a/tests/baselines/reference/bigintIndex.types +++ b/tests/baselines/reference/bigintIndex.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/bigintIndex.ts === +=== tests/cases/compiler/a.ts === interface BigIntIndex { [index: bigint]: E; // should error >index : bigint @@ -96,3 +96,26 @@ typedArray[2] = 0xCC; >2 : 2 >0xCC : 204 +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +=== tests/cases/compiler/b.ts === +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +>a : {} +>{ : {} +>1n : 1n +>123 : 123 + +const b = {[1n]: 456}; +>b : {} +>{[1n]: 456} : {} +>[1n] : number +>1n : 1n +>456 : 456 + +const c = {[bigNum]: 789}; +>c : {} +>{[bigNum]: 789} : {} +>[bigNum] : number +>bigNum : bigint +>789 : 789 + diff --git a/tests/cases/compiler/bigintIndex.ts b/tests/cases/compiler/bigintIndex.ts index 17a4db01778..78bb24be441 100644 --- a/tests/cases/compiler/bigintIndex.ts +++ b/tests/cases/compiler/bigintIndex.ts @@ -1,6 +1,7 @@ // @target: esnext // @experimentalBigInt: true +// @filename: a.ts interface BigIntIndex { [index: bigint]: E; // should error } @@ -22,4 +23,11 @@ const typedArray = new Uint8Array(3); typedArray[bigNum] = 0xAA; // should error typedArray[String(bigNum)] = 0xAA; typedArray["1"] = 0xBB; -typedArray[2] = 0xCC; \ No newline at end of file +typedArray[2] = 0xCC; + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +// @filename: b.ts +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +const b = {[1n]: 456}; +const c = {[bigNum]: 789}; \ No newline at end of file From 6c59a3b890fc06b0d391865dab2ae3ccbafc4a90 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Mon, 5 Nov 2018 11:29:11 -0800 Subject: [PATCH 219/262] Fix ambient initializer emit for bigint --- src/compiler/checker.ts | 22 +++++++++++---- .../reference/bigintWithLib.errors.txt | 8 +++++- tests/baselines/reference/bigintWithLib.js | 27 ++++++++++++++++++- .../baselines/reference/bigintWithLib.symbols | 13 +++++++++ tests/baselines/reference/bigintWithLib.types | 18 +++++++++++++ tests/cases/compiler/bigintWithLib.ts | 9 ++++++- 6 files changed, 89 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a16cab1443c..308f3a61b2c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -30128,6 +30128,12 @@ namespace ts { (expr).operand.kind === SyntaxKind.NumericLiteral; } + function isBigIntLiteralExpression(expr: Expression) { + return expr.kind === SyntaxKind.BigIntLiteral || + expr.kind === SyntaxKind.PrefixUnaryExpression && (expr).operator === SyntaxKind.MinusToken && + (expr).operand.kind === SyntaxKind.BigIntLiteral; + } + function isSimpleLiteralEnumReference(expr: Expression) { if ( (isPropertyAccessExpression(expr) || (isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && @@ -30136,19 +30142,25 @@ namespace ts { } function checkAmbientInitializer(node: VariableDeclaration | PropertyDeclaration | PropertySignature) { - if (node.initializer) { - const isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer) || node.initializer.kind === SyntaxKind.TrueKeyword || node.initializer.kind === SyntaxKind.FalseKeyword); + const {initializer} = node; + if (initializer) { + const isInvalidInitializer = !( + isStringOrNumberLiteralExpression(initializer) || + isSimpleLiteralEnumReference(initializer) || + initializer.kind === SyntaxKind.TrueKeyword || initializer.kind === SyntaxKind.FalseKeyword || + isBigIntLiteralExpression(initializer) + ); const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); if (isConstOrReadonly && !node.type) { if (isInvalidInitializer) { - return grammarErrorOnNode(node.initializer!, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); + return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); } } else { - return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } if (!isConstOrReadonly || isInvalidInitializer) { - return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + return grammarErrorOnNode(initializer, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } } } diff --git a/tests/baselines/reference/bigintWithLib.errors.txt b/tests/baselines/reference/bigintWithLib.errors.txt index a24f6ac4802..18267e6ffdf 100644 --- a/tests/baselines/reference/bigintWithLib.errors.txt +++ b/tests/baselines/reference/bigintWithLib.errors.txt @@ -74,4 +74,10 @@ tests/cases/compiler/bigintWithLib.ts(43,26): error TS2345: Argument of type '12 bigintVal = dataView.getBigInt64(1); bigintVal = dataView.getBigInt64(1, true); bigintVal = dataView.getBigUint64(2); - bigintVal = dataView.getBigUint64(2, true); \ No newline at end of file + bigintVal = dataView.getBigUint64(2, true); + + // Test emitted declarations files + const w = 12n; // should emit as const w = 12n + const x = -12n; // should emit as const x = -12n + const y: 12n = 12n; // should emit type 12n + let z = 12n; // should emit type bigint in declaration file \ No newline at end of file diff --git a/tests/baselines/reference/bigintWithLib.js b/tests/baselines/reference/bigintWithLib.js index 979e0d2b129..754b2144f0c 100644 --- a/tests/baselines/reference/bigintWithLib.js +++ b/tests/baselines/reference/bigintWithLib.js @@ -45,7 +45,13 @@ dataView.setBigUint64(2, 123); // should error bigintVal = dataView.getBigInt64(1); bigintVal = dataView.getBigInt64(1, true); bigintVal = dataView.getBigUint64(2); -bigintVal = dataView.getBigUint64(2, true); +bigintVal = dataView.getBigUint64(2, true); + +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +const x = -12n; // should emit as const x = -12n +const y: 12n = 12n; // should emit type 12n +let z = 12n; // should emit type bigint in declaration file //// [bigintWithLib.js] // Test BigInt functions @@ -92,3 +98,22 @@ bigintVal = dataView.getBigInt64(1); bigintVal = dataView.getBigInt64(1, true); bigintVal = dataView.getBigUint64(2); bigintVal = dataView.getBigUint64(2, true); +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +const x = -12n; // should emit as const x = -12n +const y = 12n; // should emit type 12n +let z = 12n; // should emit type bigint in declaration file + + +//// [bigintWithLib.d.ts] +declare let bigintVal: bigint; +declare let stringVal: string; +declare let bigIntArray: BigInt64Array; +declare let len: number; +declare let arrayBufferLike: ArrayBufferView; +declare let bigUintArray: BigUint64Array; +declare const dataView: DataView; +declare const w = 12n; +declare const x = -12n; +declare const y: 12n; +declare let z: bigint; diff --git a/tests/baselines/reference/bigintWithLib.symbols b/tests/baselines/reference/bigintWithLib.symbols index 0f313251ab0..cdc80161a45 100644 --- a/tests/baselines/reference/bigintWithLib.symbols +++ b/tests/baselines/reference/bigintWithLib.symbols @@ -204,3 +204,16 @@ bigintVal = dataView.getBigUint64(2, true); >dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) >getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +>w : Symbol(w, Decl(bigintWithLib.ts, 49, 5)) + +const x = -12n; // should emit as const x = -12n +>x : Symbol(x, Decl(bigintWithLib.ts, 50, 5)) + +const y: 12n = 12n; // should emit type 12n +>y : Symbol(y, Decl(bigintWithLib.ts, 51, 5)) + +let z = 12n; // should emit type bigint in declaration file +>z : Symbol(z, Decl(bigintWithLib.ts, 52, 3)) + diff --git a/tests/baselines/reference/bigintWithLib.types b/tests/baselines/reference/bigintWithLib.types index 5ba273091b6..a1d79119cf6 100644 --- a/tests/baselines/reference/bigintWithLib.types +++ b/tests/baselines/reference/bigintWithLib.types @@ -332,3 +332,21 @@ bigintVal = dataView.getBigUint64(2, true); >2 : 2 >true : true +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +>w : 12n +>12n : 12n + +const x = -12n; // should emit as const x = -12n +>x : -12n +>-12n : -12n +>12n : 12n + +const y: 12n = 12n; // should emit type 12n +>y : 12n +>12n : 12n + +let z = 12n; // should emit type bigint in declaration file +>z : bigint +>12n : 12n + diff --git a/tests/cases/compiler/bigintWithLib.ts b/tests/cases/compiler/bigintWithLib.ts index 3299b1ecc83..0cefd3094d4 100644 --- a/tests/cases/compiler/bigintWithLib.ts +++ b/tests/cases/compiler/bigintWithLib.ts @@ -1,5 +1,6 @@ // @experimentalBigInt: true // @target: esnext +// @declaration: true // Test BigInt functions let bigintVal: bigint = BigInt(123); @@ -47,4 +48,10 @@ dataView.setBigUint64(2, 123); // should error bigintVal = dataView.getBigInt64(1); bigintVal = dataView.getBigInt64(1, true); bigintVal = dataView.getBigUint64(2); -bigintVal = dataView.getBigUint64(2, true); \ No newline at end of file +bigintVal = dataView.getBigUint64(2, true); + +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +const x = -12n; // should emit as const x = -12n +const y: 12n = 12n; // should emit type 12n +let z = 12n; // should emit type bigint in declaration file \ No newline at end of file From 23e7330ddb47314ac186f2826c346db4ab85cd8b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 5 Nov 2018 12:16:55 -0800 Subject: [PATCH 220/262] When removing old diagnostics for files referencing modules that export affected file with signature change, delete the diagnostics of the module as well as anything that exports that module Fixes #28328 --- src/compiler/builder.ts | 30 ++++++++++- src/testRunner/unittests/tscWatchMode.ts | 63 ++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index fbc2dc3f7d2..0fe147def8c 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -225,7 +225,35 @@ namespace ts { */ function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path) { return forEachEntry(state.referencedMap!, (referencesInFile, filePath) => - referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOf(state, filePath as Path) + referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath as Path) + ); + } + + /** + * Removes semantic diagnostics of file and anything that exports this file + */ + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state: BuilderProgramState, filePath: Path): boolean { + if (removeSemanticDiagnosticsOf(state, filePath)) { + // If there are no more diagnostics from old cache, done + return true; + } + + Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + // Go through exported modules from cache first + // If exported modules has path, all files referencing file exported from are affected + if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => + exportedModules && + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path) + )) { + return true; + } + + // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected + return !!forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) => + !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it + exportedModules.has(filePath) && + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path) ); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index 3523db7544f..e60e50dacc7 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1472,6 +1472,69 @@ foo().hello` checkProgramActualFiles(watch(), [aFile.path, libFile.path]); checkOutputErrorsIncremental(host, emptyArray); }); + + it("updates errors when file transitively exported file changes", () => { + const projectLocation = "/user/username/projects/myproject"; + const config: File = { + path: `${projectLocation}/tsconfig.json`, + content: JSON.stringify({ + files: ["app.ts"], + compilerOptions: { baseUrl: "." } + }) + }; + const app: File = { + path: `${projectLocation}/app.ts`, + content: `import { Data } from "lib2/public"; +export class App { + public constructor() { + new Data().test(); + } +}` + }; + const lib2Public: File = { + path: `${projectLocation}/lib2/public.ts`, + content: `export * from "./data";` + }; + const lib2Data: File = { + path: `${projectLocation}/lib2/data.ts`, + content: `import { ITest } from "lib1/public"; +export class Data { + public test() { + const result: ITest = { + title: "title" + } + return result; + } +}` + }; + const lib1Public: File = { + path: `${projectLocation}/lib1/public.ts`, + content: `export * from "./tools/public";` + }; + const lib1ToolsPublic: File = { + path: `${projectLocation}/lib1/tools/public.ts`, + content: `export * from "./tools.interface";` + }; + const lib1ToolsInterface: File = { + path: `${projectLocation}/lib1/tools/tools.interface.ts`, + content: `export interface ITest { + title: string; +}` + }; + const filesWithoutConfig = [libFile, app, lib2Public, lib2Data, lib1Public, lib1ToolsPublic, lib1ToolsInterface]; + const files = [config, ...filesWithoutConfig]; + const host = createWatchedSystem(files, { currentDirectory: projectLocation }); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsInitial(host, emptyArray); + + host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsIncremental(host, [ + "lib2/data.ts(5,13): error TS2322: Type '{ title: string; }' is not assignable to type 'ITest'.\n Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?\n" + ]); + }); }); describe("tsc-watch emit with outFile or out setting", () => { From bb99c4123003ade3e471cf17472be6d3f72d96ff Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Mon, 5 Nov 2018 12:23:02 -0800 Subject: [PATCH 221/262] Don't error on bigint literal used in type --- src/compiler/checker.ts | 16 ++++++++++------ .../warnExperimentalBigIntLiteral.errors.txt | 16 +++++++--------- .../reference/warnExperimentalBigIntLiteral.js | 6 ++++-- .../warnExperimentalBigIntLiteral.symbols | 9 ++++++--- .../warnExperimentalBigIntLiteral.types | 7 ++++++- .../compiler/warnExperimentalBigIntLiteral.ts | 3 ++- 6 files changed, 35 insertions(+), 22 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 308f3a61b2c..08f5c3925fd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -30471,13 +30471,17 @@ namespace ts { } function checkGrammarBigIntLiteral(node: BigIntLiteral): boolean { - if (languageVersion < ScriptTarget.ESNext) { - if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targetting_lower_than_ESNext)) { - return true; + const literalType = isLiteralTypeNode(node.parent) || + isPrefixUnaryExpression(node.parent) && isLiteralTypeNode(node.parent.parent); + if (!literalType) { + if (languageVersion < ScriptTarget.ESNext) { + if (grammarErrorOnNode(node, Diagnostics.BigInt_literals_are_not_available_when_targetting_lower_than_ESNext)) { + return true; + } + } + if (!compilerOptions.experimentalBigInt) { + return grammarErrorOnNode(node, Diagnostics.Experimental_support_for_BigInt_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalBigInt_option_to_remove_this_warning); } - } - if (!compilerOptions.experimentalBigInt) { - return grammarErrorOnNode(node, Diagnostics.Experimental_support_for_BigInt_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalBigInt_option_to_remove_this_warning); } return false; } diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt index 6df7ea6e0a2..3e8e50d148c 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.errors.txt @@ -1,16 +1,14 @@ -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(3,24): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,22): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,29): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,39): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -tests/cases/compiler/warnExperimentalBigIntLiteral.ts(4,48): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(5,22): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(5,29): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(5,39): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. +tests/cases/compiler/warnExperimentalBigIntLiteral.ts(5,48): error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. -==== tests/cases/compiler/warnExperimentalBigIntLiteral.ts (5 errors) ==== +==== tests/cases/compiler/warnExperimentalBigIntLiteral.ts (4 errors) ==== const normalNumber = 123; // should not error let bigintType: bigint; // should not error - let bigintLiteralType: 123n; // should error when used as type - ~~~~ -!!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. + let bigintLiteralType: 123n; // should not error when used as type + let bigintNegativeLiteralType: -123n; // should not error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error ~~~~ !!! error TS1351: Experimental support for BigInt is a feature that is subject to change in a future release. Set the 'experimentalBigInt' option to remove this warning. diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.js b/tests/baselines/reference/warnExperimentalBigIntLiteral.js index 8516350ddbf..2a1ee53b2c0 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.js +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.js @@ -1,11 +1,13 @@ //// [warnExperimentalBigIntLiteral.ts] const normalNumber = 123; // should not error let bigintType: bigint; // should not error -let bigintLiteralType: 123n; // should error when used as type +let bigintLiteralType: 123n; // should not error when used as type +let bigintNegativeLiteralType: -123n; // should not error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error //// [warnExperimentalBigIntLiteral.js] const normalNumber = 123; // should not error let bigintType; // should not error -let bigintLiteralType; // should error when used as type +let bigintLiteralType; // should not error when used as type +let bigintNegativeLiteralType; // should not error when used as type const bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols index 782e7edcac6..1ea1c380601 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.symbols @@ -5,9 +5,12 @@ const normalNumber = 123; // should not error let bigintType: bigint; // should not error >bigintType : Symbol(bigintType, Decl(warnExperimentalBigIntLiteral.ts, 1, 3)) -let bigintLiteralType: 123n; // should error when used as type +let bigintLiteralType: 123n; // should not error when used as type >bigintLiteralType : Symbol(bigintLiteralType, Decl(warnExperimentalBigIntLiteral.ts, 2, 3)) -const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error ->bigintNumber : Symbol(bigintNumber, Decl(warnExperimentalBigIntLiteral.ts, 3, 5)) +let bigintNegativeLiteralType: -123n; // should not error when used as type +>bigintNegativeLiteralType : Symbol(bigintNegativeLiteralType, Decl(warnExperimentalBigIntLiteral.ts, 3, 3)) + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : Symbol(bigintNumber, Decl(warnExperimentalBigIntLiteral.ts, 4, 5)) diff --git a/tests/baselines/reference/warnExperimentalBigIntLiteral.types b/tests/baselines/reference/warnExperimentalBigIntLiteral.types index a3f01b31294..a0ba0a9564b 100644 --- a/tests/baselines/reference/warnExperimentalBigIntLiteral.types +++ b/tests/baselines/reference/warnExperimentalBigIntLiteral.types @@ -6,9 +6,14 @@ const normalNumber = 123; // should not error let bigintType: bigint; // should not error >bigintType : bigint -let bigintLiteralType: 123n; // should error when used as type +let bigintLiteralType: 123n; // should not error when used as type >bigintLiteralType : 123n +let bigintNegativeLiteralType: -123n; // should not error when used as type +>bigintNegativeLiteralType : -123n +>-123n : -123n +>123n : 123n + const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error >bigintNumber : bigint >123n * 0b1111n + 0o444n * 0x7fn : bigint diff --git a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts index c9f94fcc992..c59bff0696e 100644 --- a/tests/cases/compiler/warnExperimentalBigIntLiteral.ts +++ b/tests/cases/compiler/warnExperimentalBigIntLiteral.ts @@ -2,5 +2,6 @@ const normalNumber = 123; // should not error let bigintType: bigint; // should not error -let bigintLiteralType: 123n; // should error when used as type +let bigintLiteralType: 123n; // should not error when used as type +let bigintNegativeLiteralType: -123n; // should not error when used as type const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error \ No newline at end of file From f37101e8719a16145fb0a2cee4d4690307870d4c Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 5 Nov 2018 12:57:33 -0800 Subject: [PATCH 222/262] Fix bug when augmenting parent-less symbol (#28345) --- src/compiler/checker.ts | 2 +- .../reference/moduleAugmentationOfAlias.js | 31 ++++++++++++++++++ .../moduleAugmentationOfAlias.symbols | 32 +++++++++++++++++++ .../reference/moduleAugmentationOfAlias.types | 28 ++++++++++++++++ .../compiler/moduleAugmentationOfAlias.ts | 15 +++++++++ 5 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/moduleAugmentationOfAlias.js create mode 100644 tests/baselines/reference/moduleAugmentationOfAlias.symbols create mode 100644 tests/baselines/reference/moduleAugmentationOfAlias.types create mode 100644 tests/cases/compiler/moduleAugmentationOfAlias.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e17b38ff736..d92d32116f7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -26751,7 +26751,7 @@ namespace ts { let reportError = !(symbol.flags & SymbolFlags.Transient); if (!reportError) { // symbol should not originate in augmentation - reportError = isExternalModuleAugmentation(symbol.parent!.declarations[0]); + reportError = !!symbol.parent && isExternalModuleAugmentation(symbol.parent.declarations[0]); } } break; diff --git a/tests/baselines/reference/moduleAugmentationOfAlias.js b/tests/baselines/reference/moduleAugmentationOfAlias.js new file mode 100644 index 00000000000..1b77eeeec18 --- /dev/null +++ b/tests/baselines/reference/moduleAugmentationOfAlias.js @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/moduleAugmentationOfAlias.ts] //// + +//// [a.ts] +interface I {} +export default I; + +//// [b.ts] +export {}; +declare module './a' { + export default interface I { x: number; } +} + +//// [c.ts] +import I from "./a"; +function f(i: I) { + i.x; +} + + +//// [a.js] +"use strict"; +exports.__esModule = true; +//// [b.js] +"use strict"; +exports.__esModule = true; +//// [c.js] +"use strict"; +exports.__esModule = true; +function f(i) { + i.x; +} diff --git a/tests/baselines/reference/moduleAugmentationOfAlias.symbols b/tests/baselines/reference/moduleAugmentationOfAlias.symbols new file mode 100644 index 00000000000..8bdf13c5396 --- /dev/null +++ b/tests/baselines/reference/moduleAugmentationOfAlias.symbols @@ -0,0 +1,32 @@ +=== /a.ts === +interface I {} +>I : Symbol(I, Decl(a.ts, 0, 0), Decl(b.ts, 1, 22)) + +export default I; +>I : Symbol(I, Decl(a.ts, 0, 0)) + +=== /b.ts === +export {}; +declare module './a' { +>'./a' : Symbol("/a", Decl(a.ts, 0, 0), Decl(b.ts, 0, 10)) + + export default interface I { x: number; } +>I : Symbol(I, Decl(a.ts, 0, 0), Decl(b.ts, 1, 22)) +>x : Symbol(I.x, Decl(b.ts, 2, 32)) +} + +=== /c.ts === +import I from "./a"; +>I : Symbol(I, Decl(c.ts, 0, 6)) + +function f(i: I) { +>f : Symbol(f, Decl(c.ts, 0, 20)) +>i : Symbol(i, Decl(c.ts, 1, 11)) +>I : Symbol(I, Decl(c.ts, 0, 6)) + + i.x; +>i.x : Symbol(I.x, Decl(b.ts, 2, 32)) +>i : Symbol(i, Decl(c.ts, 1, 11)) +>x : Symbol(I.x, Decl(b.ts, 2, 32)) +} + diff --git a/tests/baselines/reference/moduleAugmentationOfAlias.types b/tests/baselines/reference/moduleAugmentationOfAlias.types new file mode 100644 index 00000000000..a5112f58695 --- /dev/null +++ b/tests/baselines/reference/moduleAugmentationOfAlias.types @@ -0,0 +1,28 @@ +=== /a.ts === +interface I {} +export default I; +>I : I + +=== /b.ts === +export {}; +declare module './a' { +>'./a' : typeof import("/a") + + export default interface I { x: number; } +>x : number +} + +=== /c.ts === +import I from "./a"; +>I : any + +function f(i: I) { +>f : (i: I) => void +>i : I + + i.x; +>i.x : number +>i : I +>x : number +} + diff --git a/tests/cases/compiler/moduleAugmentationOfAlias.ts b/tests/cases/compiler/moduleAugmentationOfAlias.ts new file mode 100644 index 00000000000..d9014033d56 --- /dev/null +++ b/tests/cases/compiler/moduleAugmentationOfAlias.ts @@ -0,0 +1,15 @@ +// @Filename: /a.ts +interface I {} +export default I; + +// @Filename: /b.ts +export {}; +declare module './a' { + export default interface I { x: number; } +} + +// @Filename: /c.ts +import I from "./a"; +function f(i: I) { + i.x; +} From c22c7e687d11f5511337909140639ac96e37b204 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 5 Nov 2018 16:16:28 -0800 Subject: [PATCH 223/262] Strcter testing for global completions; and 'excludes' can only be a string (#28349) --- src/harness/fourslash.ts | 528 ++++++++++-------- .../fourslash/completionsImport_keywords.ts | 13 +- tests/cases/fourslash/fourslash.ts | 41 +- tests/cases/fourslash/server/completions02.ts | 10 +- 4 files changed, 316 insertions(+), 276 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index e4908d3612f..1f6a9d3be40 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -787,6 +787,7 @@ namespace FourSlash { } if (options.excludes) { 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}`); } @@ -812,7 +813,9 @@ namespace FourSlash { } if (kind !== undefined || kindModifiers !== undefined) { - assert.equal(actual.kind, kind); + if (actual.kind !== kind) { + this.raiseError(`Unexpected kind for ${actual.name}: Expected ${kind}, actual ${actual.kind}`); + } if (actual.kindModifiers !== (kindModifiers || "")) { this.raiseError(`Bad kind modifiers for ${actual.name}: Expected ${kindModifiers || ""}, actual ${actual.kindModifiers}`); } @@ -4427,110 +4430,119 @@ namespace FourSlashInterface { } } export namespace Completion { - const res: string[] = []; + const functionEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "function", kindModifiers: "declare" }); + const constEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "const", kindModifiers: "declare" }); + const moduleEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "module", kindModifiers: "declare" }); + const keywordEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "keyword" }); + const methodEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "method", kindModifiers: "declare" }); + const propertyEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "property", kindModifiers: "declare" }); + const interfaceEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "interface", kindModifiers: "declare" }); + const typeEntry = (name: string): ExpectedCompletionEntryObject => ({ name, kind: "type", kindModifiers: "declare" }); + + const res: ExpectedCompletionEntryObject[] = []; for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) { - res.push(ts.Debug.assertDefined(ts.tokenToString(i))); + res.push({ name: ts.Debug.assertDefined(ts.tokenToString(i)), kind: "keyword" }); } - export const keywordsWithUndefined: ReadonlyArray = res; - export const keywords: ReadonlyArray = keywordsWithUndefined.filter(k => k !== "undefined"); + export const keywordsWithUndefined: ReadonlyArray = res; + export const keywords: ReadonlyArray = keywordsWithUndefined.filter(k => k.name !== "undefined"); - export const typeKeywords: ReadonlyArray = - ["false", "null", "true", "void", "any", "boolean", "keyof", "never", "number", "object", "string", "symbol", "undefined", "unique", "unknown"]; + export const typeKeywords: ReadonlyArray = + ["false", "null", "true", "void", "any", "boolean", "keyof", "never", "number", "object", "string", "symbol", "undefined", "unique", "unknown"].map(keywordEntry); - const globalTypeDecls = [ - "Symbol", - "PropertyKey", - "PropertyDescriptor", - "PropertyDescriptorMap", - "Object", - "ObjectConstructor", - "Function", - "FunctionConstructor", - "CallableFunction", - "NewableFunction", - "IArguments", - "String", - "StringConstructor", - "Boolean", - "BooleanConstructor", - "Number", - "NumberConstructor", - "TemplateStringsArray", - "ImportMeta", - "Math", - "Date", - "DateConstructor", - "RegExpMatchArray", - "RegExpExecArray", - "RegExp", - "RegExpConstructor", - "Error", - "ErrorConstructor", - "EvalError", - "EvalErrorConstructor", - "RangeError", - "RangeErrorConstructor", - "ReferenceError", - "ReferenceErrorConstructor", - "SyntaxError", - "SyntaxErrorConstructor", - "TypeError", - "TypeErrorConstructor", - "URIError", - "URIErrorConstructor", - "JSON", - "ReadonlyArray", - "ConcatArray", - "Array", - "ArrayConstructor", - "TypedPropertyDescriptor", - "ClassDecorator", - "PropertyDecorator", - "MethodDecorator", - "ParameterDecorator", - "PromiseConstructorLike", - "PromiseLike", - "Promise", - "ArrayLike", - "Partial", - "Required", - "Readonly", - "Pick", - "Record", - "Exclude", - "Extract", - "NonNullable", - "Parameters", - "ConstructorParameters", - "ReturnType", - "InstanceType", - "ThisType", - "ArrayBuffer", - "ArrayBufferTypes", - "ArrayBufferLike", - "ArrayBufferConstructor", - "ArrayBufferView", - "DataView", - "DataViewConstructor", - "Int8Array", - "Int8ArrayConstructor", - "Uint8Array", - "Uint8ArrayConstructor", - "Uint8ClampedArray", - "Uint8ClampedArrayConstructor", - "Int16Array", - "Int16ArrayConstructor", - "Uint16Array", - "Uint16ArrayConstructor", - "Int32Array", - "Int32ArrayConstructor", - "Uint32Array", - "Uint32ArrayConstructor", - "Float32Array", - "Float32ArrayConstructor", - "Float64Array", - "Float64ArrayConstructor", - "Intl", + const globalTypeDecls: ReadonlyArray = [ + interfaceEntry("Symbol"), + typeEntry("PropertyKey"), + interfaceEntry("PropertyDescriptor"), + interfaceEntry("PropertyDescriptorMap"), + constEntry("Object"), + interfaceEntry("ObjectConstructor"), + constEntry("Function"), + interfaceEntry("FunctionConstructor"), + interfaceEntry("CallableFunction"), + interfaceEntry("NewableFunction"), + interfaceEntry("IArguments"), + constEntry("String"), + interfaceEntry("StringConstructor"), + constEntry("Boolean"), + interfaceEntry("BooleanConstructor"), + constEntry("Number"), + interfaceEntry("NumberConstructor"), + interfaceEntry("TemplateStringsArray"), + interfaceEntry("ImportMeta"), + constEntry("Math"), + constEntry("Date"), + interfaceEntry("DateConstructor"), + interfaceEntry("RegExpMatchArray"), + interfaceEntry("RegExpExecArray"), + constEntry("RegExp"), + interfaceEntry("RegExpConstructor"), + constEntry("Error"), + interfaceEntry("ErrorConstructor"), + constEntry("EvalError"), + interfaceEntry("EvalErrorConstructor"), + constEntry("RangeError"), + interfaceEntry("RangeErrorConstructor"), + constEntry("ReferenceError"), + interfaceEntry("ReferenceErrorConstructor"), + constEntry("SyntaxError"), + interfaceEntry("SyntaxErrorConstructor"), + constEntry("TypeError"), + interfaceEntry("TypeErrorConstructor"), + constEntry("URIError"), + interfaceEntry("URIErrorConstructor"), + constEntry("JSON"), + interfaceEntry("ReadonlyArray"), + interfaceEntry("ConcatArray"), + constEntry("Array"), + interfaceEntry("ArrayConstructor"), + interfaceEntry("TypedPropertyDescriptor"), + typeEntry("ClassDecorator"), + typeEntry("PropertyDecorator"), + typeEntry("MethodDecorator"), + typeEntry("ParameterDecorator"), + typeEntry("PromiseConstructorLike"), + interfaceEntry("PromiseLike"), + interfaceEntry("Promise"), + interfaceEntry("ArrayLike"), + typeEntry("Partial"), + typeEntry("Required"), + typeEntry("Readonly"), + typeEntry("Pick"), + typeEntry("Record"), + typeEntry("Exclude"), + typeEntry("Extract"), + typeEntry("NonNullable"), + typeEntry("Parameters"), + typeEntry("ConstructorParameters"), + typeEntry("ReturnType"), + typeEntry("InstanceType"), + interfaceEntry("ThisType"), + constEntry("ArrayBuffer"), + interfaceEntry("ArrayBufferTypes"), + typeEntry("ArrayBufferLike"), + interfaceEntry("ArrayBufferConstructor"), + interfaceEntry("ArrayBufferView"), + constEntry("DataView"), + interfaceEntry("DataViewConstructor"), + constEntry("Int8Array"), + interfaceEntry("Int8ArrayConstructor"), + constEntry("Uint8Array"), + interfaceEntry("Uint8ArrayConstructor"), + constEntry("Uint8ClampedArray"), + interfaceEntry("Uint8ClampedArrayConstructor"), + constEntry("Int16Array"), + interfaceEntry("Int16ArrayConstructor"), + constEntry("Uint16Array"), + interfaceEntry("Uint16ArrayConstructor"), + constEntry("Int32Array"), + interfaceEntry("Int32ArrayConstructor"), + constEntry("Uint32Array"), + interfaceEntry("Uint32ArrayConstructor"), + constEntry("Float32Array"), + interfaceEntry("Float32ArrayConstructor"), + constEntry("Float64Array"), + interfaceEntry("Float64ArrayConstructor"), + moduleEntry("Intl"), ]; export const globalTypes = globalTypesPlus([]); @@ -4543,54 +4555,54 @@ namespace FourSlashInterface { ]; } - export const classElementKeywords: ReadonlyArray = - ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"]; + export const classElementKeywords: ReadonlyArray = + ["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"].map(keywordEntry); - export const constructorParameterKeywords: ReadonlyArray = - ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntry => ({ name, kind: "keyword" })); + export const constructorParameterKeywords: ReadonlyArray = + ["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword" })); - export const functionMembers: ReadonlyArray = [ - "apply", - "call", - "bind", - "toString", - "length", - { name: "arguments", text: "(property) Function.arguments: any" }, - "caller" + export const functionMembers: ReadonlyArray = [ + methodEntry("apply"), + methodEntry("call"), + methodEntry("bind"), + methodEntry("toString"), + propertyEntry("length"), + { name: "arguments", kind: "property", kindModifiers: "declare", text: "(property) Function.arguments: any" }, + propertyEntry("caller"), ]; - export const stringMembers: ReadonlyArray = [ - "toString", - "charAt", - "charCodeAt", - "concat", - "indexOf", - "lastIndexOf", - "localeCompare", - "match", - "replace", - "search", - "slice", - "split", - "substring", - "toLowerCase", - "toLocaleLowerCase", - "toUpperCase", - "toLocaleUpperCase", - "trim", - "length", - "substr", - "valueOf", + export const stringMembers: ReadonlyArray = [ + methodEntry("toString"), + methodEntry("charAt"), + methodEntry("charCodeAt"), + methodEntry("concat"), + methodEntry("indexOf"), + methodEntry("lastIndexOf"), + methodEntry("localeCompare"), + methodEntry("match"), + methodEntry("replace"), + methodEntry("search"), + methodEntry("slice"), + methodEntry("split"), + methodEntry("substring"), + methodEntry("toLowerCase"), + methodEntry("toLocaleLowerCase"), + methodEntry("toUpperCase"), + methodEntry("toLocaleUpperCase"), + methodEntry("trim"), + propertyEntry("length"), + methodEntry("substr"), + methodEntry("valueOf"), ]; - export const functionMembersWithPrototype: ReadonlyArray = [ + export const functionMembersWithPrototype: ReadonlyArray = [ ...functionMembers.slice(0, 4), - "prototype", + propertyEntry("prototype"), ...functionMembers.slice(4), ]; // TODO: Shouldn't propose type keywords in statement position - export const statementKeywordsWithTypes: ReadonlyArray = [ + export const statementKeywordsWithTypes: ReadonlyArray = [ "break", "case", "catch", @@ -4665,108 +4677,125 @@ namespace FourSlashInterface { "global", "bigint", "of", + ].map(keywordEntry); + + export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => { + const name = k.name; + switch (name) { + case "false": + case "true": + case "null": + case "void": + return true; + case "declare": + case "module": + return false; + default: + return !ts.contains(typeKeywords, k); + } + }); + + export const globalsVars: ReadonlyArray = [ + functionEntry("eval"), + functionEntry("parseInt"), + functionEntry("parseFloat"), + functionEntry("isNaN"), + functionEntry("isFinite"), + functionEntry("decodeURI"), + functionEntry("decodeURIComponent"), + functionEntry("encodeURI"), + functionEntry("encodeURIComponent"), + functionEntry("escape"), + functionEntry("unescape"), + constEntry("NaN"), + constEntry("Infinity"), + constEntry("Object"), + constEntry("Function"), + constEntry("String"), + constEntry("Boolean"), + constEntry("Number"), + constEntry("Math"), + constEntry("Date"), + constEntry("RegExp"), + constEntry("Error"), + constEntry("EvalError"), + constEntry("RangeError"), + constEntry("ReferenceError"), + constEntry("SyntaxError"), + constEntry("TypeError"), + constEntry("URIError"), + constEntry("JSON"), + constEntry("Array"), + constEntry("ArrayBuffer"), + constEntry("DataView"), + constEntry("Int8Array"), + constEntry("Uint8Array"), + constEntry("Uint8ClampedArray"), + constEntry("Int16Array"), + constEntry("Uint16Array"), + constEntry("Int32Array"), + constEntry("Uint32Array"), + constEntry("Float32Array"), + constEntry("Float64Array"), + moduleEntry("Intl"), ]; - export const statementKeywords: ReadonlyArray = statementKeywordsWithTypes.filter(k => - k === "false" || k === "true" || k === "null" || k === "void" || !ts.contains(typeKeywords, k) && k !== "declare" && k !== "module"); - - export const globalsVars: ReadonlyArray = [ - "eval", - "parseInt", - "parseFloat", - "isNaN", - "isFinite", - "decodeURI", - "decodeURIComponent", - "encodeURI", - "encodeURIComponent", - "escape", - "unescape", - "NaN", - "Infinity", - "Object", - "Function", - "String", - "Boolean", - "Number", - "Math", - "Date", - "RegExp", - "Error", - "EvalError", - "RangeError", - "ReferenceError", - "SyntaxError", - "TypeError", - "URIError", - "JSON", - "Array", - "ArrayBuffer", - "DataView", - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "Intl", - ]; + const globalKeywordsInsideFunction: ReadonlyArray = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "implements", + "interface", + "let", + "package", + "yield", + "async", + ].map(keywordEntry); // TODO: many of these are inappropriate to always provide export const globalsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ - "arguments", + { name: "arguments", kind: "local var" }, ...plus, ...globalsVars, - "undefined", - "break", - "case", - "catch", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "else", - "enum", - "export", - "extends", - "false", - "finally", - "for", - "function", - "if", - "import", - "in", - "instanceof", - "new", - "null", - "return", - "super", - "switch", - "this", - "throw", - "true", - "try", - "typeof", - "var", - "void", - "while", - "with", - "implements", - "interface", - "let", - "package", - "yield", - "async", + { name: "undefined", kind: "var" }, + ...globalKeywordsInsideFunction, ]; // TODO: many of these are inappropriate to always provide - export const globalKeywords: ReadonlyArray = [ + export const globalKeywords: ReadonlyArray = [ "break", "case", "catch", @@ -4841,9 +4870,9 @@ namespace FourSlashInterface { "global", "bigint", "of", - ]; + ].map(keywordEntry); - export const insideMethodKeywords: ReadonlyArray = [ + export const insideMethodKeywords: ReadonlyArray = [ "break", "case", "catch", @@ -4886,17 +4915,21 @@ namespace FourSlashInterface { "package", "yield", "async", - ]; + ].map(keywordEntry); - export const globalKeywordsPlusUndefined: ReadonlyArray = (() => { - const i = globalKeywords.indexOf("unique"); - return [...globalKeywords.slice(0, i), "undefined", ...globalKeywords.slice(i)]; + 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 = [...globalsVars, "undefined", ...globalKeywords]; + export const globals: ReadonlyArray = [ + ...globalsVars, + { name: "undefined", kind: "var" }, + ...globalKeywords + ]; export function globalsPlus(plus: ReadonlyArray): ReadonlyArray { - return [...globalsVars, ...plus, "undefined", ...globalKeywords]; + return [...globalsVars, ...plus, { name: "undefined", kind: "var" }, ...globalKeywords]; } } @@ -4914,20 +4947,21 @@ namespace FourSlashInterface { newContent: NewFileContent; } - export type ExpectedCompletionEntry = string | { - readonly name: string, - readonly source?: string, - readonly insertText?: string, - readonly replacementSpan?: FourSlash.Range, - readonly hasAction?: boolean, // If not specified, will assert that this is false. + export type ExpectedCompletionEntry = string | ExpectedCompletionEntryObject; + export interface ExpectedCompletionEntryObject { + readonly name: string; + readonly source?: string; + readonly insertText?: string; + readonly replacementSpan?: FourSlash.Range; + readonly hasAction?: boolean; // If not specified, will assert that this is false. readonly isRecommended?: boolean; // If not specified, will assert that this is false. - readonly kind?: string, // If not specified, won't assert about this - readonly kindModifiers?: string, // Must be paired with 'kind' + readonly kind?: string; // If not specified, won't assert about this + readonly kindModifiers?: string; // Must be paired with 'kind' readonly text?: string; readonly documentation?: string; readonly sourceDisplay?: string; readonly tags?: ReadonlyArray; - }; + } export interface VerifyCompletionsOptions { readonly marker?: ArrayOrSingle; diff --git a/tests/cases/fourslash/completionsImport_keywords.ts b/tests/cases/fourslash/completionsImport_keywords.ts index 3ac4e0b320e..6d4edd83b36 100644 --- a/tests/cases/fourslash/completionsImport_keywords.ts +++ b/tests/cases/fourslash/completionsImport_keywords.ts @@ -21,22 +21,23 @@ verify.completions( // no reserved words { marker: "break", - includes: { name: "break", text: "break", kind: "keyword" }, - excludes: { name: "break", source: "/a" }, + exact: completion.globals, preferences, }, // no strict mode reserved words { marker: "implements", - includes: { name: "implements", text: "implements", kind: "keyword" }, - excludes: { name: "implements", source: "/a" }, + exact: completion.globals, preferences, }, // yes contextual keywords { marker: "unique", - includes: { name: "unique", source: "/a", sourceDisplay: "./a", text: "(alias) const unique: 0\nexport unique", hasAction: true }, - excludes: { name: "unique", source: undefined }, + exact: [ + ...completion.globalsVars, "undefined", + { name: "unique", source: "/a", sourceDisplay: "./a", text: "(alias) const unique: 0\nexport unique", hasAction: true }, + ...completion.globalKeywords.filter(e => e.name !== "unique"), + ], preferences, }, ); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index d1979265548..ddf55fb41b5 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -514,7 +514,7 @@ declare namespace FourSlashInterface { readonly isGlobalCompletion?: boolean; readonly exact?: ArrayOrSingle; readonly includes?: ArrayOrSingle; - readonly excludes?: ArrayOrSingle; + readonly excludes?: ArrayOrSingle; readonly preferences?: UserPreferences; readonly triggerCharacter?: string; } @@ -648,23 +648,24 @@ declare var format: FourSlashInterface.format; declare var cancellation: FourSlashInterface.cancellation; declare var classification: typeof FourSlashInterface.classification; declare namespace completion { - export const globals: ReadonlyArray; - export const globalKeywords: ReadonlyArray; - export const insideMethodKeywords: ReadonlyArray; - export const globalKeywordsPlusUndefined: ReadonlyArray; - export const globalsVars: ReadonlyArray; - export function globalsInsideFunction(plus: ReadonlyArray): ReadonlyArray; - export function globalsPlus(plus: ReadonlyArray): ReadonlyArray; - export const keywordsWithUndefined: ReadonlyArray; - export const keywords: ReadonlyArray; - export const typeKeywords: ReadonlyArray; - export const globalTypes: ReadonlyArray; - export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray; - export const classElementKeywords: ReadonlyArray; - export const constructorParameterKeywords: ReadonlyArray; - export const functionMembers: ReadonlyArray; - export const stringMembers: ReadonlyArray; - export const functionMembersWithPrototype: ReadonlyArray; - export const statementKeywordsWithTypes: ReadonlyArray; - export const statementKeywords: ReadonlyArray; + type Entry = FourSlashInterface.ExpectedCompletionEntryObject; + export const globals: ReadonlyArray; + export const globalKeywords: ReadonlyArray; + export const insideMethodKeywords: ReadonlyArray; + export const globalKeywordsPlusUndefined: ReadonlyArray; + export const globalsVars: ReadonlyArray; + export function globalsInsideFunction(plus: ReadonlyArray): ReadonlyArray; + export function globalsPlus(plus: ReadonlyArray): ReadonlyArray; + export const keywordsWithUndefined: ReadonlyArray; + export const keywords: ReadonlyArray; + export const typeKeywords: ReadonlyArray; + export const globalTypes: ReadonlyArray; + export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray; + export const classElementKeywords: ReadonlyArray; + export const constructorParameterKeywords: ReadonlyArray; + export const functionMembers: ReadonlyArray; + export const stringMembers: ReadonlyArray; + export const functionMembersWithPrototype: ReadonlyArray; + export const statementKeywordsWithTypes: ReadonlyArray; + export const statementKeywords: ReadonlyArray; } diff --git a/tests/cases/fourslash/server/completions02.ts b/tests/cases/fourslash/server/completions02.ts index 1a493af524b..8e44edd8225 100644 --- a/tests/cases/fourslash/server/completions02.ts +++ b/tests/cases/fourslash/server/completions02.ts @@ -7,9 +7,13 @@ ////} ////Foo./**/ -const entryName = (e: FourSlashInterface.ExpectedCompletionEntry) => typeof e === "string" ? e : e.name; -const sortedFunctionMembers = completion.functionMembersWithPrototype.slice().sort((a, b) => entryName(a).localeCompare(entryName(b))); -const exact: ReadonlyArray = [...sortedFunctionMembers, { name: "x", text: "var Foo.x: number" }]; +const sortedFunctionMembers = completion.functionMembersWithPrototype.slice().sort((a, b) => a.name.localeCompare(b.name)); +const exact: ReadonlyArray = [ + ...sortedFunctionMembers.map(e => + e.name === "arguments" ? { ...e, kind: "property", kindModifiers: "declare" } : + e.name === "prototype" ? { ...e, kindModifiers: undefined } : e), + { name: "x", text: "var Foo.x: number" }, +]; verify.completions({ marker: "", exact }); // Make an edit From b28e411734c3fd2039f18004984f0814ed3b89aa Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Mon, 5 Nov 2018 16:20:52 -0800 Subject: [PATCH 224/262] Update user baselines (#28341) --- .../user/chrome-devtools-frontend.log | 84 +++++++++++++++++++ .../baselines/reference/user/graceful-fs.log | 28 +++---- 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 7841072577e..bd38799ab19 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -768,6 +768,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21003,8): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21007,8): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21011,8): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21017,1): error TS2323: Cannot redeclare exported variable 'deflate'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21022,19): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21026,23): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(21034,19): error TS2350: Only a void function can be called with the 'new' keyword. @@ -846,7 +847,29 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23247,18): error TS2339: Property 'length' does not exist on type 'Buffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23247,37): error TS2339: Property 'length' does not exist on type 'Buffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23256,26): error TS2339: Property 'length' does not exist on type 'Buffer'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23459,1): error TS2323: Cannot redeclare exported variable 'isArray'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23464,1): error TS2323: Cannot redeclare exported variable 'isBoolean'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23469,1): error TS2323: Cannot redeclare exported variable 'isNull'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23474,1): error TS2323: Cannot redeclare exported variable 'isNullOrUndefined'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23479,1): error TS2323: Cannot redeclare exported variable 'isNumber'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23484,1): error TS2323: Cannot redeclare exported variable 'isString'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23489,1): error TS2323: Cannot redeclare exported variable 'isSymbol'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23494,1): error TS2323: Cannot redeclare exported variable 'isUndefined'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23499,1): error TS2323: Cannot redeclare exported variable 'isRegExp'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23504,1): error TS2323: Cannot redeclare exported variable 'isObject'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23509,1): error TS2323: Cannot redeclare exported variable 'isDate'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23514,1): error TS2323: Cannot redeclare exported variable 'isError'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23519,1): error TS2323: Cannot redeclare exported variable 'isFunction'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23529,1): error TS2323: Cannot redeclare exported variable 'isPrimitive'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23531,1): error TS2323: Cannot redeclare exported variable 'isBuffer'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(23601,5): error TS2339: Property 'context' does not exist on type 'Error'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24073,1): error TS2323: Cannot redeclare exported variable 'Buf8'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24074,1): error TS2323: Cannot redeclare exported variable 'Buf16'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24075,1): error TS2323: Cannot redeclare exported variable 'Buf32'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24078,1): error TS2323: Cannot redeclare exported variable 'Buf8'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24079,1): error TS2323: Cannot redeclare exported variable 'Buf16'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24080,1): error TS2323: Cannot redeclare exported variable 'Buf32'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(26059,1): error TS2323: Cannot redeclare exported variable 'deflate'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27915,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27918,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. @@ -857,6 +880,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27929,20): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27956,16): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28222,51): error TS2300: Duplicate identifier '_read'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28457,20): error TS2339: Property 'emit' does not exist on type 'Readable'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28533,20): error TS2300: Duplicate identifier '_read'. @@ -897,6 +921,23 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30311,40): error TS2345: Argument of type '(x: string) => string | number' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30729,1): error TS2323: Cannot redeclare exported variable 'isArray'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30734,1): error TS2323: Cannot redeclare exported variable 'isBoolean'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30739,1): error TS2323: Cannot redeclare exported variable 'isNull'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30744,1): error TS2323: Cannot redeclare exported variable 'isNullOrUndefined'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30749,1): error TS2323: Cannot redeclare exported variable 'isNumber'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30754,1): error TS2323: Cannot redeclare exported variable 'isString'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30759,1): error TS2323: Cannot redeclare exported variable 'isSymbol'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30764,1): error TS2323: Cannot redeclare exported variable 'isUndefined'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30769,1): error TS2323: Cannot redeclare exported variable 'isRegExp'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30774,1): error TS2323: Cannot redeclare exported variable 'isObject'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30779,1): error TS2323: Cannot redeclare exported variable 'isDate'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30785,1): error TS2323: Cannot redeclare exported variable 'isError'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30790,1): error TS2323: Cannot redeclare exported variable 'isFunction'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30800,1): error TS2323: Cannot redeclare exported variable 'isPrimitive'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30802,1): error TS2323: Cannot redeclare exported variable 'isBuffer'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(30828,1): error TS2323: Cannot redeclare exported variable 'log'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31089,1): error TS2323: Cannot redeclare exported variable 'log'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31094,37): error TS2304: Cannot find name 'chrome'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31095,21): error TS2304: Cannot find name 'chrome'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31096,1): error TS2304: Cannot find name 'chrome'. @@ -904,10 +945,14 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31124,56): error TS2339: Property 'process' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31130,128): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31132,62): error TS2339: Property 'firebug' does not exist on type 'Console'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31289,1): error TS2323: Cannot redeclare exported variable 'names'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31290,1): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31343,6): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31344,6): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31345,6): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31382,17): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: any; enabled: any; useColors: any; color: any; }'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31410,1): error TS2323: Cannot redeclare exported variable 'names'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(31411,1): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39766,1): error TS2304: Cannot find name 'axe'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39802,8): error TS2339: Property 'requestFileSystem' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(39802,33): error TS2339: Property 'requestFileSystem' does not exist on type 'Window'. @@ -2785,7 +2830,14 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,11): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60267,32): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60268,1): error TS2304: Cannot find name 'define'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60346,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60397,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60430,8): error TS2339: Property 'errors' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60436,1): error TS2323: Cannot redeclare exported variable 'Syntax'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60446,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60601,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60602,1): error TS2323: Cannot redeclare exported variable 'Syntax'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60688,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60728,13): error TS2339: Property 'match' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,6): error TS2339: Property 'scanner' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(60732,25): error TS2339: Property 'startMarker' does not exist on type 'JSXParser'. @@ -2948,6 +3000,11 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61200,9): error TS2339: Property 'config' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61201,6): error TS2339: Property 'tokens' does not exist on type 'JSXParser'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61209,62): error TS2339: Property 'match' does not exist on type 'JSXParser'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61221,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61281,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61386,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(61407,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62087,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(62832,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'id' must be of type 'string', but here has type 'any'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63482,12): error TS2339: Property 'message' does not exist on type '{ simple: boolean; paramSet: {}; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(63483,39): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; paramSet: {}; }'. @@ -2959,12 +3016,19 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64518,9): error TS2551: Property 'paramSet' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. Did you mean 'params'? node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64534,18): error TS2339: Property 'stricted' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(64536,17): error TS2339: Property 'message' does not exist on type '{ simple: boolean; params: undefined[]; firstRestricted: any; }'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65232,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65248,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65283,7): error TS2339: Property 'index' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65284,7): error TS2339: Property 'lineNumber' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65285,7): error TS2339: Property 'description' does not exist on type 'Error'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65310,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65379,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65468,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65533,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66529,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66549,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66811,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67117,1): error TS2322: Type 'string[]' is not assignable to type 'RegExpExecArray'. Property 'index' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(67300,14): error TS2339: Property 'Channels' does not exist on type '{}'. @@ -2994,6 +3058,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68209,38): error TS2339: Property 'componentsOrder' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68212,26): error TS2339: Property 'maxH' does not exist on type '{}'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68213,26): error TS2339: Property 'maxV' does not exist on type '{}'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(69799,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,4): error TS2531: Object is possibly 'null'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,26): error TS2531: Object is possibly 'null'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70753,6): error TS2531: Object is possibly 'null'. @@ -11532,16 +11597,31 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,482): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,502): error TS2554: Expected 1 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1,564): error TS2339: Property 'code' does not exist on type 'Error'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(166,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(293,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(337,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(392,1): error TS2323: Cannot redeclare exported variable 'EventEmitter'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(398,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1330,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1370,101): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1550,11): error TS2339: Property 'TIME_BEFORE_LINKIFY' does not exist on type 'typeof Linkifier'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(1557,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2037,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2281,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2359,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2378,16): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2397,20): error TS2339: Property 'clipboardData' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2398,27): error TS2339: Property 'clipboardData' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2450,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2476,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2503,41): error TS2339: Property '_document' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2509,18): error TS2339: Property '_parentElement' does not exist on type 'CharMeasure'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2524,18): error TS2339: Property 'emit' does not exist on type 'CharMeasure'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2535,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2612,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2615,22): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'any', but here has type 'number'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2674,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2690,63): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2694,68): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2697,70): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. @@ -11549,6 +11629,9 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2704,51): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2713,22): error TS2339: Property 'OBJECT_ID_ATTRIBUTE' does not exist on type 'typeof DomElementObjectPool'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2714,22): error TS2339: Property '_objectCount' does not exist on type 'typeof DomElementObjectPool'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2721,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2732,1): error TS2323: Cannot redeclare exported variable '__esModule'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2766,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(2925,9): error TS2322: Type 'number' is not assignable to type 'number[]'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3087,14): error TS2339: Property 'browser' does not exist on type 'Terminal'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(3151,54): error TS2339: Property 'theme' does not exist on type 'Terminal'. @@ -11609,6 +11692,7 @@ node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(4164,20): error TS2300: Duplicate identifier 'handler'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(4171,10): error TS2339: Property 'emit' does not exist on type 'Terminal'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(4174,10): error TS2339: Property 'emit' does not exist on type 'Terminal'. +node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/build/xterm.js(4307,1): error TS2323: Cannot redeclare exported variable 'EventEmitter'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(13,6): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(24,8): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(42,21): error TS2339: Property 'testRunner' does not exist on type 'Window'. diff --git a/tests/baselines/reference/user/graceful-fs.log b/tests/baselines/reference/user/graceful-fs.log index ef5a4e24f37..37974c72857 100644 --- a/tests/baselines/reference/user/graceful-fs.log +++ b/tests/baselines/reference/user/graceful-fs.log @@ -1,24 +1,24 @@ Exit Code: 1 Standard output: -node_modules/graceful-fs/fs.js(14,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'copy' must be of type '{ __proto__: any; }', but here has type 'any'. -node_modules/graceful-fs/fs.js(17,38): error TS2345: Argument of type 'PropertyDescriptor | undefined' is not assignable to parameter of type 'PropertyDescriptor & ThisType'. +node_modules/graceful-fs/clone.js(12,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'copy' must be of type '{ __proto__: any; }', but here has type 'any'. +node_modules/graceful-fs/clone.js(15,38): error TS2345: Argument of type 'PropertyDescriptor | undefined' is not assignable to parameter of type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor'. -node_modules/graceful-fs/graceful-fs.js(12,3): error TS2322: Type '(msg: string, ...param: any[]) => void' is not assignable to type '() => void'. -node_modules/graceful-fs/graceful-fs.js(15,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(14,3): error TS2322: Type '(msg: string, ...param: any[]) => void' is not assignable to type '() => void'. +node_modules/graceful-fs/graceful-fs.js(17,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. Property '0' is missing in type 'IArguments'. -node_modules/graceful-fs/graceful-fs.js(22,5): error TS2554: Expected 0 arguments, but got 1. -node_modules/graceful-fs/graceful-fs.js(37,1): error TS2322: Type '(fd: any, cb: any) => void' is not assignable to type 'typeof close'. - Property '__promisify__' is missing in type '(fd: any, cb: any) => void'. -node_modules/graceful-fs/graceful-fs.js(51,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[number]'. +node_modules/graceful-fs/graceful-fs.js(24,5): error TS2554: Expected 0 arguments, but got 1. +node_modules/graceful-fs/graceful-fs.js(30,54): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. +node_modules/graceful-fs/graceful-fs.js(32,8): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. +node_modules/graceful-fs/graceful-fs.js(52,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[number]'. Property '0' is missing in type 'IArguments'. -node_modules/graceful-fs/graceful-fs.js(161,5): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(162,5): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(180,68): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(174,5): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(175,5): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(197,68): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. Property 'pop' is missing in type 'IArguments'. -node_modules/graceful-fs/graceful-fs.js(203,70): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. -node_modules/graceful-fs/graceful-fs.js(252,3): error TS2554: Expected 0 arguments, but got 3. -node_modules/graceful-fs/graceful-fs.js(259,5): error TS2554: Expected 0 arguments, but got 3. +node_modules/graceful-fs/graceful-fs.js(220,70): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(269,3): error TS2554: Expected 0 arguments, but got 3. +node_modules/graceful-fs/graceful-fs.js(276,5): error TS2554: Expected 0 arguments, but got 3. From 929791868fc67d790cb156e34f0286d82196be23 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 5 Nov 2018 17:23:19 -0800 Subject: [PATCH 225/262] Make for..in expressions allowed to be null/undefined (#28348) --- src/compiler/checker.ts | 16 ++++++++++-- .../ambientWithStatements.errors.txt | 5 +--- .../forInStrictNullChecksNoError.errors.txt | 12 +++++++++ .../reference/forInStrictNullChecksNoError.js | 15 +++++++++++ .../forInStrictNullChecksNoError.symbols | 20 +++++++++++++++ .../forInStrictNullChecksNoError.types | 25 +++++++++++++++++++ .../reference/widenedTypes.errors.txt | 5 +--- .../compiler/forInStrictNullChecksNoError.ts | 7 ++++++ 8 files changed, 95 insertions(+), 10 deletions(-) create mode 100644 tests/baselines/reference/forInStrictNullChecksNoError.errors.txt create mode 100644 tests/baselines/reference/forInStrictNullChecksNoError.js create mode 100644 tests/baselines/reference/forInStrictNullChecksNoError.symbols create mode 100644 tests/baselines/reference/forInStrictNullChecksNoError.types create mode 100644 tests/cases/compiler/forInStrictNullChecksNoError.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5c187d6ad8a..b54b1393253 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4766,7 +4766,7 @@ namespace ts { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === SyntaxKind.ForInStatement) { - const indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + const indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); return indexType.flags & (TypeFlags.TypeParameter | TypeFlags.Index) ? getExtractStringType(indexType) : stringType; } @@ -15175,6 +15175,10 @@ namespace ts { } return declaredType; } + // for (const _ in ref) acts as a nonnull on ref + if (isVariableDeclaration(node) && node.parent.parent.kind === SyntaxKind.ForInStatement && isMatchingReference(reference, node.parent.parent.expression)) { + return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))); + } // Assignment doesn't affect reference return undefined; } @@ -18489,6 +18493,14 @@ namespace ts { ); } + function getNonNullableTypeIfNeeded(type: Type) { + const kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & TypeFlags.Nullable; + if (kind) { + return getNonNullableType(type); + } + return type; + } + function checkNonNullType( type: Type, node: Node, @@ -25286,7 +25298,7 @@ namespace ts { // Grammar checking checkGrammarForInOrForOfStatement(node); - const rightType = checkNonNullExpression(node.expression); + const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression)); // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement diff --git a/tests/baselines/reference/ambientWithStatements.errors.txt b/tests/baselines/reference/ambientWithStatements.errors.txt index 3e134970a1f..c7cb28a0f46 100644 --- a/tests/baselines/reference/ambientWithStatements.errors.txt +++ b/tests/baselines/reference/ambientWithStatements.errors.txt @@ -1,11 +1,10 @@ tests/cases/compiler/ambientWithStatements.ts(2,5): error TS1036: Statements are not allowed in ambient contexts. tests/cases/compiler/ambientWithStatements.ts(3,5): error TS1104: A 'continue' statement can only be used within an enclosing iteration statement. -tests/cases/compiler/ambientWithStatements.ts(7,15): error TS2531: Object is possibly 'null'. tests/cases/compiler/ambientWithStatements.ts(11,5): error TS1108: A 'return' statement can only be used within a function body. tests/cases/compiler/ambientWithStatements.ts(25,5): error TS2410: The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'. -==== tests/cases/compiler/ambientWithStatements.ts (5 errors) ==== +==== tests/cases/compiler/ambientWithStatements.ts (4 errors) ==== declare module M { break; ~~~~~ @@ -17,8 +16,6 @@ tests/cases/compiler/ambientWithStatements.ts(25,5): error TS2410: The 'with' st do { } while (true); var x; for (x in null) { } - ~~~~ -!!! error TS2531: Object is possibly 'null'. if (true) { } else { } 1; L: var y; diff --git a/tests/baselines/reference/forInStrictNullChecksNoError.errors.txt b/tests/baselines/reference/forInStrictNullChecksNoError.errors.txt new file mode 100644 index 00000000000..fd6bd4c8d8f --- /dev/null +++ b/tests/baselines/reference/forInStrictNullChecksNoError.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/forInStrictNullChecksNoError.ts(5,5): error TS2533: Object is possibly 'null' or 'undefined'. + + +==== tests/cases/compiler/forInStrictNullChecksNoError.ts (1 errors) ==== + function f(x: { [key: string]: number; } | null | undefined) { + for (const key in x) { // 1 + console.log(x[key]); // 2 + } + x["no"]; // should still error + ~ +!!! error TS2533: Object is possibly 'null' or 'undefined'. + } \ No newline at end of file diff --git a/tests/baselines/reference/forInStrictNullChecksNoError.js b/tests/baselines/reference/forInStrictNullChecksNoError.js new file mode 100644 index 00000000000..d6a036ec1d4 --- /dev/null +++ b/tests/baselines/reference/forInStrictNullChecksNoError.js @@ -0,0 +1,15 @@ +//// [forInStrictNullChecksNoError.ts] +function f(x: { [key: string]: number; } | null | undefined) { + for (const key in x) { // 1 + console.log(x[key]); // 2 + } + x["no"]; // should still error +} + +//// [forInStrictNullChecksNoError.js] +function f(x) { + for (var key in x) { // 1 + console.log(x[key]); // 2 + } + x["no"]; // should still error +} diff --git a/tests/baselines/reference/forInStrictNullChecksNoError.symbols b/tests/baselines/reference/forInStrictNullChecksNoError.symbols new file mode 100644 index 00000000000..861856fab0f --- /dev/null +++ b/tests/baselines/reference/forInStrictNullChecksNoError.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/forInStrictNullChecksNoError.ts === +function f(x: { [key: string]: number; } | null | undefined) { +>f : Symbol(f, Decl(forInStrictNullChecksNoError.ts, 0, 0)) +>x : Symbol(x, Decl(forInStrictNullChecksNoError.ts, 0, 11)) +>key : Symbol(key, Decl(forInStrictNullChecksNoError.ts, 0, 17)) + + for (const key in x) { // 1 +>key : Symbol(key, Decl(forInStrictNullChecksNoError.ts, 1, 14)) +>x : Symbol(x, Decl(forInStrictNullChecksNoError.ts, 0, 11)) + + console.log(x[key]); // 2 +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>x : Symbol(x, Decl(forInStrictNullChecksNoError.ts, 0, 11)) +>key : Symbol(key, Decl(forInStrictNullChecksNoError.ts, 1, 14)) + } + x["no"]; // should still error +>x : Symbol(x, Decl(forInStrictNullChecksNoError.ts, 0, 11)) +} diff --git a/tests/baselines/reference/forInStrictNullChecksNoError.types b/tests/baselines/reference/forInStrictNullChecksNoError.types new file mode 100644 index 00000000000..ffbc4af929d --- /dev/null +++ b/tests/baselines/reference/forInStrictNullChecksNoError.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/forInStrictNullChecksNoError.ts === +function f(x: { [key: string]: number; } | null | undefined) { +>f : (x: { [key: string]: number; } | null | undefined) => void +>x : { [key: string]: number; } | null | undefined +>key : string +>null : null + + for (const key in x) { // 1 +>key : string +>x : { [key: string]: number; } | null | undefined + + console.log(x[key]); // 2 +>console.log(x[key]) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>x[key] : number +>x : { [key: string]: number; } +>key : string + } + x["no"]; // should still error +>x["no"] : number +>x : { [key: string]: number; } | null | undefined +>"no" : "no" +} diff --git a/tests/baselines/reference/widenedTypes.errors.txt b/tests/baselines/reference/widenedTypes.errors.txt index fb6779ff0eb..1c3efb3a624 100644 --- a/tests/baselines/reference/widenedTypes.errors.txt +++ b/tests/baselines/reference/widenedTypes.errors.txt @@ -1,7 +1,6 @@ tests/cases/compiler/widenedTypes.ts(1,1): error TS2358: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter. tests/cases/compiler/widenedTypes.ts(4,1): error TS2531: Object is possibly 'null'. tests/cases/compiler/widenedTypes.ts(5,7): error TS2531: Object is possibly 'null'. -tests/cases/compiler/widenedTypes.ts(7,15): error TS2531: Object is possibly 'null'. tests/cases/compiler/widenedTypes.ts(9,14): error TS2695: Left side of comma operator is unused and has no side effects. tests/cases/compiler/widenedTypes.ts(10,1): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/widenedTypes.ts(17,1): error TS2322: Type '""' is not assignable to type 'number'. @@ -9,7 +8,7 @@ tests/cases/compiler/widenedTypes.ts(22,22): error TS2322: Type 'number' is not tests/cases/compiler/widenedTypes.ts(23,39): error TS2322: Type 'number' is not assignable to type 'string'. -==== tests/cases/compiler/widenedTypes.ts (9 errors) ==== +==== tests/cases/compiler/widenedTypes.ts (8 errors) ==== null instanceof (() => { }); ~~~~ !!! error TS2358: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter. @@ -23,8 +22,6 @@ tests/cases/compiler/widenedTypes.ts(23,39): error TS2322: Type 'number' is not !!! error TS2531: Object is possibly 'null'. for (var a in null) { } - ~~~~ -!!! error TS2531: Object is possibly 'null'. var t = [3, (3, null)]; ~ diff --git a/tests/cases/compiler/forInStrictNullChecksNoError.ts b/tests/cases/compiler/forInStrictNullChecksNoError.ts new file mode 100644 index 00000000000..61e4f665d49 --- /dev/null +++ b/tests/cases/compiler/forInStrictNullChecksNoError.ts @@ -0,0 +1,7 @@ +// @strictNullChecks: true +function f(x: { [key: string]: number; } | null | undefined) { + for (const key in x) { // 1 + console.log(x[key]); // 2 + } + x["no"]; // should still error +} \ No newline at end of file From aa023eb6e32205d4c43b89ee425c4b411ca0e0c1 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 5 Nov 2018 18:04:57 -0800 Subject: [PATCH 226/262] Remove TypeFlags.UnionOfPrimitiveTypes --- src/compiler/checker.ts | 34 ++++++++++++++++++++-------------- src/compiler/types.ts | 13 +++++++------ 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 5c187d6ad8a..4bd2dd54908 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9012,7 +9012,7 @@ namespace ts { neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : TypeFlags.UnionOfPrimitiveTypes, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, !(includes & TypeFlags.NotPrimitiveUnion), aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures: ReadonlyArray): TypePredicate | undefined { @@ -9052,7 +9052,7 @@ namespace ts { } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types: Type[], unionOfUnitTypes: TypeFlags, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getUnionTypeFromSortedList(types: Type[], primitiveTypesOnly: boolean, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { if (types.length === 0) { return neverType; } @@ -9063,9 +9063,10 @@ namespace ts { let type = unionTypes.get(id); if (!type) { const propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); - type = createType(TypeFlags.Union | propagatedFlags | unionOfUnitTypes); + type = createType(TypeFlags.Union | propagatedFlags); unionTypes.set(id, type); type.types = types; + type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -9157,13 +9158,16 @@ namespace ts { // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types: Type[]) { let unionTypes: UnionType[] | undefined; - const index = findIndex(types, t => (t.flags & TypeFlags.UnionOfPrimitiveTypes) !== 0); + const index = findIndex(types, t => !!(t.flags & TypeFlags.Union) && (t).primitiveTypesOnly); + if (index < 0) { + return false; + } let i = index + 1; // Remove all but the first union of primitive types and collect them in // the unionTypes array. while (i < types.length) { const t = types[i]; - if (t.flags & TypeFlags.UnionOfPrimitiveTypes) { + if (t.flags & TypeFlags.Union && (t).primitiveTypesOnly) { (unionTypes || (unionTypes = [types[index]])).push(t); orderedRemoveItemAt(types, i); } @@ -9190,7 +9194,7 @@ namespace ts { } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, TypeFlags.UnionOfPrimitiveTypes); + types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); return true; } @@ -9232,7 +9236,7 @@ namespace ts { return typeSet[0]; } if (includes & TypeFlags.Union) { - if (includes & TypeFlags.UnionOfPrimitiveTypes && intersectUnionsOfPrimitiveTypes(typeSet)) { + if (intersectUnionsOfPrimitiveTypes(typeSet)) { // When the intersection creates a reduced set (which might mean that *all* union types have // disappeared), we restart the operation to get a new set of combined flags. Once we have // reduced we'll never reduce again, so this occurs at most once. @@ -11809,12 +11813,14 @@ namespace ts { } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) { - const sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); - if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo); + function findMatchingDiscriminantType(source: Type, target: Type) { + if (target.flags & TypeFlags.Union) { + const sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); + if (sourcePropertiesFiltered) { + return discriminateTypeByDiscriminableItems(target, map(sourcePropertiesFiltered, p => ([() => getTypeOfSymbol(p), p.escapedName] as [() => Type, __String])), isRelatedTo); + } } } return undefined; @@ -14846,7 +14852,7 @@ namespace ts { if (type.flags & TypeFlags.Union) { const types = (type).types; const filtered = filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & TypeFlags.UnionOfPrimitiveTypes); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, (type).primitiveTypesOnly); } return f(type) ? type : neverType; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 46a5ed91275..0ca4de3f537 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3838,13 +3838,11 @@ namespace ts { /* @internal */ FreshLiteral = 1 << 27, // Fresh literal or unique type /* @internal */ - UnionOfPrimitiveTypes = 1 << 28, // Type is union of primitive types + ContainsWideningType = 1 << 28, // Type is or contains undefined or null widening type /* @internal */ - ContainsWideningType = 1 << 29, // Type is or contains undefined or null widening type + ContainsObjectLiteral = 1 << 29, // Type is or contains object literal type /* @internal */ - ContainsObjectLiteral = 1 << 30, // Type is or contains object literal type - /* @internal */ - ContainsAnyFunctionType = 1 << 31, // Type is or contains the anyFunctionType + ContainsAnyFunctionType = 1 << 30, // Type is or contains the anyFunctionType /* @internal */ AnyOrUnknown = Any | Unknown, @@ -4077,7 +4075,10 @@ namespace ts { couldContainTypeVariables: boolean; } - export interface UnionType extends UnionOrIntersectionType { } + export interface UnionType extends UnionOrIntersectionType { + /* @internal */ + primitiveTypesOnly: boolean; + } export interface IntersectionType extends UnionOrIntersectionType { /* @internal */ From 76a742191f79456f8ff8cb214a2eadd9b8676506 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 6 Nov 2018 06:25:10 -0800 Subject: [PATCH 227/262] Remove usage of TypeFlags.FreshLiteral for fresh literal types --- src/compiler/checker.ts | 45 ++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4bd2dd54908..589239bce51 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -408,11 +408,13 @@ namespace ts { const regularFalseType = createIntrinsicType(TypeFlags.BooleanLiteral, "false") as FreshableIntrinsicType; const trueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; const regularTrueType = createIntrinsicType(TypeFlags.BooleanLiteral, "true") as FreshableIntrinsicType; - falseType.flags |= TypeFlags.FreshLiteral; - trueType.flags |= TypeFlags.FreshLiteral; trueType.regularType = regularTrueType; + trueType.freshType = trueType; + regularTrueType.regularType = regularTrueType; regularTrueType.freshType = trueType; falseType.regularType = regularFalseType; + falseType.freshType = falseType; + regularFalseType.regularType = regularFalseType; regularFalseType.freshType = falseType; const booleanType = createBooleanType([regularFalseType, regularTrueType]); // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false` @@ -8969,7 +8971,7 @@ namespace ts { t.flags & TypeFlags.NumberLiteral && includes & TypeFlags.Number || t.flags & TypeFlags.BigIntLiteral && includes & TypeFlags.BigInt || t.flags & TypeFlags.UniqueESSymbol && includes & TypeFlags.ESSymbol || - t.flags & TypeFlags.Literal && t.flags & TypeFlags.FreshLiteral && containsType(types, (t).regularType); + isFreshLiteralType(t) && containsType(types, (t).regularType); if (remove) { orderedRemoveItemAt(types, i); } @@ -10039,10 +10041,11 @@ namespace ts { } function getFreshTypeOfLiteralType(type: Type): Type { - if (type.flags & TypeFlags.Literal && !(type.flags & TypeFlags.FreshLiteral)) { - if (!(type).freshType) { // NOTE: Safe because all freshable intrinsics always have fresh types already - const freshType = createLiteralType(type.flags | TypeFlags.FreshLiteral, (type).value, (type).symbol); + if (type.flags & TypeFlags.Literal) { + if (!(type).freshType) { + const freshType = createLiteralType(type.flags, (type).value, (type).symbol); freshType.regularType = type; + freshType.freshType = freshType; (type).freshType = freshType; } return (type).freshType; @@ -10051,11 +10054,15 @@ namespace ts { } function getRegularTypeOfLiteralType(type: Type): Type { - return type.flags & TypeFlags.Literal && type.flags & TypeFlags.FreshLiteral ? (type).regularType : + return type.flags & TypeFlags.Literal ? (type).regularType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getRegularTypeOfLiteralType)) : type; } + function isFreshLiteralType(type: Type) { + return !!(type.flags & TypeFlags.Literal) && (type).freshType === type; + } + function getLiteralType(value: string | number | PseudoBigInt, enumId?: number, symbol?: Symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', // where NNN is the text representation of a numeric literal and SSS are the characters @@ -10069,6 +10076,7 @@ namespace ts { typeof value === "string" ? TypeFlags.StringLiteral : TypeFlags.BigIntLiteral) | (enumId ? TypeFlags.EnumLiteral : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + type.regularType = type; } return type; } @@ -11340,10 +11348,10 @@ namespace ts { } function isTypeRelatedTo(source: Type, target: Type, relation: Map) { - if (source.flags & TypeFlags.Literal && source.flags & TypeFlags.FreshLiteral) { + if (isFreshLiteralType(source)) { source = (source).regularType; } - if (target.flags & TypeFlags.Literal && target.flags & TypeFlags.FreshLiteral) { + if (isFreshLiteralType(target)) { target = (target).regularType; } if (source === target || @@ -11498,10 +11506,10 @@ namespace ts { * * Ternary.False if they are not related. */ function isRelatedTo(source: Type, target: Type, reportErrors = false, headMessage?: DiagnosticMessage, isApparentIntersectionConstituent?: boolean): Ternary { - if (source.flags & TypeFlags.Literal && source.flags & TypeFlags.FreshLiteral) { + if (isFreshLiteralType(source)) { source = (source).regularType; } - if (target.flags & TypeFlags.Literal && target.flags & TypeFlags.FreshLiteral) { + if (isFreshLiteralType(target)) { target = (target).regularType; } if (source.flags & TypeFlags.Substitution) { @@ -13113,11 +13121,11 @@ namespace ts { } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.EnumLiteral && type.flags & TypeFlags.FreshLiteral ? getBaseTypeOfEnumLiteralType(type) : - type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : - type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : - type.flags & TypeFlags.BigIntLiteral && type.flags & TypeFlags.FreshLiteral ? bigintType : - type.flags & TypeFlags.BooleanLiteral && type.flags & TypeFlags.FreshLiteral ? booleanType : + return type.flags & TypeFlags.EnumLiteral && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) : + type.flags & TypeFlags.StringLiteral && isFreshLiteralType(type) ? stringType : + type.flags & TypeFlags.NumberLiteral && isFreshLiteralType(type) ? numberType : + type.flags & TypeFlags.BigIntLiteral && isFreshLiteralType(type) ? bigintType : + type.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(type) ? booleanType : type.flags & TypeFlags.Union ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; } @@ -14530,7 +14538,7 @@ namespace ts { return assignedType; } let reducedType = filterType(declaredType, t => typeMaybeAssignableTo(assignedType, t)); - if (assignedType.flags & TypeFlags.FreshLiteral && assignedType.flags & TypeFlags.BooleanLiteral) { + if (assignedType.flags & TypeFlags.BooleanLiteral && isFreshLiteralType(assignedType)) { reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types } // Our crude heuristic produces an invalid result in some cases: see GH#26130. @@ -28768,8 +28776,7 @@ namespace ts { function isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { - const type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & TypeFlags.Literal && type.flags & TypeFlags.FreshLiteral); + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node))); } return false; } From a323d98512c1d962985cd06d1de82bc5ee343cb9 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Tue, 6 Nov 2018 08:57:05 -0800 Subject: [PATCH 228/262] Update user baselines (#28371) --- .../user/chrome-devtools-frontend.log | 54 +++++++++---------- tests/baselines/reference/user/clone.log | 4 +- tests/baselines/reference/user/lodash.log | 6 +-- tests/baselines/reference/user/npm.log | 2 - tests/baselines/reference/user/uglify-js.log | 2 +- 5 files changed, 33 insertions(+), 35 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index bd38799ab19..00abd3fd7c5 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -3366,7 +3366,7 @@ node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(2856,10): error node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(2858,32): error TS2339: Property 'left' does not exist on type 'never'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(2858,49): error TS2339: Property 'right' does not exist on type 'never'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(3034,25): error TS2339: Property 'xRel' does not exist on type 'Pos'. -node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(4840,5): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(4840,5): 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/cm/codemirror.js(5675,35): error TS2339: Property 'line' does not exist on type 'LineWidget'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(5675,61): error TS2339: Property 'line' does not exist on type 'LineWidget'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(5693,57): error TS2339: Property 'line' does not exist on type 'LineWidget'. @@ -3428,7 +3428,7 @@ node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7777,11): error node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7827,32): error TS2339: Property 'lineDiv' does not exist on type 'Display'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7827,41): error TS2339: Property 'textRendering' does not exist on type 'CSSStyleDeclaration'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7828,15): error TS2339: Property 'lineDiv' does not exist on type 'Display'. -node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7895,25): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(7895,25): 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/cm/codemirror.js(8658,17): error TS2339: Property 'outside' does not exist on type 'Pos'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(8659,54): error TS2339: Property 'hitSide' does not exist on type 'Pos'. node_modules/chrome-devtools-frontend/front_end/cm/codemirror.js(8680,19): error TS2339: Property 'div' does not exist on type 'ContentEditableInput'. @@ -4384,8 +4384,8 @@ node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(74, node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(81,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(116,28): error TS2322: Type '{ cookies: Cookie[]; }' is not assignable to type '{ folderName: string; cookies: Cookie[]; }'. Property 'folderName' is missing in type '{ cookies: Cookie[]; }'. -node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(320,33): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(320,52): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(320,33): 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/cookie_table/CookiesTable.js(320,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/cookie_table/CookiesTable.js(346,21): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(347,19): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(348,22): error TS2555: Expected at least 2 arguments, but got 1. @@ -4941,11 +4941,11 @@ node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(43,25): error TS269 node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,116): error TS2322: Type 'string[]' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. Property 'chars1' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,240): error TS2322: Type '0' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. -node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,321): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,321): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,352): error TS2365: Operator '<=' cannot be applied to types 'number' and '{ chars1: string; chars2: string; lineArray: string[]; }'. -node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,375): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,375): 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/diff/diff_match_patch.js(6,379): error TS2365: Operator '+' cannot be applied to types '{ chars1: string; chars2: string; lineArray: string[]; }' and 'number'. -node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,388): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,388): 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/diff/diff_match_patch.js(6,476): error TS2322: Type '0' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(13,201): error TS2403: Subsequent variable declarations must have the same type. Variable 'd' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(15,142): error TS2403: Subsequent variable declarations must have the same type. Variable 'd' must be of type 'any', but here has type 'any[]'. @@ -5492,11 +5492,11 @@ node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(1 node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(164,22): error TS2339: Property 'toFixedIfFloating' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(179,18): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(183,9): error TS2322: Type 'number' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(183,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(183,17): 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/elements/MetricsSidebarPane.js(186,21): error TS2339: Property 'toFixedIfFloating' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(195,18): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(199,9): error TS2322: Type 'number' is not assignable to type 'string'. -node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(199,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(199,18): 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/elements/MetricsSidebarPane.js(202,21): error TS2339: Property 'toFixedIfFloating' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(235,7): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/MetricsSidebarPane.js(235,35): error TS2555: Expected at least 2 arguments, but got 1. @@ -5572,7 +5572,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(68 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(704,36): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(716,22): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(716,38): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(724,7): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(724,7): 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/elements/StylesSidebarPane.js(758,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(762,18): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(763,39): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -5631,7 +5631,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(12 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1296,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1325,43): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string | string[]'. Type 'TemplateStringsArray' is not assignable to type 'string[]'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1346,7): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1346,7): 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/elements/StylesSidebarPane.js(1346,33): error TS2339: Property '_updateFilter' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1349,77): error TS2339: Property 'deepTextContent' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1363,30): error TS2339: Property 'selectors' does not exist on type 'CSSRule'. @@ -5680,7 +5680,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(19 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1984,25): error TS2339: Property 'key' does not exist on type 'CSSRule'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1987,17): error TS2339: Property 'setKeyText' does not exist on type 'CSSRule'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2018,64): error TS2339: Property 'key' does not exist on type 'CSSRule'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2109,7): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2109,7): 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/elements/StylesSidebarPane.js(2109,46): error TS2339: Property '_updateFilter' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2148,30): error TS2694: Namespace 'SDK.CSSModel' has no exported member 'ContrastInfo'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2266,49): error TS2339: Property 'section' does not exist on type 'TreeOutline'. @@ -5729,7 +5729,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(26 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2699,49): error TS2694: Namespace 'Elements.StylePropertyTreeElement' has no exported member 'Context'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2715,49): error TS2694: Namespace 'Elements.StylePropertyTreeElement' has no exported member 'Context'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2750,49): error TS2694: Namespace 'Elements.StylePropertyTreeElement' has no exported member 'Context'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2765,40): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2765,40): 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/elements/StylesSidebarPane.js(2769,7): error TS2322: Type 'StylePropertyTreeElement' is not assignable to type 'this'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2780,32): error TS2339: Property 'isWhitespace' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2785,32): error TS2339: Property 'focus' does not exist on type 'Element'. @@ -5739,7 +5739,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(28 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2838,73): error TS2339: Property 'nameElement' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2838,99): error TS2339: Property 'valueElement' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2839,25): error TS2339: Property 'startEditing' does not exist on type 'TreeElement'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2849,61): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2849,61): 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/elements/StylesSidebarPane.js(2857,9): error TS2322: Type 'StylePropertyTreeElement' is not assignable to type 'this'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2906,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2910,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. @@ -6370,7 +6370,7 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js( node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(527,43): error TS2339: Property 'startNode' does not exist on type 'Parser'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(528,8): error TS2339: Property 'nextToken' does not exist on type 'Parser'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(529,15): error TS2339: Property 'parseTopLevel' does not exist on type 'Parser'. -node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(1674,55): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(1674,55): 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/formatter_worker/acorn/acorn.js(2451,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(2451,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. node_modules/chrome-devtools-frontend/front_end/formatter_worker/acorn/acorn.js(2451,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. @@ -6538,7 +6538,7 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2510,16): error TS2339: Property 'isArray' does not exist on type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2524,18): error TS2339: Property 'rawName' does not exist on type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2527,16): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. -node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2527,30): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2527,30): 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/heap_snapshot_worker/HeapSnapshot.js(2541,17): error TS2339: Property 'isUserRoot' does not exist on type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2541,38): error TS2339: Property 'isDocumentDOMTreesRoot' does not exist on type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2629,14): error TS2403: Subsequent variable declarations must have the same type. Variable 'iter' must be of type 'HeapSnapshotEdgeIterator', but here has type 'any'. @@ -7754,10 +7754,10 @@ node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSectio node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(923,51): error TS2339: Property 'parentObject' does not exist on type 'RemoteObjectProperty'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(924,51): error TS2339: Property 'parentObject' does not exist on type 'RemoteObjectProperty'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(980,18): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1153,23): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1153,23): 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/object_ui/ObjectPropertiesSection.js(1182,26): error TS2339: Property '_readOnly' does not exist on type 'ObjectPropertyTreeElement'. -node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1211,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1211,44): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1211,20): 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/object_ui/ObjectPropertiesSection.js(1211,44): 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/object_ui/ObjectPropertiesSection.js(1241,23): error TS2339: Property 'parentObject' does not exist on type 'RemoteObjectProperty'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1243,26): error TS2339: Property '_readOnly' does not exist on type 'ObjectPropertyTreeElement'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(1319,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -7781,7 +7781,7 @@ node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFor node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(127,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(136,26): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(137,26): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(149,19): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(149,19): 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/object_ui/RemoteObjectPreviewFormatter.js(161,23): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(167,23): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/RemoteObjectPreviewFormatter.js(171,23): error TS2339: Property 'createTextChild' does not exist on type 'Element'. @@ -7806,7 +7806,7 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(67,47): node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(131,41): error TS2339: Property 'offsetWidth' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(133,46): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(182,27): error TS2339: Property 'shiftKey' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(182,38): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(182,38): 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/perf_ui/ChartViewport.js(183,46): error TS2339: Property 'wheelDeltaY' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(183,72): error TS2339: Property 'wheelDeltaX' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/ChartViewport.js(184,55): error TS2339: Property 'wheelDeltaX' does not exist on type 'Event'. @@ -8016,7 +8016,7 @@ node_modules/chrome-devtools-frontend/front_end/performance_test_runner/Timeline node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(355,13): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(67,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(155,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(315,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(315,20): 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/persistence/Automapping.js(329,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(355,41): error TS2339: Property 'reverse' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(363,44): error TS2339: Property 'reverse' does not exist on type 'string'. @@ -8150,8 +8150,8 @@ node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(275,8): er node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(320,8): error TS2339: Property 'naturalOrderComparator' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(335,19): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(336,19): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(342,18): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(342,27): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(342,18): 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/platform/utilities.js(342,27): 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/platform/utilities.js(364,8): error TS2339: Property 'caseInsensetiveComparator' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(378,8): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(391,8): error TS2339: Property 'gcd' does not exist on type 'NumberConstructor'. @@ -9758,7 +9758,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/CookieModel.js(114,38): erro node_modules/chrome-devtools-frontend/front_end/sdk/CookieModel.js(129,38): error TS2339: Property 'networkAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/CookieParser.js(246,25): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/sdk/CookieParser.js(250,33): error TS2694: Namespace 'Protocol' has no exported member 'Network'. -node_modules/chrome-devtools-frontend/front_end/sdk/CookieParser.js(325,53): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/sdk/CookieParser.js(325,53): 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/sdk/DOMDebuggerModel.js(11,26): error TS2339: Property 'domdebuggerAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(232,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMDebuggerModel.js(275,24): error TS2694: Namespace 'Protocol' has no exported member 'DOMDebugger'. @@ -11730,7 +11730,7 @@ node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(503,30 node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(641,59): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(641,92): error TS2339: Property 'testRunner' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(642,3): error TS2322: Type '1' is not assignable to type 'boolean'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(683,28): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(683,28): 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/test_runner/TestRunner.js(717,24): error TS2694: Namespace 'TestRunner' has no exported member 'CustomFormatters'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(748,24): error TS2694: Namespace 'TestRunner' has no exported member 'CustomFormatters'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(777,22): error TS2339: Property 'attributes' does not exist on type 'Node'. @@ -12934,7 +12934,7 @@ node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(276,35): error node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(279,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(291,15): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(347,27): error TS2339: Property 'createChild' does not exist on type 'HTMLSelectElement'. -node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(376,7): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(376,7): 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/ui/ListWidget.js(378,24): error TS2339: Property 'disabled' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(395,18): error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(402,28): error TS2339: Property 'disabled' does not exist on type 'Element'. diff --git a/tests/baselines/reference/user/clone.log b/tests/baselines/reference/user/clone.log index 2176908b848..1aa3a2c2fe5 100644 --- a/tests/baselines/reference/user/clone.log +++ b/tests/baselines/reference/user/clone.log @@ -2,11 +2,11 @@ Exit Code: 1 Standard output: node_modules/clone/clone.js(167,16): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. node_modules/clone/clone.js(167,23): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. -node_modules/clone/clone.js(167,43): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +node_modules/clone/clone.js(167,43): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. node_modules/clone/clone.js(176,14): error TS2532: Object is possibly 'undefined'. node_modules/clone/clone.js(186,16): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'string', but here has type 'number'. node_modules/clone/clone.js(186,23): error TS2365: Operator '<' cannot be applied to types 'string' and 'number'. -node_modules/clone/clone.js(186,52): error TS2356: An arithmetic operand must be of type 'any', 'number' or an enum type. +node_modules/clone/clone.js(186,52): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index f26218b780d..6dd4a9d5992 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -26,9 +26,9 @@ node_modules/lodash/_arrayReduceRight.js(16,19): error TS2532: Object is possibl node_modules/lodash/_arrayReduceRight.js(19,41): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arraySome.js(16,19): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_asciiWords.js(8,20): error TS8024: JSDoc '@param' tag has name 'The', but there is no parameter with that name. -node_modules/lodash/_baseClone.js(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -node_modules/lodash/_baseClone.js(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -node_modules/lodash/_baseClone.js(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/lodash/_baseClone.js(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +node_modules/lodash/_baseClone.js(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +node_modules/lodash/_baseClone.js(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/lodash/_baseClone.js(115,33): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean | undefined'. node_modules/lodash/_baseClone.js(128,43): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean | undefined'. node_modules/lodash/_baseClone.js(157,17): error TS2552: Cannot find name 'keysIn'. Did you mean 'keys'? diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 37c97f611a0..459a4562c24 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -1546,8 +1546,6 @@ node_modules/npm/test/tap/scripts-whitespace-windows.js(38,47): error TS2339: Pr node_modules/npm/test/tap/search.all-package-search.js(3,18): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/tap/search.all-package-search.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/search.all-package-search.js(8,21): error TS2307: Cannot find module 'tacks'. -node_modules/npm/test/tap/search.all-package-search.js(151,19): error TS2532: Object is possibly 'undefined'. -node_modules/npm/test/tap/search.all-package-search.js(152,26): error TS2532: Object is possibly 'undefined'. node_modules/npm/test/tap/search.esearch.js(4,18): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/tap/search.esearch.js(9,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/search.esearch.js(33,9): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 56c7d551683..8faa9c30925 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -66,7 +66,7 @@ node_modules/uglify-js/lib/output.js(246,9): error TS2554: Expected 0 arguments, node_modules/uglify-js/lib/output.js(475,22): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(767,23): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(1163,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/output.js(1445,58): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +node_modules/uglify-js/lib/output.js(1445,58): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/uglify-js/lib/parse.js(367,20): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. node_modules/uglify-js/lib/parse.js(449,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. From 772f6cdf48835f1d08a8e8df884131a56b34a180 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 6 Nov 2018 09:54:23 -0800 Subject: [PATCH 229/262] Remove JSDocTag#atToken (#28376) --- src/compiler/factory.ts | 1 - src/compiler/parser.ts | 93 ++++++++----------- src/compiler/types.ts | 2 - src/services/classifier.ts | 2 +- ...ocComments.parsesCorrectly.@link tags.json | 5 - ...ts.parsesCorrectly.Nested @param tags.json | 10 -- ...parsesCorrectly.argSynonymForParamTag.json | 5 - ...sCorrectly.argumentSynonymForParamTag.json | 5 - ...ments.parsesCorrectly.leadingAsterisk.json | 5 - ...less-than and greater-than characters.json | 5 - ...nts.parsesCorrectly.noLeadingAsterisk.json | 5 - ...Comments.parsesCorrectly.noReturnType.json | 5 - ...cComments.parsesCorrectly.oneParamTag.json | 5 - ...DocComments.parsesCorrectly.paramTag1.json | 5 - ...arsesCorrectly.paramTagBracketedName1.json | 5 - ...arsesCorrectly.paramTagBracketedName2.json | 5 - ...parsesCorrectly.paramTagNameThenType1.json | 5 - ...parsesCorrectly.paramTagNameThenType2.json | 5 - ...ents.parsesCorrectly.paramWithoutType.json | 5 - ...ocComments.parsesCorrectly.returnTag1.json | 5 - ...ocComments.parsesCorrectly.returnTag2.json | 5 - ...cComments.parsesCorrectly.returnsTag1.json | 5 - ...cComments.parsesCorrectly.templateTag.json | 5 - ...Comments.parsesCorrectly.templateTag2.json | 5 - ...Comments.parsesCorrectly.templateTag3.json | 5 - ...Comments.parsesCorrectly.templateTag4.json | 5 - ...Comments.parsesCorrectly.templateTag5.json | 5 - ...Comments.parsesCorrectly.templateTag6.json | 5 - ...Comments.parsesCorrectly.twoParamTag2.json | 10 -- ...parsesCorrectly.twoParamTagOnSameLine.json | 10 -- .../DocComments.parsesCorrectly.typeTag.json | 5 - ...sCorrectly.typedefTagWithChildrenTags.json | 15 --- .../reference/api/tsserverlibrary.d.ts | 2 - tests/baselines/reference/api/typescript.d.ts | 2 - 34 files changed, 40 insertions(+), 227 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 160376c39b2..ec19d2c906c 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2225,7 +2225,6 @@ namespace ts { /* @internal */ function createJSDocTag(kind: T["kind"], tagName: string): T { const node = createSynthesizedNode(kind) as T; - node.atToken = createToken(SyntaxKind.AtToken); node.tagName = createIdentifier(tagName); return node; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 6831d27db9c..21122b5f7ed 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6548,8 +6548,7 @@ namespace ts { function parseTag(indent: number) { Debug.assert(token() === SyntaxKind.AtToken); - const atToken = createNode(SyntaxKind.AtToken, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); + const start = scanner.getTokenPos(); nextJSDocToken(); const tagName = parseJSDocIdentifierName(/*message*/ undefined); @@ -6559,40 +6558,40 @@ namespace ts { switch (tagName.escapedText) { case "augments": case "extends": - tag = parseAugmentsTag(atToken, tagName); + tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseClassTag(atToken, tagName); + tag = parseClassTag(start, tagName); break; case "this": - tag = parseThisTag(atToken, tagName); + tag = parseThisTag(start, tagName); break; case "enum": - tag = parseEnumTag(atToken, tagName); + tag = parseEnumTag(start, tagName); break; case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(atToken, tagName, PropertyLikeParse.Parameter, indent); + return parseParameterOrPropertyTag(start, tagName, PropertyLikeParse.Parameter, indent); case "return": case "returns": - tag = parseReturnTag(atToken, tagName); + tag = parseReturnTag(start, tagName); break; case "template": - tag = parseTemplateTag(atToken, tagName); + tag = parseTemplateTag(start, tagName); break; case "type": - tag = parseTypeTag(atToken, tagName); + tag = parseTypeTag(start, tagName); break; case "typedef": - tag = parseTypedefTag(atToken, tagName, indent); + tag = parseTypedefTag(start, tagName, indent); break; case "callback": - tag = parseCallbackTag(atToken, tagName, indent); + tag = parseCallbackTag(start, tagName, indent); break; default: - tag = parseUnknownTag(atToken, tagName); + tag = parseUnknownTag(start, tagName); break; } @@ -6675,9 +6674,8 @@ namespace ts { return comments.length === 0 ? undefined : comments.join(""); } - function parseUnknownTag(atToken: AtToken, tagName: Identifier) { - const result = createNode(SyntaxKind.JSDocTag, atToken.pos); - result.atToken = atToken; + function parseUnknownTag(start: number, tagName: Identifier) { + const result = createNode(SyntaxKind.JSDocTag, start); result.tagName = tagName; return finishNode(result); } @@ -6734,7 +6732,7 @@ namespace ts { } } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag(start: number, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -6747,15 +6745,14 @@ namespace ts { } const result = target === PropertyLikeParse.Property ? - createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) : - createNode(SyntaxKind.JSDocParameterTag, atToken.pos); - const comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + createNode(SyntaxKind.JSDocPropertyTag, start) : + createNode(SyntaxKind.JSDocParameterTag, start); + const comment = parseTagComments(indent + scanner.getStartPos() - start); const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } - result.atToken = atToken; result.tagName = tagName; result.typeExpression = typeExpression; result.name = name; @@ -6789,33 +6786,30 @@ namespace ts { } } - function parseReturnTag(atToken: AtToken, tagName: Identifier): JSDocReturnTag { + function parseReturnTag(start: number, tagName: Identifier): JSDocReturnTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocReturnTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); } - const result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocReturnTag, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } - function parseTypeTag(atToken: AtToken, tagName: Identifier): JSDocTypeTag { + function parseTypeTag(start: number, tagName: Identifier): JSDocTypeTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), Diagnostics._0_tag_already_specified, tagName.escapedText); } - const result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocTypeTag, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } - function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag { - const result = createNode(SyntaxKind.JSDocAugmentsTag, atToken.pos); - result.atToken = atToken; + function parseAugmentsTag(start: number, tagName: Identifier): JSDocAugmentsTag { + const result = createNode(SyntaxKind.JSDocAugmentsTag, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); @@ -6844,37 +6838,33 @@ namespace ts { return node; } - function parseClassTag(atToken: AtToken, tagName: Identifier): JSDocClassTag { - const tag = createNode(SyntaxKind.JSDocClassTag, atToken.pos); - tag.atToken = atToken; + function parseClassTag(start: number, tagName: Identifier): JSDocClassTag { + const tag = createNode(SyntaxKind.JSDocClassTag, start); tag.tagName = tagName; return finishNode(tag); } - function parseThisTag(atToken: AtToken, tagName: Identifier): JSDocThisTag { - const tag = createNode(SyntaxKind.JSDocThisTag, atToken.pos); - tag.atToken = atToken; + function parseThisTag(start: number, tagName: Identifier): JSDocThisTag { + const tag = createNode(SyntaxKind.JSDocThisTag, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseEnumTag(atToken: AtToken, tagName: Identifier): JSDocEnumTag { - const tag = createNode(SyntaxKind.JSDocEnumTag, atToken.pos); - tag.atToken = atToken; + function parseEnumTag(start: number, tagName: Identifier): JSDocEnumTag { + const tag = createNode(SyntaxKind.JSDocEnumTag, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } - function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag { + function parseTypedefTag(start: number, tagName: Identifier, indent: number): JSDocTypedefTag { const typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); - const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, atToken.pos); - typedefTag.atToken = atToken; + const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -6887,7 +6877,6 @@ namespace ts { let child: JSDocTypeTag | JSDocPropertyTag | false; let jsdocTypeLiteral: JSDocTypeLiteral | undefined; let childTypeTag: JSDocTypeTag | undefined; - const start = atToken.pos; while (child = tryParse(() => parseChildPropertyTag(indent))) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); @@ -6941,9 +6930,8 @@ namespace ts { return typeNameOrNamespaceName; } - function parseCallbackTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocCallbackTag { - const callbackTag = createNode(SyntaxKind.JSDocCallbackTag, atToken.pos) as JSDocCallbackTag; - callbackTag.atToken = atToken; + function parseCallbackTag(start: number, tagName: Identifier, indent: number): JSDocCallbackTag { + const callbackTag = createNode(SyntaxKind.JSDocCallbackTag, start) as JSDocCallbackTag; callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); @@ -6951,7 +6939,6 @@ namespace ts { callbackTag.comment = parseTagComments(indent); let child: JSDocParameterTag | false; - const start = scanner.getStartPos(); const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature; jsdocSignature.parameters = []; while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag)) { @@ -7039,8 +7026,7 @@ namespace ts { function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { Debug.assert(token() === SyntaxKind.AtToken); - const atToken = createNode(SyntaxKind.AtToken); - atToken.end = scanner.getTextPos(); + const start = scanner.getStartPos(); nextJSDocToken(); const tagName = parseJSDocIdentifierName(); @@ -7048,7 +7034,7 @@ namespace ts { let t: PropertyLikeParse; switch (tagName.escapedText) { case "type": - return target === PropertyLikeParse.Property && parseTypeTag(atToken, tagName); + return target === PropertyLikeParse.Property && parseTypeTag(start, tagName); case "prop": case "property": t = PropertyLikeParse.Property; @@ -7064,10 +7050,10 @@ namespace ts { if (!(target & t)) { return false; } - return parseParameterOrPropertyTag(atToken, tagName, target, indent); + return parseParameterOrPropertyTag(start, tagName, target, indent); } - function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag { + function parseTemplateTag(start: number, tagName: Identifier): JSDocTemplateTag { // the template tag looks like '@template {Constraint} T,U,V' let constraint: JSDocTypeExpression | undefined; if (token() === SyntaxKind.OpenBraceToken) { @@ -7085,8 +7071,7 @@ namespace ts { typeParameters.push(typeParameter); } while (parseOptionalJsdoc(SyntaxKind.CommaToken)); - const result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); - result.atToken = atToken; + const result = createNode(SyntaxKind.JSDocTemplateTag, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 46a5ed91275..f5c996eed87 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -719,7 +719,6 @@ namespace ts { export type AsteriskToken = Token; export type EqualsGreaterThanToken = Token; export type EndOfFileToken = Token & JSDocContainer; - export type AtToken = Token; export type ReadonlyToken = Token; export type AwaitKeywordToken = Token; export type PlusToken = Token; @@ -2421,7 +2420,6 @@ namespace ts { export interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 26d77ffc602..f85a69681de 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -703,7 +703,7 @@ namespace ts { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, ClassificationType.punctuation); // "@" + pushClassification(tag.pos, 1, ClassificationType.punctuation); // "@" pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, ClassificationType.docCommentTagName); // e.g. "param" pos = tag.tagName.end; diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json index c694d240371..73f9fb3b8b0 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json @@ -7,11 +7,6 @@ "kind": "JSDocTag", "pos": 63, "end": 68, - "atToken": { - "kind": "AtToken", - "pos": 63, - "end": 64 - }, "tagName": { "kind": "Identifier", "pos": 64, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json index f75d1e5fc6b..10ae7a71097 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 6, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 6, - "end": 7 - }, "tagName": { "kind": "Identifier", "pos": 7, @@ -31,11 +26,6 @@ "kind": "JSDocParameterTag", "pos": 34, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 34, - "end": 35 - }, "tagName": { "kind": "Identifier", "pos": 35, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json index cde6addda7c..6859d67c4c2 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 42, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json index f193bc3fe9e..16874177ac9 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 47, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json index 37d4610f987..3e5137d7b4d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 7, "end": 59, - "atToken": { - "kind": "AtToken", - "pos": 7, - "end": 8 - }, "tagName": { "kind": "Identifier", "pos": 8, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json index 204ba39d3dd..92bce57f68c 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 15, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json index f5eee243cf5..be925823222 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 32, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json index cbbb64b5a73..8383a0401dd 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 57, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json index a27e0d158e2..98ea87a26bd 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 59, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json index d271a3b3483..e381cf9329b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json index 7a1c85b25d6..7af573ee0b3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 29, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json index 57ab44a68b7..ca20f10e0d3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 44, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json index e85d787cd99..a8fb42ee2ca 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 21, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json index e02a0a38bb4..ab1bbd97998 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json index fdc4d523104..7df8cea13ea 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json index 70497ee8c1b..17a823c4283 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 25, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index 4d16157d91d..bf15a478146 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 19, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index 3f5f2a54ec7..2b635be0577 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 21, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index 193c5c0eb01..5a9127ccfdf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index 193c5c0eb01..5a9127ccfdf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index fca64bcb430..eec9555c363 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 23, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 90158499b17..778af6902a9 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json index 3a5e71ef8b1..38997b2e70f 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 34, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -41,11 +36,6 @@ "kind": "JSDocParameterTag", "pos": 34, "end": 58, - "atToken": { - "kind": "AtToken", - "pos": 34, - "end": 35 - }, "tagName": { "kind": "Identifier", "pos": 35, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json index 51868df260b..f74d57ad4d6 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 30, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -41,11 +36,6 @@ "kind": "JSDocParameterTag", "pos": 30, "end": 54, - "atToken": { - "kind": "AtToken", - "pos": 30, - "end": 31 - }, "tagName": { "kind": "Identifier", "pos": 31, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 7b3050cffa2..dcc611bff2d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -7,11 +7,6 @@ "kind": "JSDocTypedefTag", "pos": 8, "end": 100, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -39,11 +34,6 @@ "kind": "JSDocPropertyTag", "pos": 47, "end": 74, - "atToken": { - "kind": "AtToken", - "pos": 47, - "end": 48 - }, "tagName": { "kind": "Identifier", "pos": 48, @@ -73,11 +63,6 @@ "kind": "JSDocPropertyTag", "pos": 74, "end": 100, - "atToken": { - "kind": "AtToken", - "pos": 74, - "end": 75 - }, "tagName": { "kind": "Identifier", "pos": 75, diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index a6b826326cf..f43b14a3cb9 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -504,7 +504,6 @@ declare namespace ts { type AsteriskToken = Token; type EqualsGreaterThanToken = Token; type EndOfFileToken = Token & JSDocContainer; - type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; type PlusToken = Token; @@ -1551,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index ec80d7722e2..39b4c5111ba 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -504,7 +504,6 @@ declare namespace ts { type AsteriskToken = Token; type EqualsGreaterThanToken = Token; type EndOfFileToken = Token & JSDocContainer; - type AtToken = Token; type ReadonlyToken = Token; type AwaitKeywordToken = Token; type PlusToken = Token; @@ -1551,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } From cc36e294cc38df9adf40396514744227b2616707 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 6 Nov 2018 11:27:07 -0800 Subject: [PATCH 230/262] Add related span pointing to this-shadowing location for implicitly-any this (#28299) * Add diagnostic pointing to this-shadowing location * Fix almost-top-level-this case * Change message on span --- src/compiler/checker.ts | 8 +++++- src/compiler/diagnosticMessages.json | 4 +++ .../reference/thisBinding2.errors.txt | 1 + .../thisShadowingErrorSpans.errors.txt | 16 ++++++++++++ .../reference/thisShadowingErrorSpans.js | 24 ++++++++++++++++++ .../reference/thisShadowingErrorSpans.symbols | 20 +++++++++++++++ .../reference/thisShadowingErrorSpans.types | 25 +++++++++++++++++++ .../cases/compiler/thisShadowingErrorSpans.ts | 9 +++++++ 8 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/thisShadowingErrorSpans.errors.txt create mode 100644 tests/baselines/reference/thisShadowingErrorSpans.js create mode 100644 tests/baselines/reference/thisShadowingErrorSpans.symbols create mode 100644 tests/baselines/reference/thisShadowingErrorSpans.types create mode 100644 tests/cases/compiler/thisShadowingErrorSpans.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b54b1393253..c6260a958de 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16296,11 +16296,17 @@ namespace ts { const type = tryGetThisTypeAt(node, container); if (!type && noImplicitThis) { // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error( + const diag = error( node, capturedByArrowFunction && container.kind === SyntaxKind.SourceFile ? Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!isSourceFile(container)) { + const outsideThis = tryGetThisTypeAt(container); + if (outsideThis) { + addRelatedInfo(diag, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } + } } return type || anyType; } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 49f682c4d58..6e80e391f9a 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2509,6 +2509,10 @@ "category": "Error", "code": 2737 }, + "An outer value of 'this' is shadowed by this container.": { + "category": "Message", + "code": 2738 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", diff --git a/tests/baselines/reference/thisBinding2.errors.txt b/tests/baselines/reference/thisBinding2.errors.txt index c91a16c812a..a5cff14f949 100644 --- a/tests/baselines/reference/thisBinding2.errors.txt +++ b/tests/baselines/reference/thisBinding2.errors.txt @@ -14,6 +14,7 @@ tests/cases/compiler/thisBinding2.ts(10,11): error TS2683: 'this' implicitly has return this.x; ~~~~ !!! error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. +!!! related TS2738 tests/cases/compiler/thisBinding2.ts:8:12: An outer value of 'this' is shadowed by this container. }(); } } diff --git a/tests/baselines/reference/thisShadowingErrorSpans.errors.txt b/tests/baselines/reference/thisShadowingErrorSpans.errors.txt new file mode 100644 index 00000000000..46c4be3a3b8 --- /dev/null +++ b/tests/baselines/reference/thisShadowingErrorSpans.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/thisShadowingErrorSpans.ts(5,13): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. + + +==== tests/cases/compiler/thisShadowingErrorSpans.ts (1 errors) ==== + class C { + m() { + this.m(); + function f() { + this.m(); + ~~~~ +!!! error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. +!!! related TS2738 tests/cases/compiler/thisShadowingErrorSpans.ts:4:18: An outer value of 'this' is shadowed by this container. + } + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/thisShadowingErrorSpans.js b/tests/baselines/reference/thisShadowingErrorSpans.js new file mode 100644 index 00000000000..78682322fc4 --- /dev/null +++ b/tests/baselines/reference/thisShadowingErrorSpans.js @@ -0,0 +1,24 @@ +//// [thisShadowingErrorSpans.ts] +class C { + m() { + this.m(); + function f() { + this.m(); + } + } +} + + +//// [thisShadowingErrorSpans.js] +"use strict"; +var C = /** @class */ (function () { + function C() { + } + C.prototype.m = function () { + this.m(); + function f() { + this.m(); + } + }; + return C; +}()); diff --git a/tests/baselines/reference/thisShadowingErrorSpans.symbols b/tests/baselines/reference/thisShadowingErrorSpans.symbols new file mode 100644 index 00000000000..9ad12ffa433 --- /dev/null +++ b/tests/baselines/reference/thisShadowingErrorSpans.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/thisShadowingErrorSpans.ts === +class C { +>C : Symbol(C, Decl(thisShadowingErrorSpans.ts, 0, 0)) + + m() { +>m : Symbol(C.m, Decl(thisShadowingErrorSpans.ts, 0, 9)) + + this.m(); +>this.m : Symbol(C.m, Decl(thisShadowingErrorSpans.ts, 0, 9)) +>this : Symbol(C, Decl(thisShadowingErrorSpans.ts, 0, 0)) +>m : Symbol(C.m, Decl(thisShadowingErrorSpans.ts, 0, 9)) + + function f() { +>f : Symbol(f, Decl(thisShadowingErrorSpans.ts, 2, 17)) + + this.m(); + } + } +} + diff --git a/tests/baselines/reference/thisShadowingErrorSpans.types b/tests/baselines/reference/thisShadowingErrorSpans.types new file mode 100644 index 00000000000..2efd099400d --- /dev/null +++ b/tests/baselines/reference/thisShadowingErrorSpans.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/thisShadowingErrorSpans.ts === +class C { +>C : C + + m() { +>m : () => void + + this.m(); +>this.m() : void +>this.m : () => void +>this : this +>m : () => void + + function f() { +>f : () => void + + this.m(); +>this.m() : any +>this.m : any +>this : any +>m : any + } + } +} + diff --git a/tests/cases/compiler/thisShadowingErrorSpans.ts b/tests/cases/compiler/thisShadowingErrorSpans.ts new file mode 100644 index 00000000000..d6c351f0080 --- /dev/null +++ b/tests/cases/compiler/thisShadowingErrorSpans.ts @@ -0,0 +1,9 @@ +// @strict: true +class C { + m() { + this.m(); + function f() { + this.m(); + } + } +} From d7390c03f0048d4accdd54b163c4e12343c3ef02 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 6 Nov 2018 12:51:11 -0800 Subject: [PATCH 231/262] Avoid elaborating on generic indexes (#28294) --- src/compiler/checker.ts | 3 +- ...sIntoApparentlyPresentPropsOnly.errors.txt | 24 ++++++++++ ...tionDivesIntoApparentlyPresentPropsOnly.js | 24 ++++++++++ ...ivesIntoApparentlyPresentPropsOnly.symbols | 39 ++++++++++++++++ ...nDivesIntoApparentlyPresentPropsOnly.types | 44 +++++++++++++++++++ .../indexedAccessRelation.errors.txt | 25 ++++++----- ...tionDivesIntoApparentlyPresentPropsOnly.ts | 11 +++++ 7 files changed, 158 insertions(+), 12 deletions(-) create mode 100644 tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.errors.txt create mode 100644 tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.js create mode 100644 tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.symbols create mode 100644 tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.types create mode 100644 tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c6260a958de..cd29b9450ba 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10936,8 +10936,9 @@ namespace ts { let reportedError = false; for (let status = iterator.next(); !status.done; status = iterator.next()) { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value; - const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); const targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); + if (targetPropType === errorType || targetPropType.flags & TypeFlags.IndexedAccess) continue; // Don't elaborate on indexes on generic variables + const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); if (sourcePropType !== errorType && targetPropType !== errorType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) { const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined); if (elaborated) { diff --git a/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.errors.txt b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.errors.txt new file mode 100644 index 00000000000..e2b18aa2fc3 --- /dev/null +++ b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.errors.txt @@ -0,0 +1,24 @@ +tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts(2,5): error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type 'T'. +tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts(6,5): error TS2322: Type '{ a: number; }' is not assignable to type 'T'. +tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts(10,5): error TS2322: Type '{ a: string; }' is not assignable to type 'T'. + + +==== tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts (3 errors) ==== + function foo(x: T) { + x = { a: "abc", b: 20, c: 30 }; + ~ +!!! error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type 'T'. + } + + function bar(x: T) { + x = { a: 20 }; + ~ +!!! error TS2322: Type '{ a: number; }' is not assignable to type 'T'. + } + + function baz(x: T) { + x = { a: "not ok" }; + ~ +!!! error TS2322: Type '{ a: string; }' is not assignable to type 'T'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.js b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.js new file mode 100644 index 00000000000..bdf87a0acca --- /dev/null +++ b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.js @@ -0,0 +1,24 @@ +//// [errorElaborationDivesIntoApparentlyPresentPropsOnly.ts] +function foo(x: T) { + x = { a: "abc", b: 20, c: 30 }; +} + +function bar(x: T) { + x = { a: 20 }; +} + +function baz(x: T) { + x = { a: "not ok" }; +} + + +//// [errorElaborationDivesIntoApparentlyPresentPropsOnly.js] +function foo(x) { + x = { a: "abc", b: 20, c: 30 }; +} +function bar(x) { + x = { a: 20 }; +} +function baz(x) { + x = { a: "not ok" }; +} diff --git a/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.symbols b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.symbols new file mode 100644 index 00000000000..8ad2996d7fe --- /dev/null +++ b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.symbols @@ -0,0 +1,39 @@ +=== tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts === +function foo(x: T) { +>foo : Symbol(foo, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 0)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 13)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 24)) +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 38)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 13)) + + x = { a: "abc", b: 20, c: 30 }; +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 0, 38)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 1, 9)) +>b : Symbol(b, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 1, 19)) +>c : Symbol(c, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 1, 26)) +} + +function bar(x: T) { +>bar : Symbol(bar, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 2, 1)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 4, 13)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 4, 24)) +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 4, 38)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 4, 13)) + + x = { a: 20 }; +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 4, 38)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 5, 9)) +} + +function baz(x: T) { +>baz : Symbol(baz, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 6, 1)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 8, 13)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 8, 24)) +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 8, 38)) +>T : Symbol(T, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 8, 13)) + + x = { a: "not ok" }; +>x : Symbol(x, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 8, 38)) +>a : Symbol(a, Decl(errorElaborationDivesIntoApparentlyPresentPropsOnly.ts, 9, 9)) +} + diff --git a/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.types b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.types new file mode 100644 index 00000000000..1393814ffe8 --- /dev/null +++ b/tests/baselines/reference/errorElaborationDivesIntoApparentlyPresentPropsOnly.types @@ -0,0 +1,44 @@ +=== tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts === +function foo(x: T) { +>foo : (x: T) => void +>a : string +>x : T + + x = { a: "abc", b: 20, c: 30 }; +>x = { a: "abc", b: 20, c: 30 } : { a: string; b: number; c: number; } +>x : T +>{ a: "abc", b: 20, c: 30 } : { a: string; b: number; c: number; } +>a : string +>"abc" : "abc" +>b : number +>20 : 20 +>c : number +>30 : 30 +} + +function bar(x: T) { +>bar : (x: T) => void +>a : string +>x : T + + x = { a: 20 }; +>x = { a: 20 } : { a: number; } +>x : T +>{ a: 20 } : { a: number; } +>a : number +>20 : 20 +} + +function baz(x: T) { +>baz : (x: T) => void +>a : string +>x : T + + x = { a: "not ok" }; +>x = { a: "not ok" } : { a: string; } +>x : T +>{ a: "not ok" } : { a: string; } +>a : string +>"not ok" : "not ok" +} + diff --git a/tests/baselines/reference/indexedAccessRelation.errors.txt b/tests/baselines/reference/indexedAccessRelation.errors.txt index 14dbee4d4c1..84e65df856d 100644 --- a/tests/baselines/reference/indexedAccessRelation.errors.txt +++ b/tests/baselines/reference/indexedAccessRelation.errors.txt @@ -1,8 +1,10 @@ -tests/cases/compiler/indexedAccessRelation.ts(16,25): error TS2322: Type 'T' is not assignable to type 'S["a"] & T'. - Type 'Foo' is not assignable to type 'S["a"] & T'. - Type 'Foo' is not assignable to type 'S["a"]'. - Type 'T' is not assignable to type 'S["a"]'. +tests/cases/compiler/indexedAccessRelation.ts(16,23): error TS2345: Argument of type '{ a: T; }' is not assignable to parameter of type 'Pick, "a">'. + Types of property 'a' are incompatible. + Type 'T' is not assignable to type 'S["a"] & T'. + Type 'Foo' is not assignable to type 'S["a"] & T'. Type 'Foo' is not assignable to type 'S["a"]'. + Type 'T' is not assignable to type 'S["a"]'. + Type 'Foo' is not assignable to type 'S["a"]'. ==== tests/cases/compiler/indexedAccessRelation.ts (1 errors) ==== @@ -22,13 +24,14 @@ tests/cases/compiler/indexedAccessRelation.ts(16,25): error TS2322: Type 'T' is { foo(a: T) { this.setState({ a: a }); - ~ -!!! error TS2322: Type 'T' is not assignable to type 'S["a"] & T'. -!!! error TS2322: Type 'Foo' is not assignable to type 'S["a"] & T'. -!!! error TS2322: Type 'Foo' is not assignable to type 'S["a"]'. -!!! error TS2322: Type 'T' is not assignable to type 'S["a"]'. -!!! error TS2322: Type 'Foo' is not assignable to type 'S["a"]'. -!!! related TS6500 tests/cases/compiler/indexedAccessRelation.ts:8:5: The expected type comes from property 'a' which is declared here on type 'Pick, "a">' + ~~~~~~~~ +!!! error TS2345: Argument of type '{ a: T; }' is not assignable to parameter of type 'Pick, "a">'. +!!! error TS2345: Types of property 'a' are incompatible. +!!! error TS2345: Type 'T' is not assignable to type 'S["a"] & T'. +!!! error TS2345: Type 'Foo' is not assignable to type 'S["a"] & T'. +!!! error TS2345: Type 'Foo' is not assignable to type 'S["a"]'. +!!! error TS2345: Type 'T' is not assignable to type 'S["a"]'. +!!! error TS2345: Type 'Foo' is not assignable to type 'S["a"]'. } } \ No newline at end of file diff --git a/tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts b/tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts new file mode 100644 index 00000000000..1045fd95cad --- /dev/null +++ b/tests/cases/compiler/errorElaborationDivesIntoApparentlyPresentPropsOnly.ts @@ -0,0 +1,11 @@ +function foo(x: T) { + x = { a: "abc", b: 20, c: 30 }; +} + +function bar(x: T) { + x = { a: 20 }; +} + +function baz(x: T) { + x = { a: "not ok" }; +} From 7df5a2cf8c4d7363e9afce5d5a1a74b9865d329d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 6 Nov 2018 13:31:56 -0800 Subject: [PATCH 232/262] Remove pointless check --- src/compiler/checker.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 589239bce51..c3653c771da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -17807,9 +17807,7 @@ namespace ts { if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & TypeFlags.Nullable)) { - propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags); - } + propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags); return result; } } From d351610e7a3c3a286eb3eb050c730217949430ed Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 6 Nov 2018 13:52:35 -0800 Subject: [PATCH 233/262] Update opposite direction of #28218 (#28384) --- src/compiler/checker.ts | 6 +-- .../reference/reactHOCSpreadprops.js | 53 +++++++++++++++++++ .../reference/reactHOCSpreadprops.symbols | 36 +++++++++++++ .../reference/reactHOCSpreadprops.types | 31 +++++++++++ tests/cases/compiler/reactHOCSpreadprops.tsx | 11 ++++ 5 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/reactHOCSpreadprops.js create mode 100644 tests/baselines/reference/reactHOCSpreadprops.symbols create mode 100644 tests/baselines/reference/reactHOCSpreadprops.types create mode 100644 tests/cases/compiler/reactHOCSpreadprops.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cd29b9450ba..5d3cc7fd182 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12035,8 +12035,8 @@ namespace ts { } if (target.flags & TypeFlags.TypeParameter) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & ObjectFlags.Mapped && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. + if (getObjectFlags(source) & ObjectFlags.Mapped && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) { if (!(getMappedTypeModifiers(source) & MappedTypeModifiers.IncludeOptional)) { const templateType = getTemplateTypeFromMappedType(source); const indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); @@ -12090,7 +12090,7 @@ namespace ts { (template).indexType === getTypeParameterFromMappedType(target)) { return Ternary.True; } - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { const indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); const templateType = getTemplateTypeFromMappedType(target); diff --git a/tests/baselines/reference/reactHOCSpreadprops.js b/tests/baselines/reference/reactHOCSpreadprops.js new file mode 100644 index 00000000000..45ecbe35f68 --- /dev/null +++ b/tests/baselines/reference/reactHOCSpreadprops.js @@ -0,0 +1,53 @@ +//// [reactHOCSpreadprops.tsx] +/// +import React = require("react"); +function f

(App: React.ComponentClass

| React.StatelessComponent

): void { + class C extends React.Component

{ + render() { + return ; + } + } +} + + +//// [reactHOCSpreadprops.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +exports.__esModule = true; +/// +var React = require("react"); +function f(App) { + var C = /** @class */ (function (_super) { + __extends(C, _super); + function C() { + return _super !== null && _super.apply(this, arguments) || this; + } + C.prototype.render = function () { + return React.createElement(App, __assign({}, this.props)); + }; + return C; + }(React.Component)); +} diff --git a/tests/baselines/reference/reactHOCSpreadprops.symbols b/tests/baselines/reference/reactHOCSpreadprops.symbols new file mode 100644 index 00000000000..06e698014f4 --- /dev/null +++ b/tests/baselines/reference/reactHOCSpreadprops.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/reactHOCSpreadprops.tsx === +/// +import React = require("react"); +>React : Symbol(React, Decl(reactHOCSpreadprops.tsx, 0, 0)) + +function f

(App: React.ComponentClass

| React.StatelessComponent

): void { +>f : Symbol(f, Decl(reactHOCSpreadprops.tsx, 1, 32)) +>P : Symbol(P, Decl(reactHOCSpreadprops.tsx, 2, 11)) +>App : Symbol(App, Decl(reactHOCSpreadprops.tsx, 2, 14)) +>React : Symbol(React, Decl(reactHOCSpreadprops.tsx, 0, 0)) +>ComponentClass : Symbol(React.ComponentClass, Decl(react16.d.ts, 421, 9)) +>P : Symbol(P, Decl(reactHOCSpreadprops.tsx, 2, 11)) +>React : Symbol(React, Decl(reactHOCSpreadprops.tsx, 0, 0)) +>StatelessComponent : Symbol(React.StatelessComponent, Decl(react16.d.ts, 406, 49)) +>P : Symbol(P, Decl(reactHOCSpreadprops.tsx, 2, 11)) + + class C extends React.Component

{ +>C : Symbol(C, Decl(reactHOCSpreadprops.tsx, 2, 81)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(reactHOCSpreadprops.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>P : Symbol(P, Decl(reactHOCSpreadprops.tsx, 2, 11)) +>x : Symbol(x, Decl(reactHOCSpreadprops.tsx, 3, 41)) + + render() { +>render : Symbol(C.render, Decl(reactHOCSpreadprops.tsx, 3, 56)) + + return ; +>App : Symbol(App, Decl(reactHOCSpreadprops.tsx, 2, 14)) +>this.props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) +>this : Symbol(C, Decl(reactHOCSpreadprops.tsx, 2, 81)) +>props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) + } + } +} + diff --git a/tests/baselines/reference/reactHOCSpreadprops.types b/tests/baselines/reference/reactHOCSpreadprops.types new file mode 100644 index 00000000000..b343ea5fc7a --- /dev/null +++ b/tests/baselines/reference/reactHOCSpreadprops.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/reactHOCSpreadprops.tsx === +/// +import React = require("react"); +>React : typeof React + +function f

(App: React.ComponentClass

| React.StatelessComponent

): void { +>f :

(App: React.ComponentClass | React.StatelessComponent

) => void +>App : React.ComponentClass | React.StatelessComponent

+>React : any +>React : any + + class C extends React.Component

{ +>C : C +>React.Component : React.Component

+>React : typeof React +>Component : typeof React.Component +>x : number + + render() { +>render : () => JSX.Element + + return ; +> : JSX.Element +>App : React.ComponentClass | React.StatelessComponent

+>this.props : Readonly<{ children?: React.ReactNode; }> & Readonly

+>this : this +>props : Readonly<{ children?: React.ReactNode; }> & Readonly

+ } + } +} + diff --git a/tests/cases/compiler/reactHOCSpreadprops.tsx b/tests/cases/compiler/reactHOCSpreadprops.tsx new file mode 100644 index 00000000000..3b1b3e74724 --- /dev/null +++ b/tests/cases/compiler/reactHOCSpreadprops.tsx @@ -0,0 +1,11 @@ +// @jsx: react +// @strict: true +/// +import React = require("react"); +function f

(App: React.ComponentClass

| React.StatelessComponent

): void { + class C extends React.Component

{ + render() { + return ; + } + } +} From e63ffe54fdecab18ee6cec306f14d7114385a7e2 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 6 Nov 2018 15:00:34 -0800 Subject: [PATCH 234/262] Move FreshLiteral flag from TypeFlags to ObjectFlags --- src/compiler/checker.ts | 45 +++++++++++++++++++++-------------------- src/compiler/types.ts | 9 ++++----- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c3653c771da..873688dfd8a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -82,6 +82,7 @@ namespace ts { const noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny"); const noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); const keyofStringsOnly = !!compilerOptions.keyofStringsOnly; + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : ObjectFlags.FreshLiteral; const emitResolver = createResolver(); const nodeBuilder = createNodeBuilder(); @@ -10000,8 +10001,8 @@ namespace ts { emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | TypeFlags.ContainsObjectLiteral; - (spread as ObjectType).objectFlags |= objectFlags | (ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread); + spread.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; + spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread | objectFlags; return spread; } @@ -11553,7 +11554,7 @@ namespace ts { isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return Ternary.True; const isComparingJsxAttributes = !!(getObjectFlags(source) & ObjectFlags.JsxAttributes); - if (isObjectLiteralType(source) && source.flags & TypeFlags.FreshLiteral) { + if (isObjectLiteralType(source) && getObjectFlags(source) & ObjectFlags.FreshLiteral) { const discriminantType = target.flags & TypeFlags.Union ? findMatchingDiscriminantType(source, target as UnionType) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { @@ -13284,7 +13285,7 @@ namespace ts { * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type: Type): Type { - if (!(isObjectLiteralType(type) && type.flags & TypeFlags.FreshLiteral)) { + if (!(isObjectLiteralType(type) && getObjectFlags(type) & ObjectFlags.FreshLiteral)) { return type; } const regularType = (type).regularType; @@ -13300,7 +13301,7 @@ namespace ts { resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~TypeFlags.FreshLiteral; + regularNew.flags = resolved.flags; regularNew.objectFlags |= ObjectFlags.ObjectLiteral | (getObjectFlags(resolved) & ObjectFlags.JSLiteral); (type).regularType = regularNew; return regularNew; @@ -17637,7 +17638,7 @@ namespace ts { let propertiesTable: SymbolTable; let propertiesArray: Symbol[] = []; let spread: Type = emptyObjectType; - let propagatedFlags: TypeFlags = TypeFlags.FreshLiteral; + let propagatedFlags: TypeFlags = 0; const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -17722,7 +17723,7 @@ namespace ts { checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); propertiesArray = []; propertiesTable = createSymbolTable(); hasComputedStringProperty = false; @@ -17734,7 +17735,7 @@ namespace ts { error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); offset = i + 1; continue; } @@ -17784,7 +17785,7 @@ namespace ts { if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, /*objectFlags*/ 0); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral); } return spread; } @@ -17795,9 +17796,8 @@ namespace ts { const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.String) : undefined; const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, IndexKind.Number) : undefined; const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); - result.objectFlags |= ObjectFlags.ObjectLiteral; + result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags & TypeFlags.PropagatingFlags; + result.objectFlags |= ObjectFlags.ObjectLiteral | freshObjectLiteralFlag; if (isJSObjectLiteral) { result.objectFlags |= ObjectFlags.JSLiteral; } @@ -17807,7 +17807,7 @@ namespace ts { if (inDestructuringPattern) { result.pattern = node; } - propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags); + propagatedFlags |= result.flags & TypeFlags.PropagatingFlags; return result; } } @@ -17898,14 +17898,15 @@ namespace ts { let hasSpreadAnyType = false; let typeToIntersect: Type | undefined; let explicitlySpecifyChildrenAttribute = false; - let propagatingFlags: TypeFlags = 0; + let typeFlags: TypeFlags = 0; + let objectFlags: ObjectFlags = ObjectFlags.JsxAttributes; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); - propagatingFlags |= (exprType.flags & TypeFlags.PropagatingFlags); + typeFlags |= exprType.flags & TypeFlags.PropagatingFlags; const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -17923,7 +17924,7 @@ namespace ts { else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); attributesTable = createSymbolTable(); } const exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -17931,7 +17932,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -17941,7 +17942,7 @@ namespace ts { if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); } } @@ -17969,7 +17970,7 @@ namespace ts { const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), - attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); + attributes.symbol, typeFlags, objectFlags); } } @@ -17988,10 +17989,10 @@ namespace ts { * @param attributesTable a symbol table of attributes property */ function createJsxAttributesType() { + objectFlags |= freshObjectLiteralFlag; const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= (propagatingFlags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag); - result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.JsxAttributes; + result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; + result.objectFlags |= ObjectFlags.ObjectLiteral | objectFlags; return result; } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 0ca4de3f537..eed58335363 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3836,13 +3836,11 @@ namespace ts { Substitution = 1 << 25, // Type parameter substitution NonPrimitive = 1 << 26, // intrinsic object type /* @internal */ - FreshLiteral = 1 << 27, // Fresh literal or unique type + ContainsWideningType = 1 << 27, // Type is or contains undefined or null widening type /* @internal */ - ContainsWideningType = 1 << 28, // Type is or contains undefined or null widening type + ContainsObjectLiteral = 1 << 28, // Type is or contains object literal type /* @internal */ - ContainsObjectLiteral = 1 << 29, // Type is or contains object literal type - /* @internal */ - ContainsAnyFunctionType = 1 << 30, // Type is or contains the anyFunctionType + ContainsAnyFunctionType = 1 << 29, // Type is or contains the anyFunctionType /* @internal */ AnyOrUnknown = Any | Unknown, @@ -3980,6 +3978,7 @@ namespace ts { JsxAttributes = 1 << 12, // Jsx attributes type MarkerType = 1 << 13, // Marker type used for variance probing JSLiteral = 1 << 14, // Object type declared in JS - disables errors on read/write of nonexisting members + FreshLiteral = 1 << 15, // Fresh object literal ClassOrInterface = Class | Interface } From 4a51f12c3ee318ce63819ca2855db2cbcf5b4f35 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 6 Nov 2018 14:57:28 -0800 Subject: [PATCH 235/262] Add metadata to response if it exists for results from language service. Currently its wired through for completions requests. Handles #21999 --- src/harness/harnessLanguageService.ts | 27 +++-- src/harness/virtualFileSystemWithWatch.ts | 1 + src/server/protocol.ts | 5 + src/server/session.ts | 28 ++++- src/services/types.ts | 4 +- .../unittests/tsserverProjectSystem.ts | 112 +++++++++++++++++- .../reference/api/tsserverlibrary.d.ts | 9 +- tests/baselines/reference/api/typescript.d.ts | 5 +- 8 files changed, 167 insertions(+), 24 deletions(-) diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index ee35ab360ca..ccad290aed7 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -1,4 +1,18 @@ namespace Harness.LanguageService { + + export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { + // tslint:disable-next-line:no-null-keyword + const proxy = Object.create(/*prototype*/ null); + const langSvc: any = info.languageService; + for (const k of Object.keys(langSvc)) { + // tslint:disable-next-line only-arrow-functions + proxy[k] = function () { + return langSvc[k].apply(langSvc, arguments); + }; + } + return proxy; + } + export class ScriptInfo { public version = 1; public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = []; @@ -869,19 +883,6 @@ namespace Harness.LanguageService { error: new Error("Could not resolve module") }; } - - function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { - // tslint:disable-next-line:no-null-keyword - const proxy = Object.create(/*prototype*/ null); - const langSvc: any = info.languageService; - for (const k of Object.keys(langSvc)) { - // tslint:disable-next-line only-arrow-functions - proxy[k] = function () { - return langSvc[k].apply(langSvc, arguments); - }; - } - return proxy; - } } } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 3f8d29abed6..9b030e212f1 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -341,6 +341,7 @@ interface Array {}` private readonly currentDirectory: string; private readonly dynamicPriorityWatchFile: HostWatchFile | undefined; private readonly customRecursiveWatchDirectory: HostWatchDirectory | undefined; + public require: (initialPath: string, moduleName: string) => server.RequireResult; constructor(public withSafeList: boolean, public useCaseSensitiveFileNames: boolean, executingFilePath: string, currentDirectory: string, fileOrFolderorSymLinkList: ReadonlyArray, public readonly newLine = "\n", public readonly useWindowsStylePath?: boolean, private readonly environmentVariables?: Map) { this.getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); diff --git a/src/server/protocol.ts b/src/server/protocol.ts index e956290181a..4eb8def8518 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -221,6 +221,11 @@ namespace ts.server.protocol { * Contains message body if success === true. */ body?: any; + + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: any; } /** diff --git a/src/server/session.ts b/src/server/session.ts index 42d3994db09..d4fc2d3fcc3 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -688,7 +688,26 @@ namespace ts.server { success, }; if (success) { - res.body = info; + let metadata: any; + if (isArray(info)) { + res.body = info; + metadata = (info as WithMetadata>).metadata; + delete (info as WithMetadata>).metadata; + } + else if (typeof info === "object") { + if ((info as WithMetadata<{}>).metadata) { + const { metadata: infoMetadata, ...body } = (info as WithMetadata<{}>); + res.body = body; + metadata = infoMetadata; + } + else { + res.body = info; + } + } + else { + res.body = info; + } + if (metadata) res.metadata = metadata; } else { Debug.assert(info === undefined); @@ -1467,7 +1486,7 @@ namespace ts.server { }); } - private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): ReadonlyArray | protocol.CompletionInfo | CompletionInfo | undefined { + private getCompletions(args: protocol.CompletionsRequestArgs, kind: protocol.CommandTypes.CompletionInfo | protocol.CommandTypes.Completions | protocol.CommandTypes.CompletionsFull): WithMetadata> | protocol.CompletionInfo | CompletionInfo | undefined { const { file, project } = this.getFileAndProject(args); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file)!; const position = this.getPosition(args, scriptInfo); @@ -1492,7 +1511,10 @@ namespace ts.server { } }).sort((a, b) => compareStringsCaseSensitiveUI(a.name, b.name)); - if (kind === protocol.CommandTypes.Completions) return entries; + if (kind === protocol.CommandTypes.Completions) { + if (completions.metadata) (entries as WithMetadata>).metadata = completions.metadata; + return entries; + } const res: protocol.CompletionInfo = { ...completions, diff --git a/src/services/types.ts b/src/services/types.ts index b856d15f61a..71f76161e23 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -238,6 +238,8 @@ namespace ts { /* @internal */ export const emptyOptions = {}; + export type WithMetadata = T & { metadata?: any; }; + // // Public services of a language service instance associated // with a language service host instance @@ -268,7 +270,7 @@ namespace ts { getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; // "options" and "source" are optional only for backwards-compatibility getCompletionEntryDetails( fileName: string, diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 4656e5282ba..1ec29f800b8 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -17,6 +17,14 @@ namespace ts.projectSystem { import safeList = TestFSWithWatch.safeList; import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; + const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; + function mapOutputToJson(s: string) { + return convertToObject( + parseJsonText("json.json", s.replace(outputEventRegex, "")), + [] + ); + } + export const customTypesMap = { path: "/typesMap.json", content: `{ @@ -353,12 +361,8 @@ namespace ts.projectSystem { }; function getEvents() { - const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; return mapDefined(host.getOutput(), s => { - const e = convertToObject( - parseJsonText("json.json", s.replace(outputEventRegex, "")), - [] - ); + const e = mapOutputToJson(s); return (isArray(eventNames) ? eventNames.some(eventName => e.event === eventName) : e.event === eventNames) ? e as T : undefined; }); } @@ -10735,6 +10739,104 @@ declare class TestLib { }); }); + describe("tsserverProjectSystem with metadata in response", () => { + const metadata = "Extra Info"; + function verifyOutput(host: TestServerHost, expectedResponse: protocol.Response) { + const output = host.getOutput().map(mapOutputToJson); + assert.deepEqual(output, [expectedResponse]); + host.clearOutput(); + } + + function verifyCommandWithMetadata(session: TestSession, host: TestServerHost, command: Partial, expectedResponseBody: U) { + command.seq = session.getSeq(); + command.type = "request"; + session.onMessage(JSON.stringify(command)); + verifyOutput(host, expectedResponseBody ? + { seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: true, body: expectedResponseBody, metadata } : + { seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: false, message: "No content available." } + ); + } + + const aTs: File = { path: "/a.ts", content: `class c { prop = "hello"; foo() { return this.prop; } }` }; + const tsconfig: File = { + path: "/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { plugins: [{ name: "myplugin" }] } + }) + }; + function createHostWithPlugin(files: ReadonlyArray) { + const host = createServerHost(files); + host.require = (_initialPath, moduleName) => { + assert.equal(moduleName, "myplugin"); + return { + module: () => ({ + create(info: server.PluginCreateInfo) { + const proxy = Harness.LanguageService.makeDefaultProxy(info); + proxy.getCompletionsAtPosition = (filename, position, options) => { + const result = info.languageService.getCompletionsAtPosition(filename, position, options); + if (result) { + result.metadata = metadata; + } + return result; + }; + return proxy; + } + }), + error: undefined + }; + }; + return host; + } + + describe("With completion requests", () => { + const completionRequestArgs: protocol.CompletionsRequestArgs = { + file: aTs.path, + line: 1, + offset: aTs.content.indexOf("this.") + 1 + "this.".length + }; + const expectedCompletionEntries: ReadonlyArray = [ + { name: "foo", kind: ScriptElementKind.memberFunctionElement, kindModifiers: "", sortText: "0" }, + { name: "prop", kind: ScriptElementKind.memberVariableElement, kindModifiers: "", sortText: "0" } + ]; + + it("can pass through metadata when the command returns array", () => { + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata>(session, host, { + command: protocol.CommandTypes.Completions, + arguments: completionRequestArgs + }, expectedCompletionEntries); + }); + + it("can pass through metadata when the command returns object", () => { + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata(session, host, { + command: protocol.CommandTypes.CompletionInfo, + arguments: completionRequestArgs + }, { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + entries: expectedCompletionEntries + }); + }); + + it("returns undefined correctly", () => { + const aTs: File = { path: "/a.ts", content: `class c { prop = "hello"; foo() { const x = 0; } }` }; + const host = createHostWithPlugin([aTs, tsconfig]); + const session = createSession(host); + openFilesForSession([aTs], session); + verifyCommandWithMetadata(session, host, { + command: protocol.CommandTypes.Completions, + arguments: { file: aTs.path, line: 1, offset: aTs.content.indexOf("x") + 1 } + }, undefined); + }); + }); + }); + function makeReferenceItem(file: File, isDefinition: boolean, text: string, lineText: string, options?: SpanFromSubstringOptions): protocol.ReferencesResponseItem { return { ...protocolFileSpanFromSubstring(file, text, options), diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index f43b14a3cb9..ffbd4c87389 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4688,6 +4688,9 @@ declare namespace ts { installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; } + type WithMetadata = T & { + metadata?: any; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4705,7 +4708,7 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; @@ -5787,6 +5790,10 @@ declare namespace ts.server.protocol { * Contains message body if success === true. */ body?: any; + /** + * Contains extra information that plugin can include to be passed on + */ + metadata?: any; } /** * Arguments for FileRequest messages. diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 39b4c5111ba..509d14e593c 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4688,6 +4688,9 @@ declare namespace ts { installPackage?(options: InstallPackageOptions): Promise; writeFile?(fileName: string, content: string): void; } + type WithMetadata = T & { + metadata?: any; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4705,7 +4708,7 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; From 7e3fd4626a1e25bf81bb364ed5d89d7cd80adcce Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 6 Nov 2018 15:07:00 -0800 Subject: [PATCH 236/262] Accept API baseline changes --- tests/baselines/reference/api/tsserverlibrary.d.ts | 1 + tests/baselines/reference/api/typescript.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index a6b826326cf..f3423c96dc3 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2254,6 +2254,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index ec80d7722e2..8c0f589032a 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2254,6 +2254,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { From 448f385e3c8427a23af505763b79eb262edf3e5b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 6 Nov 2018 15:49:17 -0800 Subject: [PATCH 237/262] Fix lint errors --- src/testRunner/unittests/tsserverProjectSystem.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 1ec29f800b8..5cd8358c0ee 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10798,7 +10798,7 @@ declare class TestLib { { name: "foo", kind: ScriptElementKind.memberFunctionElement, kindModifiers: "", sortText: "0" }, { name: "prop", kind: ScriptElementKind.memberVariableElement, kindModifiers: "", sortText: "0" } ]; - + it("can pass through metadata when the command returns array", () => { const host = createHostWithPlugin([aTs, tsconfig]); const session = createSession(host); @@ -10832,7 +10832,7 @@ declare class TestLib { verifyCommandWithMetadata(session, host, { command: protocol.CommandTypes.Completions, arguments: { file: aTs.path, line: 1, offset: aTs.content.indexOf("x") + 1 } - }, undefined); + }, /*expectedResponseBody*/ undefined); }); }); }); From f0f02754f3c2a6a35a56f0855916f42be521900b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 6 Nov 2018 18:45:08 -0800 Subject: [PATCH 238/262] Change type of metadata to unknown --- src/server/protocol.ts | 2 +- src/server/session.ts | 2 +- src/services/types.ts | 2 +- tests/baselines/reference/api/tsserverlibrary.d.ts | 4 ++-- tests/baselines/reference/api/typescript.d.ts | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 4eb8def8518..193621da82a 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -225,7 +225,7 @@ namespace ts.server.protocol { /** * Contains extra information that plugin can include to be passed on */ - metadata?: any; + metadata?: unknown; } /** diff --git a/src/server/session.ts b/src/server/session.ts index d4fc2d3fcc3..10399e21680 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -688,7 +688,7 @@ namespace ts.server { success, }; if (success) { - let metadata: any; + let metadata: unknown; if (isArray(info)) { res.body = info; metadata = (info as WithMetadata>).metadata; diff --git a/src/services/types.ts b/src/services/types.ts index 71f76161e23..73e41309a63 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -238,7 +238,7 @@ namespace ts { /* @internal */ export const emptyOptions = {}; - export type WithMetadata = T & { metadata?: any; }; + export type WithMetadata = T & { metadata?: unknown; }; // // Public services of a language service instance associated diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index ffbd4c87389..f7399eebce2 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4689,7 +4689,7 @@ declare namespace ts { writeFile?(fileName: string, content: string): void; } type WithMetadata = T & { - metadata?: any; + metadata?: unknown; }; interface LanguageService { cleanupSemanticCache(): void; @@ -5793,7 +5793,7 @@ declare namespace ts.server.protocol { /** * Contains extra information that plugin can include to be passed on */ - metadata?: any; + metadata?: unknown; } /** * Arguments for FileRequest messages. diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 509d14e593c..9cb6a040f2a 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4689,7 +4689,7 @@ declare namespace ts { writeFile?(fileName: string, content: string): void; } type WithMetadata = T & { - metadata?: any; + metadata?: unknown; }; interface LanguageService { cleanupSemanticCache(): void; From e2947fac1c7c5c81549b72a85c48760116ae448f Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Wed, 7 Nov 2018 16:12:48 +0000 Subject: [PATCH 239/262] remove even more redundant internal comments --- src/compiler/binder.ts | 2 -- src/compiler/core.ts | 1 - src/compiler/sourcemapDecoder.ts | 2 -- src/compiler/tsbuild.ts | 20 ++++++++++---------- src/compiler/types.ts | 1 - src/compiler/watch.ts | 1 - src/jsTyping/jsTyping.ts | 3 --- src/jsTyping/shared.ts | 1 - src/server/project.ts | 2 +- src/server/scriptInfo.ts | 1 - src/server/scriptVersionCache.ts | 1 - src/server/utilities.ts | 2 -- src/services/formatting/formatting.ts | 1 - src/services/organizeImports.ts | 4 ++-- src/services/patternMatcher.ts | 4 ++-- src/services/suggestionDiagnostics.ts | 2 -- src/services/utilities.ts | 7 ------- 17 files changed, 15 insertions(+), 40 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index eae59db1bc6..3a2e3ff0b2a 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2921,7 +2921,6 @@ namespace ts { } } - /* @internal */ export function isExportsOrModuleExportsOrAlias(sourceFile: SourceFile, node: Expression): boolean { return isExportsIdentifier(node) || isModuleExportsPropertyAccessExpression(node) || @@ -3898,7 +3897,6 @@ namespace ts { * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather * than calling this function. */ - /* @internal */ export function getTransformFlagsSubtreeExclusions(kind: SyntaxKind) { if (kind >= SyntaxKind.FirstTypeNode && kind <= SyntaxKind.LastTypeNode) { return TransformFlags.TypeExcludes; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 8c976cee9ee..bbc90984071 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2052,7 +2052,6 @@ namespace ts { } /** Represents a "prefix*suffix" pattern. */ - /* @internal */ export interface Pattern { prefix: string; suffix: string; diff --git a/src/compiler/sourcemapDecoder.ts b/src/compiler/sourcemapDecoder.ts index dd0d65c8092..ef48c9d1c69 100644 --- a/src/compiler/sourcemapDecoder.ts +++ b/src/compiler/sourcemapDecoder.ts @@ -150,14 +150,12 @@ namespace ts.sourcemaps { } } - /*@internal*/ export interface MappingsDecoder extends Iterator { readonly decodingIndex: number; readonly error: string | undefined; readonly lastSpan: SourceMapSpan; } - /*@internal*/ export function decodeMappings(map: SourceMapData): MappingsDecoder { const state: DecoderState = { encodedText: map.mappings, diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 4b9e75102b6..9e1c7c1bf42 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -22,9 +22,9 @@ namespace ts { force?: boolean; verbose?: boolean; - /*@internal*/ clean?: boolean; - /*@internal*/ watch?: boolean; - /*@internal*/ help?: boolean; + clean?: boolean; + watch?: boolean; + help?: boolean; preserveWatchOutput?: boolean; listEmittedFiles?: boolean; @@ -340,18 +340,18 @@ namespace ts { cleanAllProjects(): ExitStatus; // TODO:: All the below ones should technically only be in watch mode. but thats for later time - /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; - /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; - /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; + resolveProjectName(name: string): ResolvedConfigFileName; + getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; + getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; - /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; - /*@internal*/ buildInvalidatedProject(): void; + invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; + buildInvalidatedProject(): void; - /*@internal*/ resetBuildContext(opts?: BuildOptions): void; + resetBuildContext(opts?: BuildOptions): void; } export interface SolutionBuilderWithWatch extends SolutionBuilder { - /*@internal*/ startWatching(): void; + startWatching(): void; } /** diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f5c996eed87..91954352fda 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5225,7 +5225,6 @@ namespace ts { useCaseSensitiveFileNames(): boolean; getCurrentDirectory(): string; - /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; getLibFileFromReference(ref: FileReference): SourceFile | undefined; diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 345991baefc..d7373b8d4dc 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -43,7 +43,6 @@ namespace ts { return false; } - /** @internal */ export const screenStartingMessageCodes: number[] = [ Diagnostics.Starting_compilation_in_watch_mode.code, Diagnostics.File_change_detected_Starting_incremental_compilation.code, diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index ad21068d578..379ca6491a6 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -24,13 +24,11 @@ namespace ts.JsTyping { version: Version; } - /* @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); return availableVersion.compareTo(cachedTyping.version) <= 0; } - /* @internal */ export const nodeCoreModuleList: ReadonlyArray = [ "assert", "async_hooks", @@ -70,7 +68,6 @@ namespace ts.JsTyping { "zlib" ]; - /* @internal */ export const nodeCoreModules = arrayToSet(nodeCoreModuleList); /** diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index 78e9fe051b7..8dc4c02e9c4 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -34,7 +34,6 @@ namespace ts.server { : undefined; } - /*@internal*/ export function nowString() { // E.g. "12:34:56.789" const d = new Date(); diff --git a/src/server/project.ts b/src/server/project.ts index 89bac4060bb..b2e7bb8e5c2 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -204,7 +204,7 @@ namespace ts.server { /*@internal*/ constructor( - /*@internal*/readonly projectName: string, + readonly projectName: string, readonly projectKind: ProjectKind, readonly projectService: ProjectService, private documentRegistry: DocumentRegistry, diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index ea029f3d9d0..4e3a67748dd 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -6,7 +6,6 @@ namespace ts.server { /* @internal */ export class TextStorage { - /*@internal*/ version: ScriptInfoVersion; /** diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index d7ac25062d0..0ffb3a195ad 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -382,7 +382,6 @@ namespace ts.server { } } - /* @internal */ export class LineIndex { root: LineNode; // set this to true to check each edit for accuracy diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 4eac1730b77..15b217822c0 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -208,13 +208,11 @@ namespace ts.server { const indentStr = "\n "; - /* @internal */ export function indent(str: string): string { return indentStr + str.replace(/\n/g, indentStr); } /** Put stringified JSON on the next line, indented. */ - /* @internal */ export function stringifyIndented(json: {}): string { return indentStr + JSON.stringify(json); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 215585f238e..a3acdbdafaa 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -334,7 +334,6 @@ namespace ts.formatting { return 0; } - /* @internal */ export function formatNodeGivenIndentation(node: Node, sourceFileLike: SourceFileLike, languageVariant: LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): TextChange[] { const range = { pos: 0, end: sourceFileLike.text.length }; return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => formatSpanWorker( diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 460cb3dd5a2..9c504357102 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -146,7 +146,7 @@ namespace ts.OrganizeImports { : undefined; } - /* @internal */ // Internal for testing + // Internal for testing /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -266,7 +266,7 @@ namespace ts.OrganizeImports { } } - /* @internal */ // Internal for testing + // Internal for testing /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index f81900e28e7..1020c97b432 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -461,11 +461,11 @@ namespace ts { }; } - /* @internal */ export function breakIntoCharacterSpans(identifier: string): TextSpan[] { + export function breakIntoCharacterSpans(identifier: string): TextSpan[] { return breakIntoSpans(identifier, /*word:*/ false); } - /* @internal */ export function breakIntoWordSpans(identifier: string): TextSpan[] { + export function breakIntoWordSpans(identifier: string): TextSpan[] { return breakIntoSpans(identifier, /*word:*/ true); } diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index b7b2ce8466d..5c175146e34 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -140,13 +140,11 @@ namespace ts { return !!forEachReturnStatement(body, isReturnStatementWithFixablePromiseHandler); } - /* @internal */ export function isReturnStatementWithFixablePromiseHandler(node: Node): node is ReturnStatement { return isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression); } // Should be kept up to date with transformExpression in convertToAsyncFunction.ts - /* @internal */ export function isFixablePromiseHandler(node: Node): boolean { // ensure outermost call exists and is a promise handler if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 61f6e6e6087..91b18a015cc 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1410,7 +1410,6 @@ namespace ts { return node.modifiers && find(node.modifiers, m => m.kind === kind); } - /* @internal */ export function insertImport(changes: textChanges.ChangeTracker, sourceFile: SourceFile, importDecl: Statement): void { const lastImportDeclaration = findLast(sourceFile.statements, isAnyImportSyntax); if (lastImportDeclaration) { @@ -1598,7 +1597,6 @@ namespace ts { return displayPart("\n", SymbolDisplayPartKind.lineBreak); } - /* @internal */ export function mapToDisplayParts(writeDisplayParts: (writer: DisplayPartsSymbolWriter) => void): SymbolDisplayPart[] { try { writeDisplayParts(displayPartWriter); @@ -1751,7 +1749,6 @@ namespace ts { /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ export function suppressLeadingAndTrailingTrivia(node: Node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -1760,7 +1757,6 @@ namespace ts { /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ export function suppressLeadingTrivia(node: Node) { addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); } @@ -1768,7 +1764,6 @@ namespace ts { /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ export function suppressTrailingTrivia(node: Node) { addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); } @@ -1783,7 +1778,6 @@ namespace ts { return node.forEachChild(child => child); } - /* @internal */ export function getUniqueName(baseName: string, sourceFile: SourceFile): string { let nameText = baseName; for (let i = 1; !isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -1797,7 +1791,6 @@ namespace ts { * to be on the reference, rather than the declaration, because it's closer to where the * user was before extracting it. */ - /* @internal */ export function getRenameLocation(edits: ReadonlyArray, renameFilename: string, name: string, preferLastLocation: boolean): number { let delta = 0; let lastPos = -1; From 1d8725057362cfd47ca13ab319b8fafd4989f493 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 6 Nov 2018 18:32:03 -0800 Subject: [PATCH 240/262] Fix the issue with file being included in the referencing project on rename when it wasnt included earlier Fixes #28043 --- src/services/getEditsForFileRename.ts | 7 ++-- .../unittests/tsserverProjectSystem.ts | 36 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 5872ade5652..0f47a15b69b 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -14,7 +14,7 @@ namespace ts { const oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); return textChanges.ChangeTracker.with({ host, formatContext }, changeTracker => { - updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName); }); } @@ -45,7 +45,7 @@ namespace ts { return combinePathsSafe(getDirectoryPath(a1), rel); } - function updateTsconfigFiles(program: Program, changeTracker: textChanges.ChangeTracker, oldToNew: PathUpdater, newFileOrDirPath: string, currentDirectory: string, useCaseSensitiveFileNames: boolean): void { + function updateTsconfigFiles(program: Program, changeTracker: textChanges.ChangeTracker, oldToNew: PathUpdater, oldFileOrDirPath: string, newFileOrDirPath: string, currentDirectory: string, useCaseSensitiveFileNames: boolean): void { const { configFile } = program.getCompilerOptions(); if (!configFile) return; const configDir = getDirectoryPath(configFile.fileName); @@ -63,7 +63,8 @@ namespace ts { const includes = mapDefined(property.initializer.elements, e => isStringLiteral(e) ? e.text : undefined); const matchers = getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (!getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !getRegexFromPattern(Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, last(property.initializer.elements), createStringLiteral(relativePath(newFileOrDirPath))); } } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 5cd8358c0ee..5bc414903a9 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10523,6 +10523,42 @@ declare class TestLib { ]); verifySingleInferredProject(session); }); + + it("getEditsForFileRename when referencing project doesnt include file and its renamed", () => { + const aTs: File = { path: "/a/src/a.ts", content: "" }; + const aTsconfig: File = { + path: "/a/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + composite: true, + declaration: true, + declarationMap: true, + outDir: "./build", + } + }), + }; + const bTs: File = { path: "/b/src/b.ts", content: "" }; + const bTsconfig: File = { + path: "/b/tsconfig.json", + content: JSON.stringify({ + compilerOptions: { + composite: true, + outDir: "./build", + }, + include: ["./src"], + references: [{ path: "../a" }], + }), + }; + + const host = createServerHost([aTs, aTsconfig, bTs, bTsconfig]); + const session = createSession(host); + openFilesForSession([aTs, bTs], session); + const response = executeSessionRequest(session, CommandNames.GetEditsForFileRename, { + oldFilePath: aTs.path, + newFilePath: "/a/src/a1.ts", + }); + assert.deepEqual>(response, []); // Should not change anything + }); }); describe("tsserverProjectSystem with tsbuild projects", () => { From ab4be8da42a3e2a768d9acca4ba034bc2c13eb4f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 7 Nov 2018 10:13:55 -0800 Subject: [PATCH 241/262] Fix the issue with file being included in the referencing project on rename when it wasnt included earlier Fixes #28307 --- src/compiler/sourcemapDecoder.ts | 2 +- src/services/sourcemaps.ts | 18 +- .../unittests/tsserverProjectSystem.ts | 193 ++++++++++++------ 3 files changed, 140 insertions(+), 73 deletions(-) diff --git a/src/compiler/sourcemapDecoder.ts b/src/compiler/sourcemapDecoder.ts index dd0d65c8092..5553509dacb 100644 --- a/src/compiler/sourcemapDecoder.ts +++ b/src/compiler/sourcemapDecoder.ts @@ -100,7 +100,7 @@ namespace ts.sourcemaps { function getSourceFileLike(fileName: string, location: string): SourceFileLike | undefined { // Lookup file in program, if provided const path = toPath(fileName, location, host.getCanonicalFileName); - const file = program && program.getSourceFile(path); + const file = program && program.getSourceFileByPath(path); // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file if (!file || file.resolvedPath !== path) { // Otherwise check the cache (which may hit disk) diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index 25e6fb9c124..cf903bb1f26 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -23,8 +23,12 @@ namespace ts { let sourcemappedFileCache: SourceFileLikeCache; return { tryGetOriginalLocation, tryGetGeneratedLocation, toLineColumnOffset, clearCache }; + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function scanForSourcemapURL(fileName: string) { - const mappedFile = sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); + const mappedFile = sourcemappedFileCache.get(toPath(fileName)); if (!mappedFile) { return; } @@ -88,7 +92,7 @@ namespace ts { } possibleMapLocations.push(fileName + ".map"); for (const location of possibleMapLocations) { - const mapPath = toPath(location, getDirectoryPath(fileName), getCanonicalFileName); + const mapPath = ts.toPath(location, getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { return convertDocumentToSourceMapper(file, host.readFile(mapPath)!, mapPath); // TODO: GH#18217 } @@ -120,12 +124,16 @@ namespace ts { } function getFile(fileName: string): SourceFileLike | undefined { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); + const path = toPath(fileName); + const file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } function toLineColumnOffset(fileName: string, position: number): LineAndCharacter { - const path = toPath(fileName, currentDirectory, getCanonicalFileName); - const file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path)!; // TODO: GH#18217 + const file = getFile(fileName)!; // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 5bc414903a9..4ac267979e7 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10562,90 +10562,149 @@ declare class TestLib { }); describe("tsserverProjectSystem with tsbuild projects", () => { - function getProjectFiles(project: string): [File, File] { - return [ - TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"), - TestFSWithWatch.getTsBuildProjectFile(project, "index.ts"), - ]; - } - - const project = "container"; - const containerLib = getProjectFiles("container/lib"); - const containerExec = getProjectFiles("container/exec"); - const containerCompositeExec = getProjectFiles("container/compositeExec"); - const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); - const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; - - function createHost() { + function createHost(files: ReadonlyArray, rootNames: ReadonlyArray) { const host = createServerHost(files); // ts build should succeed - const solutionBuilder = tscWatch.createSolutionBuilder(host, [containerConfig.path], {}); + const solutionBuilder = tscWatch.createSolutionBuilder(host, rootNames, {}); solutionBuilder.buildAllProjects(); assert.equal(host.getOutput().length, 0); return host; } - it("does not error on container only project", () => { - const host = createHost(); + describe("with container project", () => { + function getProjectFiles(project: string): [File, File] { + return [ + TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"), + TestFSWithWatch.getTsBuildProjectFile(project, "index.ts"), + ]; + } - // Open external project for the folder - const session = createSession(host); - const service = session.getProjectService(); - service.openExternalProjects([{ - projectFileName: TestFSWithWatch.getTsBuildProjectFilePath(project, project), - rootFiles: files.map(f => ({ fileName: f.path })), - options: {} - }]); - checkNumberOfProjects(service, { configuredProjects: 4 }); - files.forEach(f => { - const args: protocol.FileRequestArgs = { - file: f.path, - projectFileName: endsWith(f.path, "tsconfig.json") ? f.path : undefined - }; - const syntaxDiagnostics = session.executeCommandSeq({ - command: protocol.CommandTypes.SyntacticDiagnosticsSync, - arguments: args + const project = "container"; + const containerLib = getProjectFiles("container/lib"); + const containerExec = getProjectFiles("container/exec"); + const containerCompositeExec = getProjectFiles("container/compositeExec"); + const containerConfig = TestFSWithWatch.getTsBuildProjectFile(project, "tsconfig.json"); + const files = [libFile, ...containerLib, ...containerExec, ...containerCompositeExec, containerConfig]; + + it("does not error on container only project", () => { + const host = createHost(files, [containerConfig.path]); + + // Open external project for the folder + const session = createSession(host); + const service = session.getProjectService(); + service.openExternalProjects([{ + projectFileName: TestFSWithWatch.getTsBuildProjectFilePath(project, project), + rootFiles: files.map(f => ({ fileName: f.path })), + options: {} + }]); + checkNumberOfProjects(service, { configuredProjects: 4 }); + files.forEach(f => { + const args: protocol.FileRequestArgs = { + file: f.path, + projectFileName: endsWith(f.path, "tsconfig.json") ? f.path : undefined + }; + const syntaxDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SyntacticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(syntaxDiagnostics, []); + const semanticDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.SemanticDiagnosticsSync, + arguments: args + }).response; + assert.deepEqual(semanticDiagnostics, []); + }); + const containerProject = service.configuredProjects.get(containerConfig.path)!; + checkProjectActualFiles(containerProject, [containerConfig.path]); + const optionsDiagnostics = session.executeCommandSeq({ + command: protocol.CommandTypes.CompilerOptionsDiagnosticsFull, + arguments: { projectFileName: containerProject.projectName } }).response; - assert.deepEqual(syntaxDiagnostics, []); - const semanticDiagnostics = session.executeCommandSeq({ - command: protocol.CommandTypes.SemanticDiagnosticsSync, - arguments: args - }).response; - assert.deepEqual(semanticDiagnostics, []); + assert.deepEqual(optionsDiagnostics, []); + }); + + it("can successfully find references with --out options", () => { + const host = createHost(files, [containerConfig.path]); + const session = createSession(host); + openFilesForSession([containerCompositeExec[1]], session); + const service = session.getProjectService(); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const locationOfMyConst = protocolLocationFromSubstring(containerCompositeExec[1].content, "myConst"); + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.Rename, + arguments: { + file: containerCompositeExec[1].path, + ...locationOfMyConst + } + }).response as protocol.RenameResponseBody; + + + const myConstLen = "myConst".length; + const locationOfMyConstInLib = protocolLocationFromSubstring(containerLib[1].content, "myConst"); + assert.deepEqual(response.locs, [ + { file: containerCompositeExec[1].path, locs: [{ start: locationOfMyConst, end: { line: locationOfMyConst.line, offset: locationOfMyConst.offset + myConstLen } }] }, + { file: containerLib[1].path, locs: [{ start: locationOfMyConstInLib, end: { line: locationOfMyConstInLib.line, offset: locationOfMyConstInLib.offset + myConstLen } }] } + ]); }); - const containerProject = service.configuredProjects.get(containerConfig.path)!; - checkProjectActualFiles(containerProject, [containerConfig.path]); - const optionsDiagnostics = session.executeCommandSeq({ - command: protocol.CommandTypes.CompilerOptionsDiagnosticsFull, - arguments: { projectFileName: containerProject.projectName } - }).response; - assert.deepEqual(optionsDiagnostics, []); }); - it("can successfully find references with --out options", () => { - const host = createHost(); + it("can go to definition correctly", () => { + const projectLocation = "/user/username/projects/myproject"; + const dependecyLocation = `${projectLocation}/dependency`; + const mainLocation = `${projectLocation}/main`; + const dependencyTs: File = { + path: `${dependecyLocation}/fns.ts`, + content: `export function fn1() { } +export function fn2() { } +export function fn3() { } +export function fn4() { } +export function fn5() { }` + }; + const dependencyConfig: File = { + path: `${dependecyLocation}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true } }) + }; + + const mainTs: File = { + path: `${mainLocation}/main.ts`, + content: `import { + fn1, fn2, fn3, fn4, fn5 +} from '../dependency/fns' + +fn1(); +fn2(); +fn3(); +fn4(); +fn5();` + }; + const mainConfig: File = { + path: `${mainLocation}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { composite: true, declarationMap: true }, + references: [{ path: "../dependency" }] + }) + }; + + const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile]; + const host = createHost(files, [mainConfig.path]); const session = createSession(host); - openFilesForSession([containerCompositeExec[1]], session); const service = session.getProjectService(); + openFilesForSession([mainTs], session); checkNumberOfProjects(service, { configuredProjects: 1 }); - const locationOfMyConst = protocolLocationFromSubstring(containerCompositeExec[1].content, "myConst"); - const response = session.executeCommandSeq({ - command: protocol.CommandTypes.Rename, - arguments: { - file: containerCompositeExec[1].path, - ...locationOfMyConst - } - }).response as protocol.RenameResponseBody; - - - const myConstLen = "myConst".length; - const locationOfMyConstInLib = protocolLocationFromSubstring(containerLib[1].content, "myConst"); - assert.deepEqual(response.locs, [ - { file: containerCompositeExec[1].path, locs: [{ start: locationOfMyConst, end: { line: locationOfMyConst.line, offset: locationOfMyConst.offset + myConstLen } }] }, - { file: containerLib[1].path, locs: [{ start: locationOfMyConstInLib, end: { line: locationOfMyConstInLib.line, offset: locationOfMyConstInLib.offset + myConstLen } }] } - ]); + checkProjectActualFiles(service.configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, `${dependecyLocation}/fns.d.ts`]); + for (let i = 0; i < 5; i++) { + const startSpan = { line: i + 5, offset: 1 }; + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...startSpan } + }).response as protocol.DefinitionInfoAndBoundSpan; + assert.deepEqual(response, { + definitions: [{ file: dependencyTs.path, start: { line: i + 1, offset: 17 }, end: { line: i + 1, offset: 20 } }], + textSpan: { start: startSpan, end: { line: startSpan.line, offset: startSpan.offset + 3 } } + }); + } }); }); From 1a9c20949e42400e55194dbd1516c2eac6257275 Mon Sep 17 00:00:00 2001 From: EECOLOR Date: Fri, 19 Oct 2018 00:10:13 +0200 Subject: [PATCH 242/262] path mappings now supports rooted disk paths and urls - fixes #13730 --- src/compiler/moduleNameResolver.ts | 25 +- src/services/stringCompletions.ts | 27 +- src/testRunner/unittests/moduleResolution.ts | 8 + ...duleResolution_rootImport_aliasWithRoot.js | 26 ++ ...esolution_rootImport_aliasWithRoot.symbols | 15 + ...lution_rootImport_aliasWithRoot.trace.json | 34 +++ ...eResolution_rootImport_aliasWithRoot.types | 15 + ...Import_aliasWithRoot_differentRootTypes.js | 42 +++ ...t_aliasWithRoot_differentRootTypes.symbols | 81 ++++++ ...liasWithRoot_differentRootTypes.trace.json | 270 ++++++++++++++++++ ...ort_aliasWithRoot_differentRootTypes.types | 81 ++++++ ...ootImport_aliasWithRoot_multipleAliases.js | 26 ++ ...port_aliasWithRoot_multipleAliases.symbols | 15 + ...t_aliasWithRoot_multipleAliases.trace.json | 31 ++ ...Import_aliasWithRoot_multipleAliases.types | 15 + ...n_rootImport_aliasWithRoot_realRootFile.js | 26 ++ ...tImport_aliasWithRoot_realRootFile.symbols | 15 + ...port_aliasWithRoot_realRootFile.trace.json | 32 +++ ...ootImport_aliasWithRoot_realRootFile.types | 15 + ...leResolution_rootImport_noAliasWithRoot.js | 26 ++ ...olution_rootImport_noAliasWithRoot.symbols | 15 + ...tion_rootImport_noAliasWithRoot.trace.json | 34 +++ ...esolution_rootImport_noAliasWithRoot.types | 15 + ...rootImport_noAliasWithRoot_failedLookup.js | 26 ++ ...mport_noAliasWithRoot_failedLookup.symbols | 15 + ...rt_noAliasWithRoot_failedLookup.trace.json | 34 +++ ...tImport_noAliasWithRoot_failedLookup.types | 15 + ...rootImport_noAliasWithRoot_realRootFile.js | 26 ++ ...mport_noAliasWithRoot_realRootFile.symbols | 15 + ...rt_noAliasWithRoot_realRootFile.trace.json | 32 +++ ...tImport_noAliasWithRoot_realRootFile.types | 15 + ...duleResolution_rootImport_aliasWithRoot.ts | 25 ++ ...Import_aliasWithRoot_differentRootTypes.ts | 49 ++++ ...ootImport_aliasWithRoot_multipleAliases.ts | 26 ++ ...n_rootImport_aliasWithRoot_realRootFile.ts | 25 ++ ...leResolution_rootImport_noAliasWithRoot.ts | 25 ++ ...rootImport_noAliasWithRoot_realRootFile.ts | 25 ++ ...tionForStringLiteralNonrelativeImport14.ts | 28 ++ ...tionForStringLiteralNonrelativeImport15.ts | 28 ++ .../TypeScript-Node-Starter | 2 +- 40 files changed, 1276 insertions(+), 24 deletions(-) create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.types create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.js create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.symbols create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.trace.json create mode 100644 tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.types create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.ts create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.ts create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.ts create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.ts create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.ts create mode 100644 tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.ts create mode 100644 tests/cases/fourslash/completionForStringLiteralNonrelativeImport14.ts create mode 100644 tests/cases/fourslash/completionForStringLiteralNonrelativeImport15.ts diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 4d32cae86f7..b8aa9fa2df4 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -730,6 +730,9 @@ namespace ts { function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { + const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) return resolved.value; + if (!isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } @@ -738,6 +741,17 @@ namespace ts { } } + function tryLoadModuleUsingPathsIfEligible(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState) { + const { baseUrl, paths } = state.compilerOptions; + if (baseUrl && paths && !pathIsRelative(moduleName)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); + trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + } + } + function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { @@ -816,22 +830,13 @@ namespace ts { } function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { - const { baseUrl, paths } = state.compilerOptions; + const { baseUrl } = state.compilerOptions; if (!baseUrl) { return undefined; } if (state.traceEnabled) { trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - if (paths) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - const resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); - if (resolved) { - return resolved.value; - } - } const candidate = normalizePath(combinePaths(baseUrl, moduleName)); if (state.traceEnabled) { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index 4726e06ec42..7e60edc03d7 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -247,19 +247,9 @@ namespace ts.Completions.StringCompletions { const scriptPath = sourceFile.path; const scriptDirectory = getDirectoryPath(scriptPath); - const extensionOptions = getExtensionOptions(compilerOptions); - if (isPathRelativeToScript(literalValue) || isRootedDiskPath(literalValue)) { - if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs( - compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); - } - else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); - } - } - else { - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); - } + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue)) + ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath) + : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } interface ExtensionOptions { @@ -269,6 +259,17 @@ namespace ts.Completions.StringCompletions { function getExtensionOptions(compilerOptions: CompilerOptions, includeExtensions = false): ExtensionOptions { return { extensions: getSupportedExtensionsForModuleResolution(compilerOptions), includeExtensions }; } + function getCompletionEntriesForRelativeModules(literalValue: string, scriptDirectory: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, scriptPath: Path) { + const extensionOptions = getExtensionOptions(compilerOptions); + if (compilerOptions.rootDirs) { + return getCompletionEntriesForDirectoryFragmentWithRootDirs( + compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath); + } + else { + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath); + } + } + function getSupportedExtensionsForModuleResolution(compilerOptions: CompilerOptions): ReadonlyArray { const extensions = getSupportedExtensions(compilerOptions); return compilerOptions.resolveJsonModule && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs ? diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 27331d6d007..05e17384978 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -757,6 +757,9 @@ import b = require("./moduleB"); ], "somefolder/*": [ "someanotherfolder/*" + ], + "/rooted/*": [ + "generated/*" ] } }; @@ -773,6 +776,7 @@ import b = require("./moduleB"); "/root/folder1/file2/index.d.ts", // then first attempt on 'generated/*' was successful ]); + check("/rooted/folder1/file2", file2, []); check("folder2/file3", file3, [ // first try '*' "/root/folder2/file3.ts", @@ -900,6 +904,9 @@ import b = require("./moduleB"); ], "somefolder/*": [ "someanotherfolder/*" + ], + "/rooted/*": [ + "generated/*" ] } }; @@ -911,6 +918,7 @@ import b = require("./moduleB"); "/root/folder1/file2.d.ts", // success when using 'generated/*' ]); + check("/rooted/folder1/file2", file2, []); check("folder1/file3", file3, [ // first try '*' "/root/folder1/file3.ts", diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.js new file mode 100644 index 00000000000..b880a69fe2d --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/foo"; +import { bar } from "/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.symbols new file mode 100644 index 00000000000..3509e873a65 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.symbols @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /root/src/foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /root/src/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.trace.json new file mode 100644 index 00000000000..3a069183090 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.trace.json @@ -0,0 +1,34 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/root/src/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.types new file mode 100644 index 00000000000..67c03269afe --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.types @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : () => void + +import { bar } from "/bar"; +>bar : () => void + +=== /root/src/foo.ts === +export function foo() {} +>foo : () => void + +=== /root/src/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.js new file mode 100644 index 00000000000..a7e74a35a45 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.js @@ -0,0 +1,42 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo as foo1 } from "/foo"; +import { bar as bar1 } from "/bar"; +import { foo as foo2 } from "c:/foo"; +import { bar as bar2 } from "c:/bar"; +import { foo as foo3 } from "c:\\foo"; +import { bar as bar3 } from "c:\\bar"; +import { foo as foo4 } from "//server/foo"; +import { bar as bar4 } from "//server/bar"; +import { foo as foo5 } from "\\\\server\\foo"; +import { bar as bar5 } from "\\\\server\\bar"; +import { foo as foo6 } from "file:///foo"; +import { bar as bar6 } from "file:///bar"; +import { foo as foo7 } from "file://c:/foo"; +import { bar as bar7 } from "file://c:/bar"; +import { foo as foo8 } from "file://server/foo"; +import { bar as bar8 } from "file://server/bar"; +import { foo as foo9 } from "http://server/foo"; +import { bar as bar9 } from "http://server/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.symbols new file mode 100644 index 00000000000..5572ccfb5d0 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.symbols @@ -0,0 +1,81 @@ +=== /root/a.ts === +import { foo as foo1 } from "/foo"; +>foo : Symbol(foo1, Decl(a.ts, 0, 8)) +>foo1 : Symbol(foo1, Decl(a.ts, 0, 8)) + +import { bar as bar1 } from "/bar"; +>bar : Symbol(bar1, Decl(a.ts, 1, 8)) +>bar1 : Symbol(bar1, Decl(a.ts, 1, 8)) + +import { foo as foo2 } from "c:/foo"; +>foo : Symbol(foo2, Decl(a.ts, 2, 8)) +>foo2 : Symbol(foo2, Decl(a.ts, 2, 8)) + +import { bar as bar2 } from "c:/bar"; +>bar : Symbol(bar2, Decl(a.ts, 3, 8)) +>bar2 : Symbol(bar2, Decl(a.ts, 3, 8)) + +import { foo as foo3 } from "c:\\foo"; +>foo : Symbol(foo3, Decl(a.ts, 4, 8)) +>foo3 : Symbol(foo3, Decl(a.ts, 4, 8)) + +import { bar as bar3 } from "c:\\bar"; +>bar : Symbol(bar3, Decl(a.ts, 5, 8)) +>bar3 : Symbol(bar3, Decl(a.ts, 5, 8)) + +import { foo as foo4 } from "//server/foo"; +>foo : Symbol(foo4, Decl(a.ts, 6, 8)) +>foo4 : Symbol(foo4, Decl(a.ts, 6, 8)) + +import { bar as bar4 } from "//server/bar"; +>bar : Symbol(bar4, Decl(a.ts, 7, 8)) +>bar4 : Symbol(bar4, Decl(a.ts, 7, 8)) + +import { foo as foo5 } from "\\\\server\\foo"; +>foo : Symbol(foo5, Decl(a.ts, 8, 8)) +>foo5 : Symbol(foo5, Decl(a.ts, 8, 8)) + +import { bar as bar5 } from "\\\\server\\bar"; +>bar : Symbol(bar5, Decl(a.ts, 9, 8)) +>bar5 : Symbol(bar5, Decl(a.ts, 9, 8)) + +import { foo as foo6 } from "file:///foo"; +>foo : Symbol(foo6, Decl(a.ts, 10, 8)) +>foo6 : Symbol(foo6, Decl(a.ts, 10, 8)) + +import { bar as bar6 } from "file:///bar"; +>bar : Symbol(bar6, Decl(a.ts, 11, 8)) +>bar6 : Symbol(bar6, Decl(a.ts, 11, 8)) + +import { foo as foo7 } from "file://c:/foo"; +>foo : Symbol(foo7, Decl(a.ts, 12, 8)) +>foo7 : Symbol(foo7, Decl(a.ts, 12, 8)) + +import { bar as bar7 } from "file://c:/bar"; +>bar : Symbol(bar7, Decl(a.ts, 13, 8)) +>bar7 : Symbol(bar7, Decl(a.ts, 13, 8)) + +import { foo as foo8 } from "file://server/foo"; +>foo : Symbol(foo8, Decl(a.ts, 14, 8)) +>foo8 : Symbol(foo8, Decl(a.ts, 14, 8)) + +import { bar as bar8 } from "file://server/bar"; +>bar : Symbol(bar8, Decl(a.ts, 15, 8)) +>bar8 : Symbol(bar8, Decl(a.ts, 15, 8)) + +import { foo as foo9 } from "http://server/foo"; +>foo : Symbol(foo9, Decl(a.ts, 16, 8)) +>foo9 : Symbol(foo9, Decl(a.ts, 16, 8)) + +import { bar as bar9 } from "http://server/bar"; +>bar : Symbol(bar9, Decl(a.ts, 17, 8)) +>bar9 : Symbol(bar9, Decl(a.ts, 17, 8)) + +=== /root/src/foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /root/src/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.trace.json new file mode 100644 index 00000000000..f00e7ffab85 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.trace.json @@ -0,0 +1,270 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'c:/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:/foo'.", + "'paths' option is specified, looking for a pattern to match module name 'c:/foo'.", + "Module name 'c:/foo', matched pattern 'c:/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'c:/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'c:/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'c:/bar'.", + "Module name 'c:/bar', matched pattern 'c:/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location 'c:/bar', target file type 'TypeScript'.", + "Directory 'c:/' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'c:/bar'.", + "Module name 'c:/bar', matched pattern 'c:/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'c:/bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'c:\\foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:\\foo'.", + "'paths' option is specified, looking for a pattern to match module name 'c:\\foo'.", + "Module name 'c:\\foo', matched pattern 'c:\\*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'c:\\foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'c:\\bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:\\bar'.", + "'paths' option is specified, looking for a pattern to match module name 'c:\\bar'.", + "Module name 'c:\\bar', matched pattern 'c:\\*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location 'c:/bar', target file type 'TypeScript'.", + "Directory 'c:/' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'c:\\bar'.", + "'paths' option is specified, looking for a pattern to match module name 'c:\\bar'.", + "Module name 'c:\\bar', matched pattern 'c:\\*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'c:\\bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module '//server/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '//server/foo'.", + "'paths' option is specified, looking for a pattern to match module name '//server/foo'.", + "Module name '//server/foo', matched pattern '//server/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '//server/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '//server/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '//server/bar'.", + "'paths' option is specified, looking for a pattern to match module name '//server/bar'.", + "Module name '//server/bar', matched pattern '//server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '//server/bar', target file type 'TypeScript'.", + "Directory '//server/' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '//server/bar'.", + "'paths' option is specified, looking for a pattern to match module name '//server/bar'.", + "Module name '//server/bar', matched pattern '//server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '//server/bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module '\\\\server\\foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '\\\\server\\foo'.", + "'paths' option is specified, looking for a pattern to match module name '\\\\server\\foo'.", + "Module name '\\\\server\\foo', matched pattern '\\\\server\\*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '\\\\server\\foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '\\\\server\\bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '\\\\server\\bar'.", + "'paths' option is specified, looking for a pattern to match module name '\\\\server\\bar'.", + "Module name '\\\\server\\bar', matched pattern '\\\\server\\*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '//server/bar', target file type 'TypeScript'.", + "Directory '//server/' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '\\\\server\\bar'.", + "'paths' option is specified, looking for a pattern to match module name '\\\\server\\bar'.", + "Module name '\\\\server\\bar', matched pattern '\\\\server\\*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '\\\\server\\bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'file:///foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file:///foo'.", + "'paths' option is specified, looking for a pattern to match module name 'file:///foo'.", + "Module name 'file:///foo', matched pattern 'file:///*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'file:///foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'file:///bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file:///bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file:///bar'.", + "Module name 'file:///bar', matched pattern 'file:///*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module 'file:///bar' from 'node_modules' folder, target file type 'TypeScript'.", + "Directory '/root/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file:///bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file:///bar'.", + "Module name 'file:///bar', matched pattern 'file:///*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'file:///bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'file://c:/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://c:/foo'.", + "'paths' option is specified, looking for a pattern to match module name 'file://c:/foo'.", + "Module name 'file://c:/foo', matched pattern 'file://c:/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'file://c:/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'file://c:/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://c:/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file://c:/bar'.", + "Module name 'file://c:/bar', matched pattern 'file://c:/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module 'file://c:/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "Directory '/root/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://c:/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file://c:/bar'.", + "Module name 'file://c:/bar', matched pattern 'file://c:/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'file://c:/bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'file://server/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://server/foo'.", + "'paths' option is specified, looking for a pattern to match module name 'file://server/foo'.", + "Module name 'file://server/foo', matched pattern 'file://server/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'file://server/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'file://server/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://server/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file://server/bar'.", + "Module name 'file://server/bar', matched pattern 'file://server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module 'file://server/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "Directory '/root/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'file://server/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'file://server/bar'.", + "Module name 'file://server/bar', matched pattern 'file://server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'file://server/bar' was successfully resolved to '/root/src/bar.js'. ========", + "======== Resolving module 'http://server/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'http://server/foo'.", + "'paths' option is specified, looking for a pattern to match module name 'http://server/foo'.", + "Module name 'http://server/foo', matched pattern 'http://server/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name 'http://server/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module 'http://server/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'http://server/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'http://server/bar'.", + "Module name 'http://server/bar', matched pattern 'http://server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module 'http://server/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "Directory '/root/node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name 'http://server/bar'.", + "'paths' option is specified, looking for a pattern to match module name 'http://server/bar'.", + "Module name 'http://server/bar', matched pattern 'http://server/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name 'http://server/bar' was successfully resolved to '/root/src/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.types new file mode 100644 index 00000000000..17c00ec2ccb --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.types @@ -0,0 +1,81 @@ +=== /root/a.ts === +import { foo as foo1 } from "/foo"; +>foo : () => void +>foo1 : () => void + +import { bar as bar1 } from "/bar"; +>bar : () => void +>bar1 : () => void + +import { foo as foo2 } from "c:/foo"; +>foo : () => void +>foo2 : () => void + +import { bar as bar2 } from "c:/bar"; +>bar : () => void +>bar2 : () => void + +import { foo as foo3 } from "c:\\foo"; +>foo : () => void +>foo3 : () => void + +import { bar as bar3 } from "c:\\bar"; +>bar : () => void +>bar3 : () => void + +import { foo as foo4 } from "//server/foo"; +>foo : () => void +>foo4 : () => void + +import { bar as bar4 } from "//server/bar"; +>bar : () => void +>bar4 : () => void + +import { foo as foo5 } from "\\\\server\\foo"; +>foo : () => void +>foo5 : () => void + +import { bar as bar5 } from "\\\\server\\bar"; +>bar : () => void +>bar5 : () => void + +import { foo as foo6 } from "file:///foo"; +>foo : () => void +>foo6 : () => void + +import { bar as bar6 } from "file:///bar"; +>bar : () => void +>bar6 : () => void + +import { foo as foo7 } from "file://c:/foo"; +>foo : () => void +>foo7 : () => void + +import { bar as bar7 } from "file://c:/bar"; +>bar : () => void +>bar7 : () => void + +import { foo as foo8 } from "file://server/foo"; +>foo : () => void +>foo8 : () => void + +import { bar as bar8 } from "file://server/bar"; +>bar : () => void +>bar8 : () => void + +import { foo as foo9 } from "http://server/foo"; +>foo : () => void +>foo9 : () => void + +import { bar as bar9 } from "http://server/bar"; +>bar : () => void +>bar9 : () => void + +=== /root/src/foo.ts === +export function foo() {} +>foo : () => void + +=== /root/src/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.js new file mode 100644 index 00000000000..59b7c085676 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/import/foo"; +import { bar } from "/client/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.symbols new file mode 100644 index 00000000000..a088f80ad3d --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.symbols @@ -0,0 +1,15 @@ +=== /root/src/a.ts === +import { foo } from "/import/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/client/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /root/import/foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /root/client/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.trace.json new file mode 100644 index 00000000000..9ee9c816b63 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.trace.json @@ -0,0 +1,31 @@ +[ + "======== Resolving module '/import/foo' from '/root/src/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/import/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/import/foo'.", + "Module name '/import/foo', matched pattern '/import/*'.", + "Trying substitution './import/*', candidate module location: './import/foo'.", + "Loading module as file / folder, candidate module location '/root/import/foo', target file type 'TypeScript'.", + "File '/root/import/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/import/foo' was successfully resolved to '/root/import/foo.ts'. ========", + "======== Resolving module '/client/bar' from '/root/src/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/client/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/client/bar'.", + "Module name '/client/bar', matched pattern '/client/*'.", + "Trying substitution './client/*', candidate module location: './client/bar'.", + "Loading module as file / folder, candidate module location '/root/client/bar', target file type 'TypeScript'.", + "File '/root/client/bar.ts' does not exist.", + "File '/root/client/bar.tsx' does not exist.", + "File '/root/client/bar.d.ts' does not exist.", + "Directory '/root/client/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '/client/bar', target file type 'TypeScript'.", + "Directory '/client' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/client/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/client/bar'.", + "Module name '/client/bar', matched pattern '/client/*'.", + "Trying substitution './client/*', candidate module location: './client/bar'.", + "Loading module as file / folder, candidate module location '/root/client/bar', target file type 'JavaScript'.", + "File '/root/client/bar.js' exist - use it as a name resolution result.", + "======== Module name '/client/bar' was successfully resolved to '/root/client/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.types new file mode 100644 index 00000000000..556f6fbb1cd --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.types @@ -0,0 +1,15 @@ +=== /root/src/a.ts === +import { foo } from "/import/foo"; +>foo : () => void + +import { bar } from "/client/bar"; +>bar : () => void + +=== /root/import/foo.ts === +export function foo() {} +>foo : () => void + +=== /root/client/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.js new file mode 100644 index 00000000000..aa8645bc401 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/foo"; +import { bar } from "/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.symbols new file mode 100644 index 00000000000..e3abb84bf63 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.symbols @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.trace.json new file mode 100644 index 00000000000..1b2d42bacdd --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.trace.json @@ -0,0 +1,32 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "Loading module as file / folder, candidate module location '/foo', target file type 'TypeScript'.", + "File '/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '/*'.", + "Trying substitution './src/*', candidate module location: './src/bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "Loading module as file / folder, candidate module location '/bar', target file type 'JavaScript'.", + "File '/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.types new file mode 100644 index 00000000000..538b6127236 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.types @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : () => void + +import { bar } from "/bar"; +>bar : () => void + +=== /foo.ts === +export function foo() {} +>foo : () => void + +=== /bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.js new file mode 100644 index 00000000000..bce7220d628 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/foo"; +import { bar } from "/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.symbols new file mode 100644 index 00000000000..3509e873a65 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.symbols @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /root/src/foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /root/src/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.trace.json new file mode 100644 index 00000000000..7eaac73acb9 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.trace.json @@ -0,0 +1,34 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/root/src/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.types new file mode 100644 index 00000000000..67c03269afe --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.types @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : () => void + +import { bar } from "/bar"; +>bar : () => void + +=== /root/src/foo.ts === +export function foo() {} +>foo : () => void + +=== /root/src/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.js new file mode 100644 index 00000000000..87217a9c327 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/foo"; +import { bar } from "/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.symbols new file mode 100644 index 00000000000..3509e873a65 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.symbols @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /root/src/foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /root/src/bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.trace.json new file mode 100644 index 00000000000..7eaac73acb9 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.trace.json @@ -0,0 +1,34 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "File '/root/src/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/root/src/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "File '/root/src/bar.ts' does not exist.", + "File '/root/src/bar.tsx' does not exist.", + "File '/root/src/bar.d.ts' does not exist.", + "Directory '/root/src/bar' does not exist, skipping all lookups in it.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "File '/root/src/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/root/src/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.types new file mode 100644 index 00000000000..67c03269afe --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_failedLookup.types @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : () => void + +import { bar } from "/bar"; +>bar : () => void + +=== /root/src/foo.ts === +export function foo() {} +>foo : () => void + +=== /root/src/bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.js b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.js new file mode 100644 index 00000000000..23dd9fb91e0 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.js @@ -0,0 +1,26 @@ +//// [tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.ts] //// + +//// [foo.ts] +export function foo() {} + +//// [bar.js] +export function bar() {} + +//// [a.ts] +import { foo } from "/foo"; +import { bar } from "/bar"; + + +//// [foo.js] +"use strict"; +exports.__esModule = true; +function foo() { } +exports.foo = foo; +//// [bar.js] +"use strict"; +exports.__esModule = true; +function bar() { } +exports.bar = bar; +//// [a.js] +"use strict"; +exports.__esModule = true; diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.symbols b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.symbols new file mode 100644 index 00000000000..e3abb84bf63 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.symbols @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : Symbol(foo, Decl(a.ts, 0, 8)) + +import { bar } from "/bar"; +>bar : Symbol(bar, Decl(a.ts, 1, 8)) + +=== /foo.ts === +export function foo() {} +>foo : Symbol(foo, Decl(foo.ts, 0, 0)) + +=== /bar.js === +export function bar() {} +>bar : Symbol(bar, Decl(bar.js, 0, 0)) + diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.trace.json new file mode 100644 index 00000000000..505871d8f31 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.trace.json @@ -0,0 +1,32 @@ +[ + "======== Resolving module '/foo' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/foo'.", + "'paths' option is specified, looking for a pattern to match module name '/foo'.", + "Module name '/foo', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//foo'.", + "Loading module as file / folder, candidate module location '/root/src/foo', target file type 'TypeScript'.", + "Loading module as file / folder, candidate module location '/foo', target file type 'TypeScript'.", + "File '/foo.ts' exist - use it as a name resolution result.", + "======== Module name '/foo' was successfully resolved to '/foo.ts'. ========", + "======== Resolving module '/bar' from '/root/a.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'TypeScript'.", + "Loading module as file / folder, candidate module location '/bar', target file type 'TypeScript'.", + "File '/bar.ts' does not exist.", + "File '/bar.tsx' does not exist.", + "File '/bar.d.ts' does not exist.", + "Directory '/bar' does not exist, skipping all lookups in it.", + "'baseUrl' option is set to '/root', using this value to resolve non-relative module name '/bar'.", + "'paths' option is specified, looking for a pattern to match module name '/bar'.", + "Module name '/bar', matched pattern '*'.", + "Trying substitution './src/*', candidate module location: './src//bar'.", + "Loading module as file / folder, candidate module location '/root/src/bar', target file type 'JavaScript'.", + "Loading module as file / folder, candidate module location '/bar', target file type 'JavaScript'.", + "File '/bar.js' exist - use it as a name resolution result.", + "======== Module name '/bar' was successfully resolved to '/bar.js'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.types b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.types new file mode 100644 index 00000000000..538b6127236 --- /dev/null +++ b/tests/baselines/reference/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.types @@ -0,0 +1,15 @@ +=== /root/a.ts === +import { foo } from "/foo"; +>foo : () => void + +import { bar } from "/bar"; +>bar : () => void + +=== /foo.ts === +export function foo() {} +>foo : () => void + +=== /bar.js === +export function bar() {} +>bar : () => void + diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.ts new file mode 100644 index 00000000000..9af12c71a95 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot.ts @@ -0,0 +1,25 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /root/src/foo.ts +export function foo() {} + +// @filename: /root/src/bar.js +export function bar() {} + +// @filename: /root/a.ts +import { foo } from "/foo"; +import { bar } from "/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "/*": ["./src/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.ts new file mode 100644 index 00000000000..a9fd2cde5bd --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_differentRootTypes.ts @@ -0,0 +1,49 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /root/src/foo.ts +export function foo() {} + +// @filename: /root/src/bar.js +export function bar() {} + +// @filename: /root/a.ts +import { foo as foo1 } from "/foo"; +import { bar as bar1 } from "/bar"; +import { foo as foo2 } from "c:/foo"; +import { bar as bar2 } from "c:/bar"; +import { foo as foo3 } from "c:\\foo"; +import { bar as bar3 } from "c:\\bar"; +import { foo as foo4 } from "//server/foo"; +import { bar as bar4 } from "//server/bar"; +import { foo as foo5 } from "\\\\server\\foo"; +import { bar as bar5 } from "\\\\server\\bar"; +import { foo as foo6 } from "file:///foo"; +import { bar as bar6 } from "file:///bar"; +import { foo as foo7 } from "file://c:/foo"; +import { bar as bar7 } from "file://c:/bar"; +import { foo as foo8 } from "file://server/foo"; +import { bar as bar8 } from "file://server/bar"; +import { foo as foo9 } from "http://server/foo"; +import { bar as bar9 } from "http://server/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "/*": ["./src/*"], + "c:/*": ["./src/*"], + "c:\\*": ["./src/*"], + "//server/*": ["./src/*"], + "\\\\server\\*": ["./src/*"], + "file:///*": ["./src/*"], + "file://c:/*": ["./src/*"], + "file://server/*": ["./src/*"], + "http://server/*": ["./src/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.ts new file mode 100644 index 00000000000..5225f1dbd05 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_multipleAliases.ts @@ -0,0 +1,26 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /root/import/foo.ts +export function foo() {} + +// @filename: /root/client/bar.js +export function bar() {} + +// @filename: /root/src/a.ts +import { foo } from "/import/foo"; +import { bar } from "/client/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "/client/*": ["./client/*"], + "/import/*": ["./import/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.ts new file mode 100644 index 00000000000..e45a25b1e11 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_aliasWithRoot_realRootFile.ts @@ -0,0 +1,25 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /foo.ts +export function foo() {} + +// @filename: /bar.js +export function bar() {} + +// @filename: /root/a.ts +import { foo } from "/foo"; +import { bar } from "/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "/*": ["./src/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.ts new file mode 100644 index 00000000000..d05ea12b257 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot.ts @@ -0,0 +1,25 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /root/src/foo.ts +export function foo() {} + +// @filename: /root/src/bar.js +export function bar() {} + +// @filename: /root/a.ts +import { foo } from "/foo"; +import { bar } from "/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "*": ["./src/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.ts b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.ts new file mode 100644 index 00000000000..eb552c73c82 --- /dev/null +++ b/tests/cases/compiler/pathMappingBasedModuleResolution_rootImport_noAliasWithRoot_realRootFile.ts @@ -0,0 +1,25 @@ +// @noImplicitReferences: true +// @traceResolution: true +// @allowJs: true + +// @filename: /foo.ts +export function foo() {} + +// @filename: /bar.js +export function bar() {} + +// @filename: /root/a.ts +import { foo } from "/foo"; +import { bar } from "/bar"; + +// @filename: /root/tsconfig.json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "*": ["./src/*"] + }, + "allowJs": true, + "outDir": "bin" + } +} diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport14.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport14.ts new file mode 100644 index 00000000000..dac27a6c307 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport14.ts @@ -0,0 +1,28 @@ +/// + +// Should give completions for modules referenced via baseUrl and paths compiler options with explicit name mappings + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "baseUrl": "./modules", +//// "paths": { +//// "/module1": ["some/path/whatever.ts"], +//// "/module2": ["some/other/path.ts"] +//// } +//// } +//// } + + +// @Filename: tests/test0.ts +//// import * as foo1 from "//*import_as0*/ +//// import foo2 = require("//*import_equals0*/ +//// var foo3 = require("//*require0*/ + +// @Filename: some/path/whatever.ts +//// export var x = 9; + +// @Filename: some/other/path.ts +//// export var y = 10; + +verify.completions({ marker: test.markerNames(), exact: ["lib", "tests", "/module1", "/module2"], isNewIdentifierLocation: true }); diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport15.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport15.ts new file mode 100644 index 00000000000..170fdd01be1 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport15.ts @@ -0,0 +1,28 @@ +/// + +// Should give completions for modules referenced via baseUrl and paths compiler options with explicit name mappings + +// @Filename: tsconfig.json +//// { +//// "compilerOptions": { +//// "baseUrl": "./modules", +//// "paths": { +//// "/module1": ["some/path/whatever.ts"], +//// "/module2": ["some/other/path.ts"] +//// } +//// } +//// } + + +// @Filename: tests/test0.ts +//// import * as foo1 from "//m*import_as0*/ +//// import foo2 = require("//m*import_equals0*/ +//// var foo3 = require("//m*require0*/ + +// @Filename: some/path/whatever.ts +//// export var x = 9; + +// @Filename: some/other/path.ts +//// export var y = 10; + +verify.completions({ marker: test.markerNames(), exact: ["/module1", "/module2"], isNewIdentifierLocation: true }); diff --git a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter index 40bdb4eadab..4779cb7e182 160000 --- a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter +++ b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter @@ -1 +1 @@ -Subproject commit 40bdb4eadabc9fbed7d83e3f26817a931c0763b6 +Subproject commit 4779cb7e182cf41d5c62289bb80d2850e0265b71 From 3ec06038d5c8569a4152e24d635f67357dacf35a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 7 Nov 2018 13:47:30 -0800 Subject: [PATCH 243/262] Retain the casing in map files in file names --- src/compiler/sourcemapDecoder.ts | 4 ++-- src/testRunner/unittests/tsserverProjectSystem.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/compiler/sourcemapDecoder.ts b/src/compiler/sourcemapDecoder.ts index 5553509dacb..17cd1375f70 100644 --- a/src/compiler/sourcemapDecoder.ts +++ b/src/compiler/sourcemapDecoder.ts @@ -83,7 +83,7 @@ namespace ts.sourcemaps { if (!maps[targetIndex] || comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot, !host.useCaseSensitiveFileNames) !== 0) { return loc; } - return { fileName: toPath(map.file!, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + return { fileName: getNormalizedAbsolutePath(map.file!, sourceRoot), position: maps[targetIndex].emittedPosition }; // Closest pos } function getOriginalPosition(loc: SourceMappableLocation): SourceMappableLocation { @@ -94,7 +94,7 @@ namespace ts.sourcemaps { // if no exact match, closest is 2's compliment of result targetIndex = ~targetIndex; } - return { fileName: toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + return { fileName: getNormalizedAbsolutePath(maps[targetIndex].sourcePath, sourceRoot), position: maps[targetIndex].sourcePosition }; // Closest pos } function getSourceFileLike(fileName: string, location: string): SourceFileLike | undefined { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 4ac267979e7..171070e2cb4 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -10655,7 +10655,7 @@ declare class TestLib { const dependecyLocation = `${projectLocation}/dependency`; const mainLocation = `${projectLocation}/main`; const dependencyTs: File = { - path: `${dependecyLocation}/fns.ts`, + path: `${dependecyLocation}/FnS.ts`, content: `export function fn1() { } export function fn2() { } export function fn3() { } From 6ad58b242e2fe4d8d0adb9009c6f0e7e59d56253 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 7 Nov 2018 15:46:13 -0800 Subject: [PATCH 244/262] Do not output summary if theres nothing to report --- src/compiler/watch.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 345991baefc..24563c1b535 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -117,6 +117,7 @@ namespace ts { } export function getErrorSummaryText(errorCount: number, newLine: string) { + if (errorCount === 0) return ""; const d = createCompilerDiagnostic(errorCount === 1 ? Diagnostics.Found_1_error : Diagnostics.Found_0_errors, errorCount); return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`; } From 7736ea4e93ba867667cc128bb07926f6d5aed2c8 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 7 Nov 2018 14:55:19 -0800 Subject: [PATCH 245/262] Add tests that create relative path even though the script info isnt dynamic --- .../unittests/tsserverProjectSystem.ts | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 171070e2cb4..31ca9403215 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -3301,6 +3301,23 @@ namespace ts.projectSystem { }); }); + it("dynamic file with reference paths external project", () => { + const file: File = { + path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", + content: `/// +/// +var x = 10;` + }; + const host = createServerHost([libFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file.path, file.content); + + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + checkProjectRootFiles(project, [file.path]); + checkProjectActualFiles(project, [file.path, libFile.path]); + }); + it("files opened, closed affecting multiple projects", () => { const file: File = { path: "/a/b/projects/config/file.ts", @@ -3893,8 +3910,8 @@ namespace ts.projectSystem { command: server.CommandNames.Open, arguments: { file: untitledFile, - fileContent: "", - scriptKindName: "JS", + fileContent: `/// `, + scriptKindName: "TS", projectRootPath: useProjectRoot ? folderPath : undefined } }); @@ -10772,16 +10789,16 @@ fn5();` const untitledFile = "untitled:^Untitled-1"; executeSessionRequestNoResponse(session, protocol.CommandTypes.Open, { file: untitledFile, - fileContent: "let foo = 1;\nfooo/**/", + fileContent: `/// \nlet foo = 1;\nfooo/**/`, scriptKindName: "TS", projectRootPath: "/proj", }); const response = executeSessionRequest(session, protocol.CommandTypes.GetCodeFixes, { file: untitledFile, - startLine: 2, + startLine: 3, startOffset: 1, - endLine: 2, + endLine: 3, endOffset: 5, errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], }); @@ -10794,8 +10811,8 @@ fn5();` changes: [{ fileName: untitledFile, textChanges: [{ - start: { line: 2, offset: 1 }, - end: { line: 2, offset: 5 }, + start: { line: 3, offset: 1 }, + end: { line: 3, offset: 5 }, newText: "foo", }], }], From 9eecf3bd681f458cb60de211678feb841c1d063f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 19 Oct 2018 15:03:05 -0700 Subject: [PATCH 246/262] Some reorg --- src/server/editorServices.ts | 4 +- src/server/session.ts | 93 +++++++++++++++++++++++------------- 2 files changed, 62 insertions(+), 35 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 2f3c6204937..eb9b7118c5f 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -835,9 +835,9 @@ namespace ts.server { /* @internal */ private forEachProject(cb: (project: Project) => void) { - this.inferredProjects.forEach(cb); - this.configuredProjects.forEach(cb); this.externalProjects.forEach(cb); + this.configuredProjects.forEach(cb); + this.inferredProjects.forEach(cb); } /* @internal */ diff --git a/src/server/session.ts b/src/server/session.ts index 10399e21680..43b624668de 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -289,7 +289,6 @@ namespace ts.server { function combineProjectOutputWhileOpeningReferencedProjects( projects: Projects, defaultProject: Project, - projectService: ProjectService, action: (project: Project) => ReadonlyArray, getLocation: (t: T) => sourcemaps.SourceMappableLocation, resultsEqual: (a: T, b: T) => boolean, @@ -299,7 +298,6 @@ namespace ts.server { projects, defaultProject, /*initialLocation*/ undefined, - projectService, ({ project }, tryAddToTodo) => { for (const output of action(project)) { if (!contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { @@ -312,17 +310,27 @@ namespace ts.server { } function combineProjectOutputForRenameLocations( - projects: Projects, defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation, projectService: ProjectService, findInStrings: boolean, findInComments: boolean + projects: Projects, + defaultProject: Project, + initialLocation: sourcemaps.SourceMappableLocation, + findInStrings: boolean, + findInComments: boolean ): ReadonlyArray { const outputs: RenameLocation[] = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, tryAddToTodo) => { - for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || emptyArray) { - if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { - outputs.push(output); + combineProjectOutputWorker( + projects, + defaultProject, + initialLocation, + ({ project, location }, tryAddToTodo) => { + for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.position, findInStrings, findInComments) || emptyArray) { + if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { + outputs.push(output); + } } - } - }, () => getDefinitionLocation(defaultProject, initialLocation)); + }, + () => getDefinitionLocation(defaultProject, initialLocation) + ); return outputs; } @@ -333,31 +341,41 @@ namespace ts.server { return info && { fileName: info.fileName, position: info.textSpan.start }; } - function combineProjectOutputForReferences(projects: Projects, defaultProject: Project, initialLocation: sourcemaps.SourceMappableLocation, projectService: ProjectService): ReadonlyArray { + function combineProjectOutputForReferences( + projects: Projects, + defaultProject: Project, + initialLocation: sourcemaps.SourceMappableLocation + ): ReadonlyArray { const outputs: ReferencedSymbol[] = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, projectService, ({ project, location }, getMappedLocation) => { - for (const outputReferencedSymbol of project.getLanguageService().findReferences(location.fileName, location.position) || emptyArray) { - const mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); - const definition: ReferencedSymbolDefinitionInfo = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : { - ...outputReferencedSymbol.definition, - textSpan: createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), - fileName: mappedDefinitionFile.fileName, - }; - let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, definition)); - if (!symbolToAddTo) { - symbolToAddTo = { definition, references: [] }; - outputs.push(symbolToAddTo); - } + combineProjectOutputWorker( + projects, + defaultProject, + initialLocation, + ({ project, location }, getMappedLocation) => { + for (const outputReferencedSymbol of project.getLanguageService().findReferences(location.fileName, location.position) || emptyArray) { + const mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); + const definition: ReferencedSymbolDefinitionInfo = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : { + ...outputReferencedSymbol.definition, + textSpan: createTextSpan(mappedDefinitionFile.position, outputReferencedSymbol.definition.textSpan.length), + fileName: mappedDefinitionFile.fileName, + }; + let symbolToAddTo = find(outputs, o => documentSpansEqual(o.definition, definition)); + if (!symbolToAddTo) { + symbolToAddTo = { definition, references: [] }; + outputs.push(symbolToAddTo); + } - for (const ref of outputReferencedSymbol.references) { - // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. - if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { - symbolToAddTo.references.push(ref); + for (const ref of outputReferencedSymbol.references) { + // If it's in a mapped file, that is added to the todo list by `getMappedLocation`. + if (!contains(symbolToAddTo.references, ref, documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) { + symbolToAddTo.references.push(ref); + } } } - } - }, () => getDefinitionLocation(defaultProject, initialLocation)); + }, + () => getDefinitionLocation(defaultProject, initialLocation) + ); return outputs.filter(o => o.references.length !== 0); } @@ -389,10 +407,10 @@ namespace ts.server { projects: Projects, defaultProject: Project, initialLocation: TLocation, - projectService: ProjectService, cb: CombineProjectOutputCallback, getDefinition: (() => sourcemaps.SourceMappableLocation | undefined) | undefined, ): void { + const projectService = defaultProject.projectService; let toDo: ProjectAndLocation[] | undefined; const seenProjects = createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, (project, path) => { @@ -1208,7 +1226,13 @@ namespace ts.server { const position = this.getPositionInFile(args, file); const projects = this.getProjects(args); - const locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, position }, this.projectService, !!args.findInStrings, !!args.findInComments); + const locations = combineProjectOutputForRenameLocations( + projects, + this.getDefaultProject(args), + { fileName: args.file, position }, + !!args.findInStrings, + !!args.findInComments + ); if (!simplifiedResult) return locations; const defaultProject = this.getDefaultProject(args); @@ -1242,7 +1266,11 @@ namespace ts.server { const file = toNormalizedPath(args.file); const projects = this.getProjects(args); const position = this.getPositionInFile(args, file); - const references = combineProjectOutputForReferences(projects, this.getDefaultProject(args), { fileName: args.file, position }, this.projectService); + const references = combineProjectOutputForReferences( + projects, + this.getDefaultProject(args), + { fileName: args.file, position }, + ); if (simplifiedResult) { const defaultProject = this.getDefaultProject(args); @@ -1749,7 +1777,6 @@ namespace ts.server { return combineProjectOutputWhileOpeningReferencedProjects( this.getProjects(args), this.getDefaultProject(args), - this.projectService, project => project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()), documentSpanLocation, From f97274383d9c31a5dd341d5343dcea425b71729a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 22 Oct 2018 18:06:19 -0700 Subject: [PATCH 247/262] Log project name when removing project --- src/server/editorServices.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index eb9b7118c5f..83e38625e73 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1037,7 +1037,7 @@ namespace ts.server { } private removeProject(project: Project) { - this.logger.info(`remove project: ${project.getRootFiles().toString()}`); + this.logger.info(`remove project: ${project.projectName}\nFiles::${project.getRootFiles().toString()}`); project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { From 41b19309d48584c3131575ea54194bf5656b1915 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 29 Oct 2018 16:32:58 -0700 Subject: [PATCH 248/262] Better project logging --- src/server/editorServices.ts | 27 +++++++++++++-------------- src/server/project.ts | 6 ++++++ 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 83e38625e73..3ea03ff0358 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1037,7 +1037,8 @@ namespace ts.server { } private removeProject(project: Project) { - this.logger.info(`remove project: ${project.projectName}\nFiles::${project.getRootFiles().toString()}`); + this.logger.info("`remove Project::"); + project.print(); project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { @@ -1477,19 +1478,9 @@ namespace ts.server { const writeProjectFileNames = this.logger.hasLevel(LogLevel.verbose); this.logger.startGroup(); - let counter = 0; - const printProjects = (projects: Project[], counter: number): number => { - for (const project of projects) { - this.logger.info(`Project '${project.getProjectName()}' (${ProjectKind[project.projectKind]}) ${counter}`); - this.logger.info(project.filesToString(writeProjectFileNames)); - this.logger.info("-----------------------------------------------"); - counter++; - } - return counter; - }; - counter = printProjects(this.externalProjects, counter); - counter = printProjects(arrayFrom(this.configuredProjects.values()), counter); - printProjects(this.inferredProjects, counter); + let counter = printProjectsWithCounter(this.externalProjects, 0); + counter = printProjectsWithCounter(arrayFrom(this.configuredProjects.values()), counter); + printProjectsWithCounter(this.inferredProjects, counter); this.logger.info("Open files: "); this.openFiles.forEach((projectRootPath, path) => { @@ -2909,4 +2900,12 @@ namespace ts.server { export function isConfigFile(config: ScriptInfoOrConfig): config is TsConfigSourceFile { return (config as TsConfigSourceFile).kind !== undefined; } + + function printProjectsWithCounter(projects: Project[], counter: number) { + for (const project of projects) { + project.print(counter); + counter++; + } + return counter; + } } diff --git a/src/server/project.ts b/src/server/project.ts index 89bac4060bb..7dd8da8a4e0 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -995,6 +995,12 @@ namespace ts.server { return strBuilder; } + print(counter?: number) { + this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]}) ${counter === undefined ? "" : counter}`); + this.writeLog(this.filesToString(this.projectService.logger.hasLevel(LogLevel.verbose))); + this.writeLog("-----------------------------------------------"); + } + setCompilerOptions(compilerOptions: CompilerOptions) { if (compilerOptions) { compilerOptions.allowNonTsExtensions = true; From 89fda5ca83cf69b5107b09f097fb5e7c19038d20 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 8 Nov 2018 12:33:54 -0800 Subject: [PATCH 249/262] Fix enum const initializer visibility painting (#28415) --- src/compiler/checker.ts | 8 ++--- src/compiler/transformers/declarations.ts | 2 +- src/compiler/types.ts | 2 +- ...enumDeclarationEmitInitializerHasImport.js | 35 +++++++++++++++++++ ...eclarationEmitInitializerHasImport.symbols | 22 ++++++++++++ ...mDeclarationEmitInitializerHasImport.types | 22 ++++++++++++ ...enumDeclarationEmitInitializerHasImport.ts | 10 ++++++ .../TypeScript-Node-Starter | 2 +- 8 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 tests/baselines/reference/enumDeclarationEmitInitializerHasImport.js create mode 100644 tests/baselines/reference/enumDeclarationEmitInitializerHasImport.symbols create mode 100644 tests/baselines/reference/enumDeclarationEmitInitializerHasImport.types create mode 100644 tests/cases/compiler/enumDeclarationEmitInitializerHasImport.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 23ccfe95c48..103200600b2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28799,15 +28799,15 @@ namespace ts { return false; } - function literalTypeToNode(type: FreshableType, enclosing: Node): Expression { - const enumResult = type.flags & TypeFlags.EnumLiteral ? nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing) + function literalTypeToNode(type: FreshableType, enclosing: Node, tracker: SymbolTracker): Expression { + const enumResult = type.flags & TypeFlags.EnumLiteral ? nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing, /*flags*/ undefined, tracker) : type === trueType ? createTrue() : type === falseType && createFalse(); return enumResult || createLiteral((type as LiteralType).value); } - function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { + function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type, node); + return literalTypeToNode(type, node, tracker); } function createResolver(): EmitResolver { diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 9ccca4732e8..968b61198a6 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -373,7 +373,7 @@ namespace ts { function ensureNoInitializer(node: CanHaveLiteralInitializer) { if (shouldPrintWithInitializer(node)) { - return resolver.createLiteralConstValue(getParseTreeNode(node) as CanHaveLiteralInitializer); // TODO: Make safe + return resolver.createLiteralConstValue(getParseTreeNode(node) as CanHaveLiteralInitializer, symbolTracker); // TODO: Make safe } return undefined; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 16947eea195..0a5e9d9dbd8 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3500,7 +3500,7 @@ namespace ts { createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): Expression; + createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker): Expression; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags | undefined, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant diff --git a/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.js b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.js new file mode 100644 index 00000000000..88e52659f93 --- /dev/null +++ b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.js @@ -0,0 +1,35 @@ +//// [tests/cases/compiler/enumDeclarationEmitInitializerHasImport.ts] //// + +//// [provider.ts] +export enum Enum { + Value1, + Value2, +} +//// [consumer.ts] +import provider = require('./provider'); + +export const value = provider.Enum.Value1; + +//// [provider.js] +"use strict"; +exports.__esModule = true; +var Enum; +(function (Enum) { + Enum[Enum["Value1"] = 0] = "Value1"; + Enum[Enum["Value2"] = 1] = "Value2"; +})(Enum = exports.Enum || (exports.Enum = {})); +//// [consumer.js] +"use strict"; +exports.__esModule = true; +var provider = require("./provider"); +exports.value = provider.Enum.Value1; + + +//// [provider.d.ts] +export declare enum Enum { + Value1 = 0, + Value2 = 1 +} +//// [consumer.d.ts] +import provider = require('./provider'); +export declare const value = provider.Enum.Value1; diff --git a/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.symbols b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.symbols new file mode 100644 index 00000000000..f101f43ab5b --- /dev/null +++ b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/consumer.ts === +import provider = require('./provider'); +>provider : Symbol(provider, Decl(consumer.ts, 0, 0)) + +export const value = provider.Enum.Value1; +>value : Symbol(value, Decl(consumer.ts, 2, 12)) +>provider.Enum.Value1 : Symbol(provider.Enum.Value1, Decl(provider.ts, 0, 18)) +>provider.Enum : Symbol(provider.Enum, Decl(provider.ts, 0, 0)) +>provider : Symbol(provider, Decl(consumer.ts, 0, 0)) +>Enum : Symbol(provider.Enum, Decl(provider.ts, 0, 0)) +>Value1 : Symbol(provider.Enum.Value1, Decl(provider.ts, 0, 18)) + +=== tests/cases/compiler/provider.ts === +export enum Enum { +>Enum : Symbol(Enum, Decl(provider.ts, 0, 0)) + + Value1, +>Value1 : Symbol(Enum.Value1, Decl(provider.ts, 0, 18)) + + Value2, +>Value2 : Symbol(Enum.Value2, Decl(provider.ts, 1, 11)) +} diff --git a/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.types b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.types new file mode 100644 index 00000000000..19e6a0c658b --- /dev/null +++ b/tests/baselines/reference/enumDeclarationEmitInitializerHasImport.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/consumer.ts === +import provider = require('./provider'); +>provider : typeof provider + +export const value = provider.Enum.Value1; +>value : provider.Enum.Value1 +>provider.Enum.Value1 : provider.Enum.Value1 +>provider.Enum : typeof provider.Enum +>provider : typeof provider +>Enum : typeof provider.Enum +>Value1 : provider.Enum.Value1 + +=== tests/cases/compiler/provider.ts === +export enum Enum { +>Enum : Enum + + Value1, +>Value1 : Enum.Value1 + + Value2, +>Value2 : Enum.Value2 +} diff --git a/tests/cases/compiler/enumDeclarationEmitInitializerHasImport.ts b/tests/cases/compiler/enumDeclarationEmitInitializerHasImport.ts new file mode 100644 index 00000000000..2fe022f17b0 --- /dev/null +++ b/tests/cases/compiler/enumDeclarationEmitInitializerHasImport.ts @@ -0,0 +1,10 @@ +// @declaration: true +// @filename: provider.ts +export enum Enum { + Value1, + Value2, +} +// @filename: consumer.ts +import provider = require('./provider'); + +export const value = provider.Enum.Value1; \ No newline at end of file diff --git a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter index 4779cb7e182..40bdb4eadab 160000 --- a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter +++ b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter @@ -1 +1 @@ -Subproject commit 4779cb7e182cf41d5c62289bb80d2850e0265b71 +Subproject commit 40bdb4eadabc9fbed7d83e3f26817a931c0763b6 From 55fb052d7a6e9070e295219cc69c9d53e45911b4 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 7 Nov 2018 14:55:19 -0800 Subject: [PATCH 250/262] Allow creation of relative path file infos only for open script infos Fixes #20476 --- src/server/editorServices.ts | 19 +++++++-- .../unittests/tsserverProjectSystem.ts | 41 +++++++++++++++---- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 3ea03ff0358..7009619b26d 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -2109,7 +2109,20 @@ namespace ts.server { } private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined, hostToQueryFileExistsOn: DirectoryStructureHost | undefined) { - return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) { + return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn); + } + + // This is non rooted path with different current directory than project service current directory + // Only paths recognized are open relative file paths + const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); + if (info) { + return info; + } + + // This means triple slash references wont be resolved in dynamic and unsaved files + // which is intentional since we dont know what it means to be relative to non disk files + return undefined; } private getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName: NormalizedPath, currentDirectory: string, fileContent: string | undefined, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined) { @@ -2126,7 +2139,7 @@ namespace ts.server { let info = this.getScriptInfoForPath(path); if (!info) { const isDynamic = isDynamicFileName(fileName); - Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nScript info with non-dynamic relative file name can only be open script info`); + Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`); Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names`); Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })}\nDynamic files must always have current directory context since containing external project name will always match the script info name.`); // If the file is not opened by client and the file doesnot exist on the disk, return @@ -2139,7 +2152,7 @@ namespace ts.server { if (!openedByClient) { this.watchClosedScriptInfo(info); } - else if (!isRootedDiskPath(fileName) && currentDirectory !== this.currentDirectory) { + else if (!isRootedDiskPath(fileName) && !isDynamic) { // File that is opened by user but isn't rooted disk path this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); } diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 31ca9403215..a113ea14d74 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -3301,7 +3301,7 @@ namespace ts.projectSystem { }); }); - it("dynamic file with reference paths external project", () => { + it("dynamic file with reference paths without external project", () => { const file: File = { path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", content: `/// @@ -3899,18 +3899,30 @@ var x = 10;` describe("when opening new file that doesnt exist on disk yet", () => { function verifyNonExistentFile(useProjectRoot: boolean) { - const host = createServerHost([libFile]); + const folderPath = "/user/someuser/projects/someFolder"; + const fileInRoot: File = { + path: `/src/somefile.d.ts`, + content: "class c { }" + }; + const fileInProjectRoot: File = { + path: `${folderPath}/src/somefile.d.ts`, + content: "class c { }" + }; + const host = createServerHost([libFile, fileInRoot, fileInProjectRoot]); const { hasError, errorLogger } = createErrorLogger(); const session = createSession(host, { canUseEvents: true, logger: errorLogger, useInferredProjectPerProjectRoot: true }); - const folderPath = "/user/someuser/projects/someFolder"; const projectService = session.getProjectService(); const untitledFile = "untitled:Untitled-1"; + const refPathNotFound1 = "../../../../../../typings/@epic/Core.d.ts"; + const refPathNotFound2 = "./src/somefile.d.ts"; + const fileContent = `/// +/// `; session.executeCommandSeq({ command: server.CommandNames.Open, arguments: { file: untitledFile, - fileContent: `/// `, + fileContent, scriptKindName: "TS", projectRootPath: useProjectRoot ? folderPath : undefined } @@ -3918,6 +3930,8 @@ var x = 10;` checkNumberOfProjects(projectService, { inferredProjects: 1 }); const infoForUntitledAtProjectRoot = projectService.getScriptInfoForPath(`${folderPath.toLowerCase()}/${untitledFile.toLowerCase()}` as Path); const infoForUnitiledAtRoot = projectService.getScriptInfoForPath(`/${untitledFile.toLowerCase()}` as Path); + const infoForSomefileAtProjectRoot = projectService.getScriptInfoForPath(`/${folderPath.toLowerCase()}/src/somefile.d.ts` as Path); + const infoForSomefileAtRoot = projectService.getScriptInfoForPath(`${fileInRoot.path.toLowerCase()}` as Path); if (useProjectRoot) { assert.isDefined(infoForUntitledAtProjectRoot); assert.isUndefined(infoForUnitiledAtRoot); @@ -3926,7 +3940,11 @@ var x = 10;` assert.isDefined(infoForUnitiledAtRoot); assert.isUndefined(infoForUntitledAtProjectRoot); } - host.checkTimeoutQueueLength(2); + assert.isUndefined(infoForSomefileAtRoot); + assert.isUndefined(infoForSomefileAtProjectRoot); + + // Since this is not js project so no typings are queued + host.checkTimeoutQueueLength(0); const newTimeoutId = host.getNextTimeoutId(); const expectedSequenceId = session.getNextSeq(); @@ -3937,19 +3955,26 @@ var x = 10;` files: [untitledFile] } }); - host.checkTimeoutQueueLength(3); + host.checkTimeoutQueueLength(1); // Run the last one = get error request host.runQueuedTimeoutCallbacks(newTimeoutId); assert.isFalse(hasError()); - host.checkTimeoutQueueLength(2); + host.checkTimeoutQueueLength(0); checkErrorMessage(session, "syntaxDiag", { file: untitledFile, diagnostics: [] }); session.clearMessages(); host.runQueuedImmediateCallbacks(); assert.isFalse(hasError()); - checkErrorMessage(session, "semanticDiag", { file: untitledFile, diagnostics: [] }); + const errorOffset = fileContent.indexOf(refPathNotFound1) + 1; + checkErrorMessage(session, "semanticDiag", { + file: untitledFile, + diagnostics: [ + createDiagnostic({ line: 1, offset: errorOffset }, { line: 1, offset: errorOffset + refPathNotFound1.length }, Diagnostics.File_0_not_found, [refPathNotFound1], "error"), + createDiagnostic({ line: 2, offset: errorOffset }, { line: 2, offset: errorOffset + refPathNotFound2.length }, Diagnostics.File_0_not_found, [refPathNotFound2.substr(2)], "error") + ] + }); session.clearMessages(); host.runQueuedImmediateCallbacks(1); From 8dd05d5858b100325ab7c2f96afd58922a274436 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 8 Nov 2018 13:01:22 -0800 Subject: [PATCH 251/262] Fix public API --- src/server/project.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/server/project.ts b/src/server/project.ts index 7dd8da8a4e0..0fddd3835ed 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -995,6 +995,7 @@ namespace ts.server { return strBuilder; } + /*@internal*/ print(counter?: number) { this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]}) ${counter === undefined ? "" : counter}`); this.writeLog(this.filesToString(this.projectService.logger.hasLevel(LogLevel.verbose))); From bcc4e648321f78a4ea75b2daf99c8742e1c2e61e Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Thu, 8 Nov 2018 23:36:54 +0100 Subject: [PATCH 252/262] revert changes to tsbuild.ts --- src/compiler/tsbuild.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 9e1c7c1bf42..4b9e75102b6 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -22,9 +22,9 @@ namespace ts { force?: boolean; verbose?: boolean; - clean?: boolean; - watch?: boolean; - help?: boolean; + /*@internal*/ clean?: boolean; + /*@internal*/ watch?: boolean; + /*@internal*/ help?: boolean; preserveWatchOutput?: boolean; listEmittedFiles?: boolean; @@ -340,18 +340,18 @@ namespace ts { cleanAllProjects(): ExitStatus; // TODO:: All the below ones should technically only be in watch mode. but thats for later time - resolveProjectName(name: string): ResolvedConfigFileName; - getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; - getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; + /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; + /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; + /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; - invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; - buildInvalidatedProject(): void; + /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; + /*@internal*/ buildInvalidatedProject(): void; - resetBuildContext(opts?: BuildOptions): void; + /*@internal*/ resetBuildContext(opts?: BuildOptions): void; } export interface SolutionBuilderWithWatch extends SolutionBuilder { - startWatching(): void; + /*@internal*/ startWatching(): void; } /** From 7bfc2c8113c9558614c2480e46141f0363477fd7 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 8 Nov 2018 14:56:10 -0800 Subject: [PATCH 253/262] Elaborate assert of infos attached to project --- src/server/editorServices.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 7009619b26d..6ce086a7fc8 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1042,7 +1042,7 @@ namespace ts.server { project.close(); if (Debug.shouldAssert(AssertionLevel.Normal)) { - this.filenameToScriptInfo.forEach(info => Debug.assert(!info.isAttached(project))); + 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))}`)); } // Remove the project from pending project updates this.pendingProjectUpdates.delete(project.getProjectName()); From 23b7284ca3e24462da78528665622c694acb9833 Mon Sep 17 00:00:00 2001 From: csigs Date: Fri, 9 Nov 2018 04:10:18 +0000 Subject: [PATCH 254/262] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 20276 ++++++++-------- 1 file changed, 10138 insertions(+), 10138 deletions(-) diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9d03da8d9b3..0078e878dbc 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10139 +1,10139 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - 형식이어야 합니다.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()'를 사용하세요.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + 또는 - 형식이어야 합니다. 예를 들어 '{0}' 또는 '{1}'입니다.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + 형식이어야 합니다.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()'를 사용하세요.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From e6e71978df30e407d51c6c6412c0841fe2e3a6d4 Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Fri, 19 Oct 2018 15:55:34 +0200 Subject: [PATCH 255/262] Correct codefix by removing private modifier In case of private attribute and private constructor parameter with assignment in the constructor body, the parameter is flagged as unused. This is caused by the private modifier which is shadowed by the explicity assignment in the body. This commit updates the codefix to just remove the private modifier in this cases. Closes #24931 --- src/services/codefixes/fixUnusedIdentifier.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 2905f0b131b..d31fe739d2b 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,8 +200,14 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { - changes.delete(sourceFile, p); - deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + const privateModifier = ts.findModifier(p, ts.SyntaxKind.PrivateKeyword); + if (privateModifier) { + changes.deleteModifier(sourceFile, p.modifiers![0]); + } + else { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); + } } } From de7faa1b7e1f0d48a7f7ec79cf2ec747e91c6097 Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Fri, 19 Oct 2018 16:32:19 +0200 Subject: [PATCH 256/262] Remove obsolte ts namespace --- src/services/codefixes/fixUnusedIdentifier.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index d31fe739d2b..5b59f4baedd 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,7 +200,7 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { - const privateModifier = ts.findModifier(p, ts.SyntaxKind.PrivateKeyword); + const privateModifier = findModifier(p, SyntaxKind.PrivateKeyword); if (privateModifier) { changes.deleteModifier(sourceFile, p.modifiers![0]); } From d411fa34a7b771b9682ff6b39bec96f61ff16588 Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Fri, 19 Oct 2018 17:17:45 +0200 Subject: [PATCH 257/262] Add test case for codeFix --- ...eFixUnusedIdentifier_parameter_modifier.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts new file mode 100644 index 00000000000..cc9f37e61b0 --- /dev/null +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts @@ -0,0 +1,22 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true + +////export class Example { +//// prop: any; +//// constructor(private arg: any) { +//// this.prop = arg; +//// } +////} + +verify.codeFix({ + description: "Remove declaration for: 'arg'", + newFileContent: +`export class Example { + prop: any; + constructor(arg: any) { + this.prop = arg; + } +}`, +}); From 13e85ac3a949183b0ffff54b0e9250887c91828b Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Fri, 2 Nov 2018 15:05:04 +0100 Subject: [PATCH 258/262] add more modifiers --- src/services/codefixes/fixUnusedIdentifier.ts | 9 ++++++--- .../codeFixUnusedIdentifier_parameter_modifier.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 5b59f4baedd..b41c5f52ee0 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,9 +200,12 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { - const privateModifier = findModifier(p, SyntaxKind.PrivateKeyword); - if (privateModifier) { - changes.deleteModifier(sourceFile, p.modifiers![0]); + const modifiers: Modifier["kind"][] = [SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ReadonlyKeyword]; + const foundModifiers = modifiers.map(modifier => findModifier(p, modifier)).filter(modifier => modifier !== undefined); + if (foundModifiers.length > 0) { + foundModifiers.forEach(modifier => { + changes.deleteModifier(sourceFile, modifier!); + }); } else { changes.delete(sourceFile, p); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts index cc9f37e61b0..5f544df5c2e 100644 --- a/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier.ts @@ -5,7 +5,7 @@ ////export class Example { //// prop: any; -//// constructor(private arg: any) { +//// constructor(private readonly arg: any) { //// this.prop = arg; //// } ////} From 6bd298b8841a67a297e083be3e73e99443f22460 Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Mon, 5 Nov 2018 18:07:29 +0100 Subject: [PATCH 259/262] add test for remove modifier and parameter --- src/services/codefixes/fixUnusedIdentifier.ts | 9 ++++----- ...sedIdentifier_parameter_modifier_and_arg.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) create mode 100644 tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier_and_arg.ts diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index b41c5f52ee0..d30e8509b07 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,11 +200,10 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { - const modifiers: Modifier["kind"][] = [SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ReadonlyKeyword]; - const foundModifiers = modifiers.map(modifier => findModifier(p, modifier)).filter(modifier => modifier !== undefined); - if (foundModifiers.length > 0) { - foundModifiers.forEach(modifier => { - changes.deleteModifier(sourceFile, modifier!); + if (p.modifiers && p.modifiers.length > 0 + && (!isIdentifier(p.name) || FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + p.modifiers.forEach(modifier => { + changes.deleteModifier(sourceFile, modifier); }); } else { diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier_and_arg.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier_and_arg.ts new file mode 100644 index 00000000000..0f33db06dfa --- /dev/null +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_parameter_modifier_and_arg.ts @@ -0,0 +1,18 @@ +/// + +// @noUnusedLocals: true +// @noUnusedParameters: true + +////export class Example { +//// constructor(private readonly arg: any) { +//// } +////} + +verify.codeFix({ + description: "Remove declaration for: 'arg'", + newFileContent: +`export class Example { + constructor() { + } +}`, +}); From 499bed540bafd675472aebad63ce1ae016680100 Mon Sep 17 00:00:00 2001 From: Markus Wolf Date: Fri, 9 Nov 2018 09:45:20 +0100 Subject: [PATCH 260/262] Better reference usage detection --- src/services/codefixes/fixUnusedIdentifier.ts | 6 +++--- src/services/findAllReferences.ts | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index d30e8509b07..de071ded24c 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -181,8 +181,8 @@ namespace ts.codefix { function deleteAssignments(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Identifier, checker: TypeChecker) { FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref: Node) => { - if (ref.parent.kind === SyntaxKind.PropertyAccessExpression) ref = ref.parent; - if (ref.parent.kind === SyntaxKind.BinaryExpression && ref.parent.parent.kind === SyntaxKind.ExpressionStatement) { + if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; + if (isBinaryExpression(ref.parent) && isExpressionStatement(ref.parent.parent) && ref.parent.left === ref) { changes.delete(sourceFile, ref.parent.parent); } }); @@ -201,7 +201,7 @@ namespace ts.codefix { function tryDeleteParameter(changes: textChanges.ChangeTracker, sourceFile: SourceFile, p: ParameterDeclaration, checker: TypeChecker, sourceFiles: ReadonlyArray, isFixAll: boolean): void { if (mayDeleteParameter(p, checker, isFixAll)) { if (p.modifiers && p.modifiers.length > 0 - && (!isIdentifier(p.name) || FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { + && (!isIdentifier(p.name) || FindAllReferences.Core.isSymbolReferencedInFile(p.name, checker, sourceFile))) { p.modifiers.forEach(modifier => { changes.deleteModifier(sourceFile, modifier); }); diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index b7ded40c28f..30b69c7ce19 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -839,7 +839,9 @@ namespace ts.FindAllReferences.Core { } export function eachSymbolReferenceInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile, cb: (token: Identifier) => T): T | undefined { - const symbol = checker.getSymbolAtLocation(definition); + const symbol = isParameterPropertyDeclaration(definition.parent) + ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) + : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) { if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; From 9dbe037e8420ef456627d719aa73c2c98a9f9d1b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 9 Nov 2018 09:22:39 -0800 Subject: [PATCH 261/262] Use seen map to avoid circular transitive exports to cause stack over flow Fixes #28433 --- src/compiler/builder.ts | 19 +++++--- src/testRunner/unittests/tscWatchMode.ts | 55 ++++++++++++++++++------ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 0fe147def8c..2de77fa5545 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -201,12 +201,13 @@ namespace ts { } Debug.assert(!!state.currentAffectedFilesExportedModulesMap); + const seenFileAndExportsOfFile = createMap(); // Go through exported modules from cache first // If exported modules has path, all files referencing file exported from are affected if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => exportedModules && exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) )) { return; } @@ -215,7 +216,7 @@ namespace ts { forEachEntry(state.exportedModulesMap, (exportedModules, exportedFromPath) => !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(affectedFile.path) && - removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile) ); } @@ -223,16 +224,20 @@ namespace ts { * removes the semantic diagnostics of files referencing referencedPath and * returns true if there are no more semantic diagnostics from old state */ - function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path) { + function removeSemanticDiagnosticsOfFilesReferencingPath(state: BuilderProgramState, referencedPath: Path, seenFileAndExportsOfFile: Map) { return forEachEntry(state.referencedMap!, (referencesInFile, filePath) => - referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath as Path) + referencesInFile.has(referencedPath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, filePath as Path, seenFileAndExportsOfFile) ); } /** * Removes semantic diagnostics of file and anything that exports this file */ - function removeSemanticDiagnosticsOfFileAndExportsOfFile(state: BuilderProgramState, filePath: Path): boolean { + function removeSemanticDiagnosticsOfFileAndExportsOfFile(state: BuilderProgramState, filePath: Path, seenFileAndExportsOfFile: Map): boolean { + if (!addToSeen(seenFileAndExportsOfFile, filePath)) { + return false; + } + if (removeSemanticDiagnosticsOf(state, filePath)) { // If there are no more diagnostics from old cache, done return true; @@ -244,7 +249,7 @@ namespace ts { if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) => exportedModules && exportedModules.has(filePath) && - removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) )) { return true; } @@ -253,7 +258,7 @@ namespace ts { return !!forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) => !state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && - removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path) + removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile) ); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index 6280823d860..f77b4bce0eb 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -1473,7 +1473,7 @@ foo().hello` checkOutputErrorsIncremental(host, emptyArray); }); - it("updates errors when file transitively exported file changes", () => { + describe("updates errors when file transitively exported file changes", () => { const projectLocation = "/user/username/projects/myproject"; const config: File = { path: `${projectLocation}/tsconfig.json`, @@ -1521,19 +1521,48 @@ export class Data { title: string; }` }; - const filesWithoutConfig = [libFile, app, lib2Public, lib2Data, lib1Public, lib1ToolsPublic, lib1ToolsInterface]; - const files = [config, ...filesWithoutConfig]; - const host = createWatchedSystem(files, { currentDirectory: projectLocation }); - const watch = createWatchOfConfigFile(config.path, host); - checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); - checkOutputErrorsInitial(host, emptyArray); - host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")); - host.checkTimeoutQueueLengthAndRun(1); - checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); - checkOutputErrorsIncremental(host, [ - "lib2/data.ts(5,13): error TS2322: Type '{ title: string; }' is not assignable to type 'ITest'.\n Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?\n" - ]); + function verifyTransitiveExports(filesWithoutConfig: ReadonlyArray) { + const files = [config, ...filesWithoutConfig]; + const host = createWatchedSystem(files, { currentDirectory: projectLocation }); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsInitial(host, emptyArray); + + host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsIncremental(host, [ + "lib2/data.ts(5,13): error TS2322: Type '{ title: string; }' is not assignable to type 'ITest'.\n Object literal may only specify known properties, but 'title' does not exist in type 'ITest'. Did you mean to write 'title2'?\n" + ]); + + } + it("when there are no circular import and exports", () => { + verifyTransitiveExports([libFile, app, lib2Public, lib2Data, lib1Public, lib1ToolsPublic, lib1ToolsInterface]); + }); + + it("when there are circular import and exports", () => { + const lib2Data: File = { + path: `${projectLocation}/lib2/data.ts`, + content: `import { ITest } from "lib1/public"; import { Data2 } from "./data2"; +export class Data { + public dat?: Data2; public test() { + const result: ITest = { + title: "title" + } + return result; + } +}` + }; + const lib2Data2: File = { + path: `${projectLocation}/lib2/data2.ts`, + content: `import { Data } from "./data"; +export class Data2 { + public dat?: Data; +}` + }; + verifyTransitiveExports([libFile, app, lib2Public, lib2Data, lib2Data2, lib1Public, lib1ToolsPublic, lib1ToolsInterface]); + }); }); }); From aaf1d8055bef0d1128db52dc57ed7a6dac110c97 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 9 Nov 2018 09:38:45 -0800 Subject: [PATCH 262/262] Support finding references at `module` in `module.exports =` or `export` in `export =` (#28221) * Support finding references at `module` in `module.exports =` or `export` in `export =` * Add json test --- src/compiler/checker.ts | 3 +++ src/services/findAllReferences.ts | 20 ++++++++++++++++ .../fourslash/findAllRefsExportEquals.ts | 17 ++++++------- .../findAllRefsImportEqualsJsonFile.ts | 24 +++++++++++++++++++ .../fourslash/findAllRefsModuleDotExports.ts | 11 +++++++++ .../findAllRefs_importType_exportEquals.ts | 13 +++++----- .../fourslash/findAllRefs_importType_js.ts | 7 +++--- tests/cases/fourslash/fourslash.ts | 6 ++++- 8 files changed, 82 insertions(+), 19 deletions(-) create mode 100644 tests/cases/fourslash/findAllRefsImportEqualsJsonFile.ts create mode 100644 tests/cases/fourslash/findAllRefsModuleDotExports.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 103200600b2..4f04c6f8e82 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28100,6 +28100,9 @@ namespace ts { case SyntaxKind.ImportType: return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + case SyntaxKind.ExportKeyword: + return isExportAssignment(node.parent) ? Debug.assertDefined(node.parent.symbol) : undefined; + default: return undefined; } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 30b69c7ce19..16e34565b7e 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -368,6 +368,10 @@ namespace ts.FindAllReferences.Core { return !options.implementations && isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } + if (symbol.escapedName === InternalSymbolName.ExportEquals) { + return getReferencedSymbolsForModule(program, symbol.parent!, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); + } + let moduleReferences: SymbolAndEntries[] = emptyArray; const moduleSourceFile = isModuleSymbol(symbol); let referencedNode: Node | undefined = node; @@ -427,6 +431,22 @@ namespace ts.FindAllReferences.Core { } } + const exported = symbol.exports!.get(InternalSymbolName.ExportEquals); + if (exported) { + for (const decl of exported.declarations) { + const sourceFile = decl.getSourceFile(); + if (sourceFilesSet.has(sourceFile.fileName)) { + // At `module.exports = ...`, reference node is `module` + const node = isBinaryExpression(decl) && isPropertyAccessExpression(decl.left) + ? decl.left.expression + : isExportAssignment(decl) + ? Debug.assertDefined(findChildOfKind(decl, SyntaxKind.ExportKeyword, sourceFile)) + : getNameOfDeclaration(decl) || decl; + references.push(nodeEntry(node)); + } + } + } + return references.length ? [{ definition: { type: DefinitionKind.Symbol, symbol }, references }] : emptyArray; } diff --git a/tests/cases/fourslash/findAllRefsExportEquals.ts b/tests/cases/fourslash/findAllRefsExportEquals.ts index 6bbdc613554..3580c8fe4ee 100644 --- a/tests/cases/fourslash/findAllRefsExportEquals.ts +++ b/tests/cases/fourslash/findAllRefsExportEquals.ts @@ -2,15 +2,16 @@ // @Filename: /a.ts ////type [|{| "isWriteAccess": true, "isDefinition": true |}T|] = number; -////export = [|T|]; +////[|export|] = [|T|]; // @Filename: /b.ts ////import [|{| "isWriteAccess": true, "isDefinition": true |}T|] = require("[|./a|]"); -const [r0, r1, r2, r3] = test.ranges(); -const mod = { definition: 'module "/a"', ranges: [r3] }; -const a = { definition: "type T = number", ranges: [r0, r1] }; -const b = { definition: '(alias) type T = number\nimport T = require("./a")', ranges: [r2] }; -verify.referenceGroups([r0, r1], [a, b]); -verify.referenceGroups(r2, [b, a]); -verify.referenceGroups(r3, [mod, a, b]); +const [r0, r1, r2, r3, r4] = test.ranges(); +const mod = { definition: 'module "/a"', ranges: [r4, r1] }; +const a = { definition: "type T = number", ranges: [r0, r2] }; +const b = { definition: '(alias) type T = number\nimport T = require("./a")', ranges: [r3] }; +verify.referenceGroups([r0, r2], [a, b]); +verify.referenceGroups(r3, [b, a]); +verify.referenceGroups(r4, [mod, a, b]); +verify.referenceGroups(r1, [mod]); diff --git a/tests/cases/fourslash/findAllRefsImportEqualsJsonFile.ts b/tests/cases/fourslash/findAllRefsImportEqualsJsonFile.ts new file mode 100644 index 00000000000..3c3c0dbb2e4 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsImportEqualsJsonFile.ts @@ -0,0 +1,24 @@ +/// + +// @allowJs: true +// @checkJs: true +// @resolveJsonModule: true + +// @Filename: /a.ts +////import [|{| "isWriteAccess": true, "isDefinition": true |}j|] = require("[|./j.json|]"); +////[|j|]; + +// @Filename: /b.js +////const [|{| "isWriteAccess": true, "isDefinition": true |}j|] = require("[|./j.json|]"); +////[|j|]; + +// @Filename: /j.json +////[|{ "x": 0 }|] + +verify.noErrors(); + +const [r0, r1, r2, r3, r4, r5, r6] = test.ranges(); +verify.singleReferenceGroup('import j = require("./j.json")', [r0, r2]); +verify.referenceGroups([r1, r4], [{ definition: 'module "/j"', ranges: [r1, r4, r6] }]); +verify.singleReferenceGroup('const j: {\n "x": number;\n}', [r3, r5]); +verify.referenceGroups(r6, undefined); diff --git a/tests/cases/fourslash/findAllRefsModuleDotExports.ts b/tests/cases/fourslash/findAllRefsModuleDotExports.ts new file mode 100644 index 00000000000..bc1bd705c2f --- /dev/null +++ b/tests/cases/fourslash/findAllRefsModuleDotExports.ts @@ -0,0 +1,11 @@ +/// + +// @allowJs: true + +// @Filename: /a.js +////const b = require("[|./b|]"); + +// @Filename: /b.js +////[|module|].exports = 0; + +verify.singleReferenceGroup('module "/b"') diff --git a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts index 7fe0696f952..496fa8a9d3b 100644 --- a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts +++ b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts @@ -5,7 +5,7 @@ ////namespace [|{| "isWriteAccess": true, "isDefinition": true |}T|] { //// export type U = string; ////} -////export = [|T|]; +////[|export|] = [|T|]; // @Filename: /b.ts ////const x: import("[|./[|a|]|]") = 0; @@ -13,14 +13,13 @@ verify.noErrors(); -const [r0, r1, r2, r3, r3b, r4, r4b] = test.ranges(); +const [r0, r1, rExport, r2, r3, r3b, r4, r4b] = test.ranges(); verify.referenceGroups(r0, [{ definition: "type T = number\nnamespace T", ranges: [r0, r2, r3] }]); verify.referenceGroups(r1, [{ definition: "namespace T", ranges: [r1, r2] }]); -verify.referenceGroups(r2, [{ definition: "type T = number\nnamespace T", ranges: [r0, r1, r2, r3] }]); -verify.referenceGroups([r3, r4], [ - { definition: 'module "/a"', ranges: [r4] }, - { definition: "type T = number\nnamespace T", ranges: [r0, r1, r2, r3] }, -]); +const t: FourSlashInterface.ReferenceGroup = { definition: "type T = number\nnamespace T", ranges: [r0, r1, r2, r3] }; +verify.referenceGroups(r2, [t]); +verify.referenceGroups([r3, r4], [{ definition: 'module "/a"', ranges: [r4, rExport] }, t]); +verify.referenceGroups(rExport, [{ definition: 'module "/a"', ranges: [r3, r4, rExport] }]); verify.renameLocations(r0, [r0, r2]); verify.renameLocations(r1, [r1, r2]); diff --git a/tests/cases/fourslash/findAllRefs_importType_js.ts b/tests/cases/fourslash/findAllRefs_importType_js.ts index 863ee05b12f..b1f612c8e45 100644 --- a/tests/cases/fourslash/findAllRefs_importType_js.ts +++ b/tests/cases/fourslash/findAllRefs_importType_js.ts @@ -4,7 +4,7 @@ // @checkJs: true // @Filename: /a.js -////module.exports = class [|{| "isWriteAccess": true, "isDefinition": true |}C|] {}; +////[|module|].exports = class [|{| "isWriteAccess": true, "isDefinition": true |}C|] {}; ////module.exports.[|{| "isWriteAccess": true, "isDefinition": true |}D|] = class [|{| "isWriteAccess": true, "isDefinition": true |}D|] {}; // @Filename: /b.js @@ -17,7 +17,8 @@ verify.noErrors(); // TODO: GH#24025 -const [r0, r1, r2, r3, r4, r5] = test.ranges(); +const [rModule, r0, r1, r2, r3, r4, r5] = test.ranges(); +verify.referenceGroups(rModule, [{ definition: 'module "/a"', ranges: [r3, r4, rModule] }]); verify.referenceGroups(r0, [ { definition: "(local class) C", ranges: [r0] }, // TODO: This definition is really ugly @@ -31,7 +32,7 @@ verify.referenceGroups(r2, [ { definition: "class D\n(property) D: typeof D", ranges: [r5] }, ]); verify.referenceGroups([r3, r4], [ - { definition: 'module "/a"', ranges: [r4] }, + { definition: 'module "/a"', ranges: [r4, rModule] }, { definition: "(local class) C", ranges: [r0] }, { definition: "(alias) (local class) export=\nimport export=", ranges: [r3] }, ]); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index ddf55fb41b5..b6df330b85c 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -231,7 +231,7 @@ declare namespace FourSlashInterface { * For each of starts, asserts the ranges that are referenced from there. * This uses the 'findReferences' command instead of 'getReferencesAtPosition', so references are grouped by their definition. */ - referenceGroups(starts: ArrayOrSingle | ArrayOrSingle, parts: Array<{ definition: ReferencesDefinition, ranges: Range[] }>): void; + referenceGroups(starts: ArrayOrSingle | ArrayOrSingle, parts: ReadonlyArray): void; singleReferenceGroup(definition: ReferencesDefinition, ranges?: Range[]): void; rangesAreOccurrences(isWriteAccess?: boolean): void; rangesWithSameTextAreRenameLocations(): void; @@ -487,6 +487,10 @@ declare namespace FourSlashInterface { }; } + interface ReferenceGroup { + readonly definition: ReferencesDefinition; + readonly ranges: ReadonlyArray; + } type ReferencesDefinition = string | { text: string; range: Range;